wsl.rs

  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, Task};
 10use release_channel::{AppVersion, ReleaseChannel};
 11use rpc::proto::Envelope;
 12use semver::Version;
 13use smol::{fs, process};
 14use std::{
 15    ffi::OsStr,
 16    fmt::Write as _,
 17    path::{Path, PathBuf},
 18    process::Stdio,
 19    sync::Arc,
 20    time::Instant,
 21};
 22use util::{
 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    has_wsl_interop: bool,
 51    connection_options: WslConnectionOptions,
 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) =
 66            cx.update(|cx| (ReleaseChannel::global(cx), AppVersion::global(cx)))?;
 67
 68        let mut this = Self {
 69            connection_options,
 70            remote_binary_path: None,
 71            platform: RemotePlatform { os: "", arch: "" },
 72            shell: String::new(),
 73            shell_kind: ShellKind::Posix,
 74            default_system_shell: String::from("/bin/sh"),
 75            has_wsl_interop: false,
 76        };
 77        delegate.set_status(Some("Detecting WSL environment"), cx);
 78        this.shell = this
 79            .detect_shell()
 80            .await
 81            .context("failed detecting shell")?;
 82        log::info!("Remote shell discovered: {}", this.shell);
 83        this.shell_kind = ShellKind::new(&this.shell, false);
 84        this.has_wsl_interop = this.detect_has_wsl_interop().await.unwrap_or_default();
 85        log::info!(
 86            "Remote has wsl interop {}",
 87            if this.has_wsl_interop {
 88                "enabled"
 89            } else {
 90                "disabled"
 91            }
 92        );
 93        this.platform = this
 94            .detect_platform()
 95            .await
 96            .context("failed detecting platform")?;
 97        log::info!("Remote platform discovered: {:?}", this.platform);
 98        this.remote_binary_path = Some(
 99            this.ensure_server_binary(&delegate, release_channel, version, cx)
100                .await
101                .context("failed ensuring server binary")?,
102        );
103        log::debug!("Detected WSL environment: {this:#?}");
104
105        Ok(this)
106    }
107
108    async fn detect_platform(&self) -> Result<RemotePlatform> {
109        let program = self.shell_kind.prepend_command_prefix("uname");
110        let arch_str = self.run_wsl_command_with_output(&program, &["-m"]).await?;
111        let arch_str = arch_str.trim().to_string();
112        let arch = match arch_str.as_str() {
113            "x86_64" => "x86_64",
114            "aarch64" | "arm64" => "aarch64",
115            _ => "x86_64",
116        };
117        Ok(RemotePlatform { os: "linux", arch })
118    }
119
120    async fn detect_shell(&self) -> Result<String> {
121        Ok(self
122            .run_wsl_command_with_output("sh", &["-c", "echo $SHELL"])
123            .await
124            .inspect_err(|err| log::error!("Failed to detect remote shell: {err}"))
125            .ok()
126            .unwrap_or_else(|| "/bin/sh".to_string()))
127    }
128
129    async fn detect_has_wsl_interop(&self) -> Result<bool> {
130        Ok(self
131            .run_wsl_command_with_output("cat", &["/proc/sys/fs/binfmt_misc/WSLInterop"])
132            .await
133            .inspect_err(|err| log::error!("Failed to detect wsl interop: {err}"))?
134            .contains("enabled"))
135    }
136
137    async fn windows_path_to_wsl_path(&self, source: &Path) -> Result<String> {
138        windows_path_to_wsl_path_impl(&self.connection_options, source).await
139    }
140
141    async fn run_wsl_command_with_output(&self, program: &str, args: &[&str]) -> Result<String> {
142        run_wsl_command_with_output_impl(&self.connection_options, program, args).await
143    }
144
145    async fn run_wsl_command(&self, program: &str, args: &[&str]) -> Result<()> {
146        run_wsl_command_impl(&self.connection_options, program, args, false)
147            .await
148            .map(|_| ())
149    }
150
151    async fn ensure_server_binary(
152        &self,
153        delegate: &Arc<dyn RemoteClientDelegate>,
154        release_channel: ReleaseChannel,
155        version: Version,
156        cx: &mut AsyncApp,
157    ) -> Result<Arc<RelPath>> {
158        let version_str = match release_channel {
159            ReleaseChannel::Dev => "build".to_string(),
160            _ => version.to_string(),
161        };
162
163        let binary_name = format!(
164            "zed-remote-server-{}-{}",
165            release_channel.dev_name(),
166            version_str
167        );
168
169        let dst_path =
170            paths::remote_wsl_server_dir_relative().join(RelPath::unix(&binary_name).unwrap());
171
172        if let Some(parent) = dst_path.parent() {
173            let parent = parent.display(PathStyle::Posix);
174            let mkdir = self.shell_kind.prepend_command_prefix("mkdir");
175            self.run_wsl_command(&mkdir, &["-p", &parent])
176                .await
177                .map_err(|e| anyhow!("Failed to create directory: {}", e))?;
178        }
179
180        #[cfg(debug_assertions)]
181        if let Some(remote_server_path) =
182            super::build_remote_server_from_source(&self.platform, delegate.as_ref(), cx).await?
183        {
184            let tmp_path = paths::remote_wsl_server_dir_relative().join(
185                &RelPath::unix(&format!(
186                    "download-{}-{}",
187                    std::process::id(),
188                    remote_server_path.file_name().unwrap().to_string_lossy()
189                ))
190                .unwrap(),
191            );
192            self.upload_file(&remote_server_path, &tmp_path, delegate, cx)
193                .await?;
194            self.extract_and_install(&tmp_path, &dst_path, delegate, cx)
195                .await?;
196            return Ok(dst_path);
197        }
198
199        if self
200            .run_wsl_command(&dst_path.display(PathStyle::Posix), &["version"])
201            .await
202            .is_ok()
203        {
204            return Ok(dst_path);
205        }
206
207        let wanted_version = match release_channel {
208            ReleaseChannel::Nightly | ReleaseChannel::Dev => None,
209            _ => Some(cx.update(|cx| AppVersion::global(cx))?),
210        };
211
212        let src_path = delegate
213            .download_server_binary_locally(self.platform, release_channel, wanted_version, cx)
214            .await?;
215
216        let tmp_path = format!(
217            "{}.{}.gz",
218            dst_path.display(PathStyle::Posix),
219            std::process::id()
220        );
221        let tmp_path = RelPath::unix(&tmp_path).unwrap();
222
223        self.upload_file(&src_path, &tmp_path, delegate, cx).await?;
224        self.extract_and_install(&tmp_path, &dst_path, delegate, cx)
225            .await?;
226
227        Ok(dst_path)
228    }
229
230    async fn upload_file(
231        &self,
232        src_path: &Path,
233        dst_path: &RelPath,
234        delegate: &Arc<dyn RemoteClientDelegate>,
235        cx: &mut AsyncApp,
236    ) -> Result<()> {
237        delegate.set_status(Some("Uploading remote server"), cx);
238
239        if let Some(parent) = dst_path.parent() {
240            let parent = parent.display(PathStyle::Posix);
241            let mkdir = self.shell_kind.prepend_command_prefix("mkdir");
242            self.run_wsl_command(&mkdir, &["-p", &parent])
243                .await
244                .context("Failed to create directory when uploading file")?;
245        }
246
247        let t0 = Instant::now();
248        let src_stat = fs::metadata(&src_path)
249            .await
250            .with_context(|| format!("source path does not exist: {}", src_path.display()))?;
251        let size = src_stat.len();
252        log::info!(
253            "uploading remote server to WSL {:?} ({}kb)",
254            dst_path,
255            size / 1024
256        );
257
258        let src_path_in_wsl = self.windows_path_to_wsl_path(src_path).await?;
259        let cp = self.shell_kind.prepend_command_prefix("cp");
260        self.run_wsl_command(
261            &cp,
262            &["-f", &src_path_in_wsl, &dst_path.display(PathStyle::Posix)],
263        )
264        .await
265        .map_err(|e| {
266            anyhow!(
267                "Failed to copy file {}({}) to WSL {:?}: {}",
268                src_path.display(),
269                src_path_in_wsl,
270                dst_path,
271                e
272            )
273        })?;
274
275        log::info!("uploaded remote server in {:?}", t0.elapsed());
276        Ok(())
277    }
278
279    async fn extract_and_install(
280        &self,
281        tmp_path: &RelPath,
282        dst_path: &RelPath,
283        delegate: &Arc<dyn RemoteClientDelegate>,
284        cx: &mut AsyncApp,
285    ) -> Result<()> {
286        delegate.set_status(Some("Extracting remote server"), cx);
287
288        let tmp_path_str = tmp_path.display(PathStyle::Posix);
289        let dst_path_str = dst_path.display(PathStyle::Posix);
290
291        // Build extraction script with proper error handling
292        let script = if tmp_path_str.ends_with(".gz") {
293            let uncompressed = tmp_path_str.trim_end_matches(".gz");
294            format!(
295                "set -e; gunzip -f '{}' && chmod 755 '{}' && mv -f '{}' '{}'",
296                tmp_path_str, uncompressed, uncompressed, dst_path_str
297            )
298        } else {
299            format!(
300                "set -e; chmod 755 '{}' && mv -f '{}' '{}'",
301                tmp_path_str, tmp_path_str, dst_path_str
302            )
303        };
304
305        self.run_wsl_command("sh", &["-c", &script])
306            .await
307            .map_err(|e| anyhow!("Failed to extract server binary: {}", e))?;
308        Ok(())
309    }
310}
311
312#[async_trait(?Send)]
313impl RemoteConnection for WslRemoteConnection {
314    fn start_proxy(
315        &self,
316        unique_identifier: String,
317        reconnect: bool,
318        incoming_tx: UnboundedSender<Envelope>,
319        outgoing_rx: UnboundedReceiver<Envelope>,
320        connection_activity_tx: Sender<()>,
321        delegate: Arc<dyn RemoteClientDelegate>,
322        cx: &mut AsyncApp,
323    ) -> Task<Result<i32>> {
324        delegate.set_status(Some("Starting proxy"), cx);
325
326        let Some(remote_binary_path) = &self.remote_binary_path else {
327            return Task::ready(Err(anyhow!("Remote binary path not set")));
328        };
329
330        let mut proxy_args = vec![];
331        for env_var in ["RUST_LOG", "RUST_BACKTRACE", "ZED_GENERATE_MINIDUMPS"] {
332            if let Some(value) = std::env::var(env_var).ok() {
333                // We don't quote the value here as it seems excessive and may result in invalid envs for the
334                // proxy server. For example, `RUST_LOG='debug'` will result in a warning "invalid logging spec 'debug'', ignoring it"
335                // in the proxy server. Therefore, we pass the env vars as is.
336                proxy_args.push(format!("{}={}", env_var, value));
337            }
338        }
339
340        proxy_args.push(remote_binary_path.display(PathStyle::Posix).into_owned());
341        proxy_args.push("proxy".to_owned());
342        proxy_args.push("--identifier".to_owned());
343        proxy_args.push(unique_identifier);
344
345        if reconnect {
346            proxy_args.push("--reconnect".to_owned());
347        }
348
349        let proxy_process =
350            match wsl_command_impl(&self.connection_options, "env", &proxy_args, false)
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            async move {
378                let wsl_src = windows_path_to_wsl_path_impl(&options, &src_path).await?;
379
380                run_wsl_command_impl(
381                    &options,
382                    "cp",
383                    &["-r", &wsl_src, &dest_path.to_string()],
384                    true,
385                )
386                .await
387                .map_err(|e| {
388                    anyhow!(
389                        "failed to upload directory {} -> {}: {}",
390                        src_path.display(),
391                        dest_path,
392                        e
393                    )
394                })?;
395
396                Ok(())
397            }
398        })
399    }
400
401    async fn kill(&self) -> Result<()> {
402        Ok(())
403    }
404
405    fn has_been_killed(&self) -> bool {
406        false
407    }
408
409    fn shares_network_interface(&self) -> bool {
410        true
411    }
412
413    fn build_command(
414        &self,
415        program: Option<String>,
416        args: &[String],
417        env: &HashMap<String, String>,
418        working_dir: Option<String>,
419        port_forward: Option<(u16, String, u16)>,
420    ) -> Result<CommandTemplate> {
421        if port_forward.is_some() {
422            bail!("WSL shares the network interface with the host system");
423        }
424
425        let shell_kind = self.shell_kind;
426        let working_dir = working_dir
427            .map(|working_dir| RemotePathBuf::new(working_dir, PathStyle::Posix).to_string())
428            .unwrap_or("~".to_string());
429
430        let mut exec = String::from("exec env ");
431
432        for (k, v) in env.iter() {
433            write!(
434                exec,
435                "{}={} ",
436                k,
437                shell_kind.try_quote(v).context("shell quoting")?
438            )?;
439        }
440
441        if let Some(program) = program {
442            write!(
443                exec,
444                "{}",
445                shell_kind
446                    .try_quote_prefix_aware(&program)
447                    .context("shell quoting")?
448            )?;
449            for arg in args {
450                let arg = shell_kind.try_quote(&arg).context("shell quoting")?;
451                write!(exec, " {}", &arg)?;
452            }
453        } else {
454            write!(&mut exec, "{} -l", self.shell)?;
455        }
456
457        let wsl_args = if let Some(user) = &self.connection_options.user {
458            vec![
459                "--distribution".to_string(),
460                self.connection_options.distro_name.clone(),
461                "--user".to_string(),
462                user.clone(),
463                "--cd".to_string(),
464                working_dir,
465                "--".to_string(),
466                self.shell.clone(),
467                "-c".to_string(),
468                exec,
469            ]
470        } else {
471            vec![
472                "--distribution".to_string(),
473                self.connection_options.distro_name.clone(),
474                "--cd".to_string(),
475                working_dir,
476                "--".to_string(),
477                self.shell.clone(),
478                "-c".to_string(),
479                exec,
480            ]
481        };
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}