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