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