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