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