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