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