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.platform);
 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                .context("Failed to create directory when uploading file")?;
255        }
256
257        let t0 = Instant::now();
258        let src_stat = fs::metadata(&src_path)
259            .await
260            .with_context(|| format!("source path does not exist: {}", src_path.display()))?;
261        let size = src_stat.len();
262        log::info!(
263            "uploading remote server to WSL {:?} ({}kb)",
264            dst_path,
265            size / 1024
266        );
267
268        let src_path_in_wsl = self.windows_path_to_wsl_path(src_path).await?;
269        let cp = self.shell_kind.prepend_command_prefix("cp");
270        self.run_wsl_command(
271            &cp,
272            &["-f", &src_path_in_wsl, &dst_path.display(PathStyle::Posix)],
273        )
274        .await
275        .map_err(|e| {
276            anyhow!(
277                "Failed to copy file {}({}) to WSL {:?}: {}",
278                src_path.display(),
279                src_path_in_wsl,
280                dst_path,
281                e
282            )
283        })?;
284
285        log::info!("uploaded remote server in {:?}", t0.elapsed());
286        Ok(())
287    }
288
289    async fn extract_and_install(
290        &self,
291        tmp_path: &RelPath,
292        dst_path: &RelPath,
293        delegate: &Arc<dyn RemoteClientDelegate>,
294        cx: &mut AsyncApp,
295    ) -> Result<()> {
296        delegate.set_status(Some("Extracting remote server"), cx);
297
298        let tmp_path_str = tmp_path.display(PathStyle::Posix);
299        let dst_path_str = dst_path.display(PathStyle::Posix);
300
301        // Build extraction script with proper error handling
302        let script = if tmp_path_str.ends_with(".gz") {
303            let uncompressed = tmp_path_str.trim_end_matches(".gz");
304            format!(
305                "set -e; gunzip -f '{}' && chmod 755 '{}' && mv -f '{}' '{}'",
306                tmp_path_str, uncompressed, uncompressed, dst_path_str
307            )
308        } else {
309            format!(
310                "set -e; chmod 755 '{}' && mv -f '{}' '{}'",
311                tmp_path_str, tmp_path_str, dst_path_str
312            )
313        };
314
315        self.run_wsl_command("sh", &["-c", &script])
316            .await
317            .map_err(|e| anyhow!("Failed to extract server binary: {}", e))?;
318        Ok(())
319    }
320}
321
322#[async_trait(?Send)]
323impl RemoteConnection for WslRemoteConnection {
324    fn start_proxy(
325        &self,
326        unique_identifier: String,
327        reconnect: bool,
328        incoming_tx: UnboundedSender<Envelope>,
329        outgoing_rx: UnboundedReceiver<Envelope>,
330        connection_activity_tx: Sender<()>,
331        delegate: Arc<dyn RemoteClientDelegate>,
332        cx: &mut AsyncApp,
333    ) -> Task<Result<i32>> {
334        delegate.set_status(Some("Starting proxy"), cx);
335
336        let Some(remote_binary_path) = &self.remote_binary_path else {
337            return Task::ready(Err(anyhow!("Remote binary path not set")));
338        };
339
340        let mut proxy_args = vec![];
341        for env_var in ["RUST_LOG", "RUST_BACKTRACE", "ZED_GENERATE_MINIDUMPS"] {
342            if let Some(value) = std::env::var(env_var).ok() {
343                // We don't quote the value here as it seems excessive and may result in invalid envs for the
344                // proxy server. For example, `RUST_LOG='debug'` will result in a warning "invalid logging spec 'debug'', ignoring it"
345                // in the proxy server. Therefore, we pass the env vars as is.
346                proxy_args.push(format!("{}={}", env_var, value));
347            }
348        }
349        proxy_args.push(remote_binary_path.display(PathStyle::Posix).into_owned());
350        proxy_args.push("proxy".to_owned());
351        proxy_args.push("--identifier".to_owned());
352        proxy_args.push(unique_identifier);
353
354        if reconnect {
355            proxy_args.push("--reconnect".to_owned());
356        }
357        let proxy_process = match self
358            .wsl_command("env", &proxy_args)
359            .kill_on_drop(true)
360            .spawn()
361        {
362            Ok(process) => process,
363            Err(error) => {
364                return Task::ready(Err(anyhow!("failed to spawn remote server: {}", error)));
365            }
366        };
367
368        super::handle_rpc_messages_over_child_process_stdio(
369            proxy_process,
370            incoming_tx,
371            outgoing_rx,
372            connection_activity_tx,
373            cx,
374        )
375    }
376
377    fn upload_directory(
378        &self,
379        src_path: PathBuf,
380        dest_path: RemotePathBuf,
381        cx: &App,
382    ) -> Task<Result<()>> {
383        cx.background_spawn({
384            let options = self.connection_options.clone();
385            let can_exec = self.can_exec;
386            async move {
387                let wsl_src = windows_path_to_wsl_path_impl(&options, &src_path, can_exec).await?;
388
389                run_wsl_command_impl(
390                    &options,
391                    "cp",
392                    &["-r", &wsl_src, &dest_path.to_string()],
393                    can_exec,
394                )
395                .await
396                .map_err(|e| {
397                    anyhow!(
398                        "failed to upload directory {} -> {}: {}",
399                        src_path.display(),
400                        dest_path,
401                        e
402                    )
403                })?;
404
405                Ok(())
406            }
407        })
408    }
409
410    async fn kill(&self) -> Result<()> {
411        Ok(())
412    }
413
414    fn has_been_killed(&self) -> bool {
415        false
416    }
417
418    fn shares_network_interface(&self) -> bool {
419        true
420    }
421
422    fn build_command(
423        &self,
424        program: Option<String>,
425        args: &[String],
426        env: &HashMap<String, String>,
427        working_dir: Option<String>,
428        port_forward: Option<(u16, String, u16)>,
429    ) -> Result<CommandTemplate> {
430        if port_forward.is_some() {
431            bail!("WSL shares the network interface with the host system");
432        }
433
434        let shell_kind = self.shell_kind;
435        let working_dir = working_dir
436            .map(|working_dir| RemotePathBuf::new(working_dir, PathStyle::Posix).to_string())
437            .unwrap_or("~".to_string());
438
439        let mut exec = String::from("exec env ");
440
441        for (k, v) in env.iter() {
442            write!(
443                exec,
444                "{}={} ",
445                k,
446                shell_kind.try_quote(v).context("shell quoting")?
447            )?;
448        }
449
450        if let Some(program) = program {
451            write!(
452                exec,
453                "{}",
454                shell_kind
455                    .try_quote_prefix_aware(&program)
456                    .context("shell quoting")?
457            )?;
458            for arg in args {
459                let arg = shell_kind.try_quote(&arg).context("shell quoting")?;
460                write!(exec, " {}", &arg)?;
461            }
462        } else {
463            write!(&mut exec, "{} -l", self.shell)?;
464        }
465
466        let wsl_args = if let Some(user) = &self.connection_options.user {
467            vec![
468                "--distribution".to_string(),
469                self.connection_options.distro_name.clone(),
470                "--user".to_string(),
471                user.clone(),
472                "--cd".to_string(),
473                working_dir,
474                "--".to_string(),
475                self.shell.clone(),
476                "-c".to_string(),
477                exec,
478            ]
479        } else {
480            vec![
481                "--distribution".to_string(),
482                self.connection_options.distro_name.clone(),
483                "--cd".to_string(),
484                working_dir,
485                "--".to_string(),
486                self.shell.clone(),
487                "-c".to_string(),
488                exec,
489            ]
490        };
491
492        Ok(CommandTemplate {
493            program: "wsl.exe".to_string(),
494            args: wsl_args,
495            env: HashMap::default(),
496        })
497    }
498
499    fn build_forward_ports_command(
500        &self,
501        _: Vec<(u16, String, u16)>,
502    ) -> anyhow::Result<CommandTemplate> {
503        Err(anyhow!("WSL shares a network interface with the host"))
504    }
505
506    fn connection_options(&self) -> RemoteConnectionOptions {
507        RemoteConnectionOptions::Wsl(self.connection_options.clone())
508    }
509
510    fn path_style(&self) -> PathStyle {
511        PathStyle::Posix
512    }
513
514    fn shell(&self) -> String {
515        self.shell.clone()
516    }
517
518    fn default_system_shell(&self) -> String {
519        self.default_system_shell.clone()
520    }
521}
522
523/// `wslpath` is a executable available in WSL, it's a linux binary.
524/// So it doesn't support Windows style paths.
525async fn sanitize_path(path: &Path) -> Result<String> {
526    let path = smol::fs::canonicalize(path)
527        .await
528        .with_context(|| format!("Failed to canonicalize path {}", path.display()))?;
529    let path_str = path.to_string_lossy();
530
531    let sanitized = path_str.strip_prefix(r"\\?\").unwrap_or(&path_str);
532    Ok(sanitized.replace('\\', "/"))
533}
534
535async fn windows_path_to_wsl_path_impl(
536    options: &WslConnectionOptions,
537    source: &Path,
538    exec: bool,
539) -> Result<String> {
540    let source = sanitize_path(source).await?;
541    run_wsl_command_impl(options, "wslpath", &["-u", &source], exec).await
542}
543
544async fn run_wsl_command_impl(
545    options: &WslConnectionOptions,
546    program: &str,
547    args: &[&str],
548    exec: bool,
549) -> Result<String> {
550    let mut command = wsl_command_impl(options, program, args, exec);
551    let output = command
552        .output()
553        .await
554        .with_context(|| format!("Failed to run command '{:?}'", command))?;
555
556    if !output.status.success() {
557        return Err(anyhow!(
558            "Command '{:?}' failed: {}",
559            command,
560            String::from_utf8_lossy(&output.stderr).trim()
561        ));
562    }
563
564    Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
565}
566
567/// Creates a new `wsl.exe` command that runs the given program with the given arguments.
568///
569/// If `exec` is true, the command will be executed in the WSL environment without spawning a new shell.
570fn wsl_command_impl(
571    options: &WslConnectionOptions,
572    program: &str,
573    args: &[impl AsRef<OsStr>],
574    exec: bool,
575) -> process::Command {
576    let mut command = util::command::new_smol_command("wsl.exe");
577
578    if let Some(user) = &options.user {
579        command.arg("--user").arg(user);
580    }
581
582    command
583        .stdin(Stdio::piped())
584        .stdout(Stdio::piped())
585        .stderr(Stdio::piped())
586        .arg("--distribution")
587        .arg(&options.distro_name)
588        .arg("--cd")
589        .arg("~");
590
591    if exec {
592        command.arg("--exec");
593    }
594
595    command.arg(program).args(args);
596
597    log::debug!("wsl {:?}", command);
598    command
599}