wsl.rs

  1use crate::{
  2    RemoteClientDelegate, RemotePlatform,
  3    remote_client::{CommandTemplate, RemoteConnection, RemoteConnectionOptions},
  4};
  5use anyhow::{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    paths::{PathStyle, RemotePathBuf},
 23    rel_path::RelPath,
 24    shell::ShellKind,
 25};
 26
 27#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 28pub struct WslConnectionOptions {
 29    pub distro_name: String,
 30    pub user: Option<String>,
 31}
 32
 33impl From<settings::WslConnection> for WslConnectionOptions {
 34    fn from(val: settings::WslConnection) -> Self {
 35        WslConnectionOptions {
 36            distro_name: val.distro_name.into(),
 37            user: val.user,
 38        }
 39    }
 40}
 41
 42#[derive(Debug)]
 43pub(crate) struct WslRemoteConnection {
 44    remote_binary_path: Option<Arc<RelPath>>,
 45    platform: RemotePlatform,
 46    shell: String,
 47    default_system_shell: String,
 48    connection_options: WslConnectionOptions,
 49    can_exec: bool,
 50}
 51
 52impl WslRemoteConnection {
 53    pub(crate) async fn new(
 54        connection_options: WslConnectionOptions,
 55        delegate: Arc<dyn RemoteClientDelegate>,
 56        cx: &mut AsyncApp,
 57    ) -> Result<Self> {
 58        log::info!(
 59            "Connecting to WSL distro {} with user {:?}",
 60            connection_options.distro_name,
 61            connection_options.user
 62        );
 63        let (release_channel, version, commit) = cx.update(|cx| {
 64            (
 65                ReleaseChannel::global(cx),
 66                AppVersion::global(cx),
 67                AppCommitSha::try_global(cx),
 68            )
 69        })?;
 70
 71        let mut this = Self {
 72            connection_options,
 73            remote_binary_path: None,
 74            platform: RemotePlatform { os: "", arch: "" },
 75            shell: String::new(),
 76            default_system_shell: String::from("/bin/sh"),
 77            can_exec: true,
 78        };
 79        delegate.set_status(Some("Detecting WSL environment"), cx);
 80        this.shell = this.detect_shell().await?;
 81        let shell = ShellKind::new(&this.shell, false);
 82        this.can_exec = this.detect_can_exec(shell).await?;
 83        this.platform = this.detect_platform(shell).await?;
 84        this.remote_binary_path = Some(
 85            this.ensure_server_binary(&delegate, release_channel, version, commit, shell, cx)
 86                .await?,
 87        );
 88        log::debug!("Detected WSL environment: {this:#?}");
 89
 90        Ok(this)
 91    }
 92
 93    async fn detect_can_exec(&self, shell: ShellKind) -> Result<bool> {
 94        let options = &self.connection_options;
 95        let program = if shell == ShellKind::Nushell {
 96            "^uname"
 97        } else {
 98            "uname"
 99        };
100        let args = &["-m"];
101        let output = wsl_command_impl(options, program, args, true)
102            .output()
103            .await?;
104
105        if !output.status.success() {
106            let output = wsl_command_impl(options, program, args, false)
107                .output()
108                .await?;
109
110            if !output.status.success() {
111                return Err(anyhow!(
112                    "Command '{}' failed: {}",
113                    program,
114                    String::from_utf8_lossy(&output.stderr).trim()
115                ));
116            }
117
118            Ok(false)
119        } else {
120            Ok(true)
121        }
122    }
123    async fn detect_platform(&self, shell: ShellKind) -> Result<RemotePlatform> {
124        let arch_str = if shell == ShellKind::Nushell {
125            // https://github.com/nushell/nushell/issues/12570
126            self.run_wsl_command("sh", &["-c", "uname -m"])
127        } else {
128            self.run_wsl_command("uname", &["-m"])
129        }
130        .await?;
131        let arch_str = arch_str.trim().to_string();
132        let arch = match arch_str.as_str() {
133            "x86_64" => "x86_64",
134            "aarch64" | "arm64" => "aarch64",
135            _ => "x86_64",
136        };
137        Ok(RemotePlatform { os: "linux", arch })
138    }
139
140    async fn detect_shell(&self) -> Result<String> {
141        Ok(self
142            .run_wsl_command("sh", &["-c", "echo $SHELL"])
143            .await
144            .ok()
145            .unwrap_or_else(|| "/bin/sh".to_string()))
146    }
147
148    async fn windows_path_to_wsl_path(&self, source: &Path) -> Result<String> {
149        windows_path_to_wsl_path_impl(&self.connection_options, source, self.can_exec).await
150    }
151
152    fn wsl_command(&self, program: &str, args: &[impl AsRef<OsStr>]) -> process::Command {
153        wsl_command_impl(&self.connection_options, program, args, self.can_exec)
154    }
155
156    async fn run_wsl_command(&self, program: &str, args: &[&str]) -> Result<String> {
157        run_wsl_command_impl(&self.connection_options, program, args, self.can_exec).await
158    }
159
160    async fn ensure_server_binary(
161        &self,
162        delegate: &Arc<dyn RemoteClientDelegate>,
163        release_channel: ReleaseChannel,
164        version: SemanticVersion,
165        commit: Option<AppCommitSha>,
166        shell: ShellKind,
167        cx: &mut AsyncApp,
168    ) -> Result<Arc<RelPath>> {
169        let version_str = match release_channel {
170            ReleaseChannel::Nightly => {
171                let commit = commit.map(|s| s.full()).unwrap_or_default();
172                format!("{}-{}", version, commit)
173            }
174            ReleaseChannel::Dev => "build".to_string(),
175            _ => version.to_string(),
176        };
177
178        let binary_name = format!(
179            "zed-remote-server-{}-{}",
180            release_channel.dev_name(),
181            version_str
182        );
183
184        let dst_path =
185            paths::remote_wsl_server_dir_relative().join(RelPath::unix(&binary_name).unwrap());
186
187        if let Some(parent) = dst_path.parent() {
188            let parent = parent.display(PathStyle::Posix);
189            if shell == ShellKind::Nushell {
190                self.run_wsl_command("mkdir", &[&parent]).await
191            } else {
192                self.run_wsl_command("mkdir", &["-p", &parent]).await
193            }
194            .map_err(|e| anyhow!("Failed to create directory: {}", e))?;
195        }
196
197        #[cfg(debug_assertions)]
198        if let Some(remote_server_path) =
199            super::build_remote_server_from_source(&self.platform, delegate.as_ref(), cx).await?
200        {
201            let tmp_path = paths::remote_wsl_server_dir_relative().join(
202                &RelPath::unix(&format!(
203                    "download-{}-{}",
204                    std::process::id(),
205                    remote_server_path.file_name().unwrap().to_string_lossy()
206                ))
207                .unwrap(),
208            );
209            self.upload_file(&remote_server_path, &tmp_path, delegate, cx)
210                .await?;
211            self.extract_and_install(&tmp_path, &dst_path, delegate, cx)
212                .await?;
213            return Ok(dst_path);
214        }
215
216        if self
217            .run_wsl_command(&dst_path.display(PathStyle::Posix), &["version"])
218            .await
219            .is_ok()
220        {
221            return Ok(dst_path);
222        }
223
224        delegate.set_status(Some("Installing remote server"), cx);
225
226        let wanted_version = match release_channel {
227            ReleaseChannel::Nightly | ReleaseChannel::Dev => None,
228            _ => Some(cx.update(|cx| AppVersion::global(cx))?),
229        };
230
231        let src_path = delegate
232            .download_server_binary_locally(self.platform, release_channel, wanted_version, cx)
233            .await?;
234
235        let tmp_path = format!(
236            "{}.{}.gz",
237            dst_path.display(PathStyle::Posix),
238            std::process::id()
239        );
240        let tmp_path = RelPath::unix(&tmp_path).unwrap();
241
242        self.upload_file(&src_path, &tmp_path, delegate, cx).await?;
243        self.extract_and_install(&tmp_path, &dst_path, delegate, cx)
244            .await?;
245
246        Ok(dst_path)
247    }
248
249    async fn upload_file(
250        &self,
251        src_path: &Path,
252        dst_path: &RelPath,
253        delegate: &Arc<dyn RemoteClientDelegate>,
254        cx: &mut AsyncApp,
255    ) -> Result<()> {
256        delegate.set_status(Some("Uploading remote server to WSL"), cx);
257
258        if let Some(parent) = dst_path.parent() {
259            self.run_wsl_command("mkdir", &["-p", &parent.display(PathStyle::Posix)])
260                .await
261                .map_err(|e| anyhow!("Failed to create directory when uploading file: {}", e))?;
262        }
263
264        let t0 = Instant::now();
265        let src_stat = fs::metadata(&src_path).await?;
266        let size = src_stat.len();
267        log::info!(
268            "uploading remote server to WSL {:?} ({}kb)",
269            dst_path,
270            size / 1024
271        );
272
273        let src_path_in_wsl = self.windows_path_to_wsl_path(src_path).await?;
274        self.run_wsl_command(
275            "cp",
276            &["-f", &src_path_in_wsl, &dst_path.display(PathStyle::Posix)],
277        )
278        .await
279        .map_err(|e| {
280            anyhow!(
281                "Failed to copy file {}({}) to WSL {:?}: {}",
282                src_path.display(),
283                src_path_in_wsl,
284                dst_path,
285                e
286            )
287        })?;
288
289        log::info!("uploaded remote server in {:?}", t0.elapsed());
290        Ok(())
291    }
292
293    async fn extract_and_install(
294        &self,
295        tmp_path: &RelPath,
296        dst_path: &RelPath,
297        delegate: &Arc<dyn RemoteClientDelegate>,
298        cx: &mut AsyncApp,
299    ) -> Result<()> {
300        delegate.set_status(Some("Extracting remote server"), cx);
301
302        let tmp_path_str = tmp_path.display(PathStyle::Posix);
303        let dst_path_str = dst_path.display(PathStyle::Posix);
304
305        // Build extraction script with proper error handling
306        let script = if tmp_path_str.ends_with(".gz") {
307            let uncompressed = tmp_path_str.trim_end_matches(".gz");
308            format!(
309                "set -e; gunzip -f '{}' && chmod 755 '{}' && mv -f '{}' '{}'",
310                tmp_path_str, uncompressed, uncompressed, dst_path_str
311            )
312        } else {
313            format!(
314                "set -e; chmod 755 '{}' && mv -f '{}' '{}'",
315                tmp_path_str, tmp_path_str, dst_path_str
316            )
317        };
318
319        self.run_wsl_command("sh", &["-c", &script])
320            .await
321            .map_err(|e| anyhow!("Failed to extract server binary: {}", e))?;
322        Ok(())
323    }
324}
325
326#[async_trait(?Send)]
327impl RemoteConnection for WslRemoteConnection {
328    fn start_proxy(
329        &self,
330        unique_identifier: String,
331        reconnect: bool,
332        incoming_tx: UnboundedSender<Envelope>,
333        outgoing_rx: UnboundedReceiver<Envelope>,
334        connection_activity_tx: Sender<()>,
335        delegate: Arc<dyn RemoteClientDelegate>,
336        cx: &mut AsyncApp,
337    ) -> Task<Result<i32>> {
338        delegate.set_status(Some("Starting proxy"), cx);
339
340        let Some(remote_binary_path) = &self.remote_binary_path else {
341            return Task::ready(Err(anyhow!("Remote binary path not set")));
342        };
343
344        let mut proxy_args = vec![];
345        for env_var in ["RUST_LOG", "RUST_BACKTRACE", "ZED_GENERATE_MINIDUMPS"] {
346            if let Some(value) = std::env::var(env_var).ok() {
347                // We don't quote the value here as it seems excessive and may result in invalid envs for the
348                // proxy server. For example, `RUST_LOG='debug'` will result in a warning "invalid logging spec 'debug'', ignoring it"
349                // in the proxy server. Therefore, we pass the env vars as is.
350                proxy_args.push(format!("{}={}", env_var, value));
351            }
352        }
353        proxy_args.push(remote_binary_path.display(PathStyle::Posix).into_owned());
354        proxy_args.push("proxy".to_owned());
355        proxy_args.push("--identifier".to_owned());
356        proxy_args.push(unique_identifier);
357
358        if reconnect {
359            proxy_args.push("--reconnect".to_owned());
360        }
361        let proxy_process = match self
362            .wsl_command("env", &proxy_args)
363            .kill_on_drop(true)
364            .spawn()
365        {
366            Ok(process) => process,
367            Err(error) => {
368                return Task::ready(Err(anyhow!("failed to spawn remote server: {}", error)));
369            }
370        };
371
372        super::handle_rpc_messages_over_child_process_stdio(
373            proxy_process,
374            incoming_tx,
375            outgoing_rx,
376            connection_activity_tx,
377            cx,
378        )
379    }
380
381    fn upload_directory(
382        &self,
383        src_path: PathBuf,
384        dest_path: RemotePathBuf,
385        cx: &App,
386    ) -> Task<Result<()>> {
387        cx.background_spawn({
388            let options = self.connection_options.clone();
389            let can_exec = self.can_exec;
390            async move {
391                let wsl_src = windows_path_to_wsl_path_impl(&options, &src_path, can_exec).await?;
392
393                run_wsl_command_impl(
394                    &options,
395                    "cp",
396                    &["-r", &wsl_src, &dest_path.to_string()],
397                    can_exec,
398                )
399                .await
400                .map_err(|e| {
401                    anyhow!(
402                        "failed to upload directory {} -> {}: {}",
403                        src_path.display(),
404                        dest_path.to_string(),
405                        e
406                    )
407                })?;
408
409                Ok(())
410            }
411        })
412    }
413
414    async fn kill(&self) -> Result<()> {
415        Ok(())
416    }
417
418    fn has_been_killed(&self) -> bool {
419        false
420    }
421
422    fn shares_network_interface(&self) -> bool {
423        true
424    }
425
426    fn build_command(
427        &self,
428        program: Option<String>,
429        args: &[String],
430        env: &HashMap<String, String>,
431        working_dir: Option<String>,
432        port_forward: Option<(u16, String, u16)>,
433    ) -> Result<CommandTemplate> {
434        if port_forward.is_some() {
435            bail!("WSL shares the network interface with the host system");
436        }
437
438        let working_dir = working_dir
439            .map(|working_dir| RemotePathBuf::new(working_dir, PathStyle::Posix).to_string())
440            .unwrap_or("~".to_string());
441
442        let mut exec = String::from("exec env ");
443
444        for (k, v) in env.iter() {
445            if let Some((k, v)) = shlex::try_quote(k).ok().zip(shlex::try_quote(v).ok()) {
446                write!(exec, "{}={} ", k, v).unwrap();
447            }
448        }
449
450        if let Some(program) = program {
451            write!(exec, "{}", shlex::try_quote(&program)?).unwrap();
452            for arg in args {
453                let arg = shlex::try_quote(&arg)?;
454                write!(exec, " {}", &arg).unwrap();
455            }
456        } else {
457            write!(&mut exec, "{} -l", self.shell).unwrap();
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).await?;
521    let path_str = path.to_string_lossy();
522
523    let sanitized = path_str.strip_prefix(r"\\?\").unwrap_or(&path_str);
524    Ok(sanitized.replace('\\', "/"))
525}
526
527async fn windows_path_to_wsl_path_impl(
528    options: &WslConnectionOptions,
529    source: &Path,
530    exec: bool,
531) -> Result<String> {
532    let source = sanitize_path(source).await?;
533    run_wsl_command_impl(options, "wslpath", &["-u", &source], exec).await
534}
535
536async fn run_wsl_command_impl(
537    options: &WslConnectionOptions,
538    program: &str,
539    args: &[&str],
540    exec: bool,
541) -> Result<String> {
542    let output = wsl_command_impl(options, program, args, exec)
543        .output()
544        .await?;
545
546    if !output.status.success() {
547        return Err(anyhow!(
548            "Command '{}' failed: {}",
549            program,
550            String::from_utf8_lossy(&output.stderr).trim()
551        ));
552    }
553
554    Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
555}
556
557/// Creates a new `wsl.exe` command that runs the given program with the given arguments.
558///
559/// If `exec` is true, the command will be executed in the WSL environment without spawning a new shell.
560fn wsl_command_impl(
561    options: &WslConnectionOptions,
562    program: &str,
563    args: &[impl AsRef<OsStr>],
564    exec: bool,
565) -> process::Command {
566    let mut command = util::command::new_smol_command("wsl.exe");
567
568    if let Some(user) = &options.user {
569        command.arg("--user").arg(user);
570    }
571
572    command
573        .stdin(Stdio::piped())
574        .stdout(Stdio::piped())
575        .stderr(Stdio::piped())
576        .arg("--distribution")
577        .arg(&options.distro_name)
578        .arg("--cd")
579        .arg("~");
580
581    if exec {
582        command.arg("--exec");
583    }
584
585    command.arg(program).args(args);
586
587    log::debug!("wsl {:?}", command);
588    command
589}