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        this.shell_kind = ShellKind::new(&this.shell, false);
 88        this.can_exec = this.detect_can_exec().await;
 89        this.platform = this
 90            .detect_platform()
 91            .await
 92            .context("failed detecting platform")?;
 93        this.remote_binary_path = Some(
 94            this.ensure_server_binary(&delegate, release_channel, version, commit, cx)
 95                .await
 96                .context("failed ensuring server binary")?,
 97        );
 98        log::debug!("Detected WSL environment: {this:#?}");
 99
100        Ok(this)
101    }
102
103    async fn detect_can_exec(&self) -> bool {
104        let options = &self.connection_options;
105        let program = self.shell_kind.prepend_command_prefix("uname");
106        let args = &["-m"];
107        let output = wsl_command_impl(options, &program, args, true)
108            .output()
109            .await;
110
111        if !output.is_ok_and(|output| output.status.success()) {
112            run_wsl_command_impl(options, &program, args, false)
113                .await
114                .context("failed detecting exec status")
115                .log_err();
116            false
117        } else {
118            true
119        }
120    }
121    async fn detect_platform(&self) -> Result<RemotePlatform> {
122        let program = self.shell_kind.prepend_command_prefix("uname");
123        let arch_str = self.run_wsl_command(&program, &["-m"]).await?;
124        let arch_str = arch_str.trim().to_string();
125        let arch = match arch_str.as_str() {
126            "x86_64" => "x86_64",
127            "aarch64" | "arm64" => "aarch64",
128            _ => "x86_64",
129        };
130        Ok(RemotePlatform { os: "linux", arch })
131    }
132
133    async fn detect_shell(&self) -> Result<String> {
134        Ok(self
135            .run_wsl_command("sh", &["-c", "echo $SHELL"])
136            .await
137            .ok()
138            .unwrap_or_else(|| "/bin/sh".to_string()))
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, self.can_exec).await
143    }
144
145    fn wsl_command(&self, program: &str, args: &[impl AsRef<OsStr>]) -> process::Command {
146        wsl_command_impl(&self.connection_options, program, args, self.can_exec)
147    }
148
149    async fn run_wsl_command(&self, program: &str, args: &[&str]) -> Result<String> {
150        run_wsl_command_impl(&self.connection_options, program, args, self.can_exec).await
151    }
152
153    async fn ensure_server_binary(
154        &self,
155        delegate: &Arc<dyn RemoteClientDelegate>,
156        release_channel: ReleaseChannel,
157        version: SemanticVersion,
158        commit: Option<AppCommitSha>,
159        cx: &mut AsyncApp,
160    ) -> Result<Arc<RelPath>> {
161        let version_str = match release_channel {
162            ReleaseChannel::Nightly => {
163                let commit = commit.map(|s| s.full()).unwrap_or_default();
164                format!("{}-{}", version, commit)
165            }
166            ReleaseChannel::Dev => "build".to_string(),
167            _ => version.to_string(),
168        };
169
170        let binary_name = format!(
171            "zed-remote-server-{}-{}",
172            release_channel.dev_name(),
173            version_str
174        );
175
176        let dst_path =
177            paths::remote_wsl_server_dir_relative().join(RelPath::unix(&binary_name).unwrap());
178
179        if let Some(parent) = dst_path.parent() {
180            let parent = parent.display(PathStyle::Posix);
181            self.run_wsl_command("mkdir", &["-p", &parent])
182                .await
183                .map_err(|e| anyhow!("Failed to create directory: {}", e))?;
184        }
185
186        #[cfg(debug_assertions)]
187        if let Some(remote_server_path) =
188            super::build_remote_server_from_source(&self.platform, delegate.as_ref(), cx).await?
189        {
190            let tmp_path = paths::remote_wsl_server_dir_relative().join(
191                &RelPath::unix(&format!(
192                    "download-{}-{}",
193                    std::process::id(),
194                    remote_server_path.file_name().unwrap().to_string_lossy()
195                ))
196                .unwrap(),
197            );
198            self.upload_file(&remote_server_path, &tmp_path, delegate, cx)
199                .await?;
200            self.extract_and_install(&tmp_path, &dst_path, delegate, cx)
201                .await?;
202            return Ok(dst_path);
203        }
204
205        if self
206            .run_wsl_command(&dst_path.display(PathStyle::Posix), &["version"])
207            .await
208            .is_ok()
209        {
210            return Ok(dst_path);
211        }
212
213        delegate.set_status(Some("Installing remote server"), cx);
214
215        let wanted_version = match release_channel {
216            ReleaseChannel::Nightly | ReleaseChannel::Dev => None,
217            _ => Some(cx.update(|cx| AppVersion::global(cx))?),
218        };
219
220        let src_path = delegate
221            .download_server_binary_locally(self.platform, release_channel, wanted_version, cx)
222            .await?;
223
224        let tmp_path = format!(
225            "{}.{}.gz",
226            dst_path.display(PathStyle::Posix),
227            std::process::id()
228        );
229        let tmp_path = RelPath::unix(&tmp_path).unwrap();
230
231        self.upload_file(&src_path, &tmp_path, delegate, cx).await?;
232        self.extract_and_install(&tmp_path, &dst_path, delegate, cx)
233            .await?;
234
235        Ok(dst_path)
236    }
237
238    async fn upload_file(
239        &self,
240        src_path: &Path,
241        dst_path: &RelPath,
242        delegate: &Arc<dyn RemoteClientDelegate>,
243        cx: &mut AsyncApp,
244    ) -> Result<()> {
245        delegate.set_status(Some("Uploading remote server to WSL"), cx);
246
247        if let Some(parent) = dst_path.parent() {
248            let parent = parent.display(PathStyle::Posix);
249            self.run_wsl_command("mkdir", &["-p", &parent])
250                .await
251                .map_err(|e| anyhow!("Failed to create directory when uploading file: {}", e))?;
252        }
253
254        let t0 = Instant::now();
255        let src_stat = fs::metadata(&src_path).await?;
256        let size = src_stat.len();
257        log::info!(
258            "uploading remote server to WSL {:?} ({}kb)",
259            dst_path,
260            size / 1024
261        );
262
263        let src_path_in_wsl = self.windows_path_to_wsl_path(src_path).await?;
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        proxy_args.push(remote_binary_path.display(PathStyle::Posix).into_owned());
344        proxy_args.push("proxy".to_owned());
345        proxy_args.push("--identifier".to_owned());
346        proxy_args.push(unique_identifier);
347
348        if reconnect {
349            proxy_args.push("--reconnect".to_owned());
350        }
351        let proxy_process = match self
352            .wsl_command("env", &proxy_args)
353            .kill_on_drop(true)
354            .spawn()
355        {
356            Ok(process) => process,
357            Err(error) => {
358                return Task::ready(Err(anyhow!("failed to spawn remote server: {}", error)));
359            }
360        };
361
362        super::handle_rpc_messages_over_child_process_stdio(
363            proxy_process,
364            incoming_tx,
365            outgoing_rx,
366            connection_activity_tx,
367            cx,
368        )
369    }
370
371    fn upload_directory(
372        &self,
373        src_path: PathBuf,
374        dest_path: RemotePathBuf,
375        cx: &App,
376    ) -> Task<Result<()>> {
377        cx.background_spawn({
378            let options = self.connection_options.clone();
379            let can_exec = self.can_exec;
380            async move {
381                let wsl_src = windows_path_to_wsl_path_impl(&options, &src_path, can_exec).await?;
382
383                run_wsl_command_impl(
384                    &options,
385                    "cp",
386                    &["-r", &wsl_src, &dest_path.to_string()],
387                    can_exec,
388                )
389                .await
390                .map_err(|e| {
391                    anyhow!(
392                        "failed to upload directory {} -> {}: {}",
393                        src_path.display(),
394                        dest_path,
395                        e
396                    )
397                })?;
398
399                Ok(())
400            }
401        })
402    }
403
404    async fn kill(&self) -> Result<()> {
405        Ok(())
406    }
407
408    fn has_been_killed(&self) -> bool {
409        false
410    }
411
412    fn shares_network_interface(&self) -> bool {
413        true
414    }
415
416    fn build_command(
417        &self,
418        program: Option<String>,
419        args: &[String],
420        env: &HashMap<String, String>,
421        working_dir: Option<String>,
422        port_forward: Option<(u16, String, u16)>,
423    ) -> Result<CommandTemplate> {
424        if port_forward.is_some() {
425            bail!("WSL shares the network interface with the host system");
426        }
427
428        let shell_kind = self.shell_kind;
429        let working_dir = working_dir
430            .map(|working_dir| RemotePathBuf::new(working_dir, PathStyle::Posix).to_string())
431            .unwrap_or("~".to_string());
432
433        let mut exec = String::from("exec env ");
434
435        for (k, v) in env.iter() {
436            write!(
437                exec,
438                "{}={} ",
439                k,
440                shell_kind.try_quote(v).context("shell quoting")?
441            )?;
442        }
443
444        if let Some(program) = program {
445            write!(
446                exec,
447                "{}",
448                shell_kind
449                    .try_quote_prefix_aware(&program)
450                    .context("shell quoting")?
451            )?;
452            for arg in args {
453                let arg = shell_kind.try_quote(&arg).context("shell quoting")?;
454                write!(exec, " {}", &arg)?;
455            }
456        } else {
457            write!(&mut exec, "{} -l", self.shell)?;
458        }
459
460        let 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                self.shell.clone(),
470                "-c".to_string(),
471                exec,
472            ]
473        } else {
474            vec![
475                "--distribution".to_string(),
476                self.connection_options.distro_name.clone(),
477                "--cd".to_string(),
478                working_dir,
479                "--".to_string(),
480                self.shell.clone(),
481                "-c".to_string(),
482                exec,
483            ]
484        };
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
517/// `wslpath` is a executable available in WSL, it's a linux binary.
518/// So it doesn't support Windows style paths.
519async fn sanitize_path(path: &Path) -> Result<String> {
520    let path = smol::fs::canonicalize(path)
521        .await
522        .with_context(|| format!("Failed to canonicalize path {}", path.display()))?;
523    let path_str = path.to_string_lossy();
524
525    let sanitized = path_str.strip_prefix(r"\\?\").unwrap_or(&path_str);
526    Ok(sanitized.replace('\\', "/"))
527}
528
529async fn windows_path_to_wsl_path_impl(
530    options: &WslConnectionOptions,
531    source: &Path,
532    exec: bool,
533) -> Result<String> {
534    let source = sanitize_path(source).await?;
535    run_wsl_command_impl(options, "wslpath", &["-u", &source], exec).await
536}
537
538async fn run_wsl_command_impl(
539    options: &WslConnectionOptions,
540    program: &str,
541    args: &[&str],
542    exec: bool,
543) -> Result<String> {
544    let mut command = wsl_command_impl(options, program, args, exec);
545    let output = command
546        .output()
547        .await
548        .with_context(|| format!("Failed to run command '{:?}'", command))?;
549
550    if !output.status.success() {
551        return Err(anyhow!(
552            "Command '{:?}' failed: {}",
553            command,
554            String::from_utf8_lossy(&output.stderr).trim()
555        ));
556    }
557
558    Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
559}
560
561/// Creates a new `wsl.exe` command that runs the given program with the given arguments.
562///
563/// If `exec` is true, the command will be executed in the WSL environment without spawning a new shell.
564fn wsl_command_impl(
565    options: &WslConnectionOptions,
566    program: &str,
567    args: &[impl AsRef<OsStr>],
568    exec: bool,
569) -> process::Command {
570    let mut command = util::command::new_smol_command("wsl.exe");
571
572    if let Some(user) = &options.user {
573        command.arg("--user").arg(user);
574    }
575
576    command
577        .stdin(Stdio::piped())
578        .stdout(Stdio::piped())
579        .stderr(Stdio::piped())
580        .arg("--distribution")
581        .arg(&options.distro_name)
582        .arg("--cd")
583        .arg("~");
584
585    if exec {
586        command.arg("--exec");
587    }
588
589    command.arg(program).args(args);
590
591    log::debug!("wsl {:?}", command);
592    command
593}