wsl.rs

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