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};
 25
 26#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 27pub struct WslConnectionOptions {
 28    pub distro_name: String,
 29    pub user: Option<String>,
 30}
 31
 32impl From<settings::WslConnection> for WslConnectionOptions {
 33    fn from(val: settings::WslConnection) -> Self {
 34        WslConnectionOptions {
 35            distro_name: val.distro_name.into(),
 36            user: val.user,
 37        }
 38    }
 39}
 40
 41#[derive(Debug)]
 42pub(crate) struct WslRemoteConnection {
 43    remote_binary_path: Option<Arc<RelPath>>,
 44    platform: RemotePlatform,
 45    shell: String,
 46    default_system_shell: String,
 47    connection_options: WslConnectionOptions,
 48    can_exec: bool,
 49}
 50
 51impl WslRemoteConnection {
 52    pub(crate) async fn new(
 53        connection_options: WslConnectionOptions,
 54        delegate: Arc<dyn RemoteClientDelegate>,
 55        cx: &mut AsyncApp,
 56    ) -> Result<Self> {
 57        log::info!(
 58            "Connecting to WSL distro {} with user {:?}",
 59            connection_options.distro_name,
 60            connection_options.user
 61        );
 62        let (release_channel, version, commit) = cx.update(|cx| {
 63            (
 64                ReleaseChannel::global(cx),
 65                AppVersion::global(cx),
 66                AppCommitSha::try_global(cx),
 67            )
 68        })?;
 69
 70        let mut this = Self {
 71            connection_options,
 72            remote_binary_path: None,
 73            platform: RemotePlatform { os: "", arch: "" },
 74            shell: String::new(),
 75            default_system_shell: String::from("/bin/sh"),
 76            can_exec: true,
 77        };
 78        delegate.set_status(Some("Detecting WSL environment"), cx);
 79        this.can_exec = this.detect_can_exec().await?;
 80        this.platform = this.detect_platform().await?;
 81        this.shell = this.detect_shell().await?;
 82        this.remote_binary_path = Some(
 83            this.ensure_server_binary(&delegate, release_channel, version, commit, cx)
 84                .await?,
 85        );
 86        log::debug!("Detected WSL environment: {this:#?}");
 87
 88        Ok(this)
 89    }
 90
 91    async fn detect_can_exec(&self) -> Result<bool> {
 92        let options = &self.connection_options;
 93        let program = "uname";
 94        let args = &["-m"];
 95        let output = wsl_command_impl(options, program, args, true)
 96            .output()
 97            .await?;
 98
 99        if !output.status.success() {
100            let output = wsl_command_impl(options, program, args, false)
101                .output()
102                .await?;
103
104            if !output.status.success() {
105                return Err(anyhow!(
106                    "Command '{}' failed: {}",
107                    program,
108                    String::from_utf8_lossy(&output.stderr).trim()
109                ));
110            }
111
112            Ok(false)
113        } else {
114            Ok(true)
115        }
116    }
117
118    async fn detect_platform(&self) -> Result<RemotePlatform> {
119        let arch_str = self.run_wsl_command("uname", &["-m"]).await?;
120        let arch_str = arch_str.trim().to_string();
121        let arch = match arch_str.as_str() {
122            "x86_64" => "x86_64",
123            "aarch64" | "arm64" => "aarch64",
124            _ => "x86_64",
125        };
126        Ok(RemotePlatform { os: "linux", arch })
127    }
128
129    async fn detect_shell(&self) -> Result<String> {
130        Ok(self
131            .run_wsl_command("sh", &["-c", "echo $SHELL"])
132            .await
133            .ok()
134            .unwrap_or_else(|| "bash".to_string()))
135    }
136
137    async fn windows_path_to_wsl_path(&self, source: &Path) -> Result<String> {
138        windows_path_to_wsl_path_impl(&self.connection_options, source, self.can_exec).await
139    }
140
141    fn wsl_command(&self, program: &str, args: &[impl AsRef<OsStr>]) -> process::Command {
142        wsl_command_impl(&self.connection_options, program, args, self.can_exec)
143    }
144
145    async fn run_wsl_command(&self, program: &str, args: &[&str]) -> Result<String> {
146        run_wsl_command_impl(&self.connection_options, program, args, self.can_exec).await
147    }
148
149    async fn ensure_server_binary(
150        &self,
151        delegate: &Arc<dyn RemoteClientDelegate>,
152        release_channel: ReleaseChannel,
153        version: SemanticVersion,
154        commit: Option<AppCommitSha>,
155        cx: &mut AsyncApp,
156    ) -> Result<Arc<RelPath>> {
157        let version_str = match release_channel {
158            ReleaseChannel::Nightly => {
159                let commit = commit.map(|s| s.full()).unwrap_or_default();
160                format!("{}-{}", version, commit)
161            }
162            ReleaseChannel::Dev => "build".to_string(),
163            _ => version.to_string(),
164        };
165
166        let binary_name = format!(
167            "zed-remote-server-{}-{}",
168            release_channel.dev_name(),
169            version_str
170        );
171
172        let dst_path =
173            paths::remote_wsl_server_dir_relative().join(RelPath::unix(&binary_name).unwrap());
174
175        if let Some(parent) = dst_path.parent() {
176            self.run_wsl_command("mkdir", &["-p", &parent.display(PathStyle::Posix)])
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        delegate.set_status(Some("Installing remote server"), cx);
209
210        let wanted_version = match release_channel {
211            ReleaseChannel::Nightly | ReleaseChannel::Dev => None,
212            _ => Some(cx.update(|cx| AppVersion::global(cx))?),
213        };
214
215        let src_path = delegate
216            .download_server_binary_locally(self.platform, release_channel, wanted_version, cx)
217            .await?;
218
219        let tmp_path = format!(
220            "{}.{}.gz",
221            dst_path.display(PathStyle::Posix),
222            std::process::id()
223        );
224        let tmp_path = RelPath::unix(&tmp_path).unwrap();
225
226        self.upload_file(&src_path, &tmp_path, delegate, cx).await?;
227        self.extract_and_install(&tmp_path, &dst_path, delegate, cx)
228            .await?;
229
230        Ok(dst_path)
231    }
232
233    async fn upload_file(
234        &self,
235        src_path: &Path,
236        dst_path: &RelPath,
237        delegate: &Arc<dyn RemoteClientDelegate>,
238        cx: &mut AsyncApp,
239    ) -> Result<()> {
240        delegate.set_status(Some("Uploading remote server to WSL"), cx);
241
242        if let Some(parent) = dst_path.parent() {
243            self.run_wsl_command("mkdir", &["-p", &parent.display(PathStyle::Posix)])
244                .await
245                .map_err(|e| anyhow!("Failed to create directory when uploading file: {}", e))?;
246        }
247
248        let t0 = Instant::now();
249        let src_stat = fs::metadata(&src_path).await?;
250        let size = src_stat.len();
251        log::info!(
252            "uploading remote server to WSL {:?} ({}kb)",
253            dst_path,
254            size / 1024
255        );
256
257        let src_path_in_wsl = self.windows_path_to_wsl_path(src_path).await?;
258        self.run_wsl_command(
259            "cp",
260            &["-f", &src_path_in_wsl, &dst_path.display(PathStyle::Posix)],
261        )
262        .await
263        .map_err(|e| {
264            anyhow!(
265                "Failed to copy file {}({}) to WSL {:?}: {}",
266                src_path.display(),
267                src_path_in_wsl,
268                dst_path,
269                e
270            )
271        })?;
272
273        log::info!("uploaded remote server in {:?}", t0.elapsed());
274        Ok(())
275    }
276
277    async fn extract_and_install(
278        &self,
279        tmp_path: &RelPath,
280        dst_path: &RelPath,
281        delegate: &Arc<dyn RemoteClientDelegate>,
282        cx: &mut AsyncApp,
283    ) -> Result<()> {
284        delegate.set_status(Some("Extracting remote server"), cx);
285
286        let tmp_path_str = tmp_path.display(PathStyle::Posix);
287        let dst_path_str = dst_path.display(PathStyle::Posix);
288
289        // Build extraction script with proper error handling
290        let script = if tmp_path_str.ends_with(".gz") {
291            let uncompressed = tmp_path_str.trim_end_matches(".gz");
292            format!(
293                "set -e; gunzip -f '{}' && chmod 755 '{}' && mv -f '{}' '{}'",
294                tmp_path_str, uncompressed, uncompressed, dst_path_str
295            )
296        } else {
297            format!(
298                "set -e; chmod 755 '{}' && mv -f '{}' '{}'",
299                tmp_path_str, tmp_path_str, dst_path_str
300            )
301        };
302
303        self.run_wsl_command("sh", &["-c", &script])
304            .await
305            .map_err(|e| anyhow!("Failed to extract server binary: {}", e))?;
306        Ok(())
307    }
308}
309
310#[async_trait(?Send)]
311impl RemoteConnection for WslRemoteConnection {
312    fn start_proxy(
313        &self,
314        unique_identifier: String,
315        reconnect: bool,
316        incoming_tx: UnboundedSender<Envelope>,
317        outgoing_rx: UnboundedReceiver<Envelope>,
318        connection_activity_tx: Sender<()>,
319        delegate: Arc<dyn RemoteClientDelegate>,
320        cx: &mut AsyncApp,
321    ) -> Task<Result<i32>> {
322        delegate.set_status(Some("Starting proxy"), cx);
323
324        let Some(remote_binary_path) = &self.remote_binary_path else {
325            return Task::ready(Err(anyhow!("Remote binary path not set")));
326        };
327
328        let mut proxy_args = vec![];
329        for env_var in ["RUST_LOG", "RUST_BACKTRACE", "ZED_GENERATE_MINIDUMPS"] {
330            if let Some(value) = std::env::var(env_var).ok() {
331                // We don't quote the value here as it seems excessive and may result in invalid envs for the
332                // proxy server. For example, `RUST_LOG='debug'` will result in a warning "invalid logging spec 'debug'', ignoring it"
333                // in the proxy server. Therefore, we pass the env vars as is.
334                proxy_args.push(format!("{}={}", env_var, value));
335            }
336        }
337        proxy_args.push(remote_binary_path.display(PathStyle::Posix).into_owned());
338        proxy_args.push("proxy".to_owned());
339        proxy_args.push("--identifier".to_owned());
340        proxy_args.push(unique_identifier);
341
342        if reconnect {
343            proxy_args.push("--reconnect".to_owned());
344        }
345        let proxy_process = match self
346            .wsl_command("env", &proxy_args)
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.to_string(),
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 working_dir = working_dir
423            .map(|working_dir| RemotePathBuf::new(working_dir, PathStyle::Posix).to_string())
424            .unwrap_or("~".to_string());
425
426        let mut exec = String::from("exec env ");
427
428        for (k, v) in env.iter() {
429            if let Some((k, v)) = shlex::try_quote(k).ok().zip(shlex::try_quote(v).ok()) {
430                write!(exec, "{}={} ", k, v).unwrap();
431            }
432        }
433
434        if let Some(program) = program {
435            write!(exec, "{}", shlex::try_quote(&program)?).unwrap();
436            for arg in args {
437                let arg = shlex::try_quote(&arg)?;
438                write!(exec, " {}", &arg).unwrap();
439            }
440        } else {
441            write!(&mut exec, "{} -l", self.shell).unwrap();
442        }
443
444        let wsl_args = if let Some(user) = &self.connection_options.user {
445            vec![
446                "--distribution".to_string(),
447                self.connection_options.distro_name.clone(),
448                "--user".to_string(),
449                user.clone(),
450                "--cd".to_string(),
451                working_dir,
452                "--".to_string(),
453                self.shell.clone(),
454                "-c".to_string(),
455                exec,
456            ]
457        } else {
458            vec![
459                "--distribution".to_string(),
460                self.connection_options.distro_name.clone(),
461                "--cd".to_string(),
462                working_dir,
463                "--".to_string(),
464                self.shell.clone(),
465                "-c".to_string(),
466                exec,
467            ]
468        };
469
470        Ok(CommandTemplate {
471            program: "wsl.exe".to_string(),
472            args: wsl_args,
473            env: HashMap::default(),
474        })
475    }
476
477    fn connection_options(&self) -> RemoteConnectionOptions {
478        RemoteConnectionOptions::Wsl(self.connection_options.clone())
479    }
480
481    fn path_style(&self) -> PathStyle {
482        PathStyle::Posix
483    }
484
485    fn shell(&self) -> String {
486        self.shell.clone()
487    }
488
489    fn default_system_shell(&self) -> String {
490        self.default_system_shell.clone()
491    }
492}
493
494/// `wslpath` is a executable available in WSL, it's a linux binary.
495/// So it doesn't support Windows style paths.
496async fn sanitize_path(path: &Path) -> Result<String> {
497    let path = smol::fs::canonicalize(path).await?;
498    let path_str = path.to_string_lossy();
499
500    let sanitized = path_str.strip_prefix(r"\\?\").unwrap_or(&path_str);
501    Ok(sanitized.replace('\\', "/"))
502}
503
504async fn windows_path_to_wsl_path_impl(
505    options: &WslConnectionOptions,
506    source: &Path,
507    exec: bool,
508) -> Result<String> {
509    let source = sanitize_path(source).await?;
510    run_wsl_command_impl(options, "wslpath", &["-u", &source], exec).await
511}
512
513async fn run_wsl_command_impl(
514    options: &WslConnectionOptions,
515    program: &str,
516    args: &[&str],
517    exec: bool,
518) -> Result<String> {
519    let output = wsl_command_impl(options, program, args, exec)
520        .output()
521        .await?;
522
523    if !output.status.success() {
524        return Err(anyhow!(
525            "Command '{}' failed: {}",
526            program,
527            String::from_utf8_lossy(&output.stderr).trim()
528        ));
529    }
530
531    Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
532}
533
534/// Creates a new `wsl.exe` command that runs the given program with the given arguments.
535///
536/// If `exec` is true, the command will be executed in the WSL environment without spawning a new shell.
537fn wsl_command_impl(
538    options: &WslConnectionOptions,
539    program: &str,
540    args: &[impl AsRef<OsStr>],
541    exec: bool,
542) -> process::Command {
543    let mut command = util::command::new_smol_command("wsl.exe");
544
545    if let Some(user) = &options.user {
546        command.arg("--user").arg(user);
547    }
548
549    command
550        .stdin(Stdio::piped())
551        .stdout(Stdio::piped())
552        .stderr(Stdio::piped())
553        .arg("--distribution")
554        .arg(&options.distro_name)
555        .arg("--cd")
556        .arg("~");
557
558    if exec {
559        command.arg("--exec");
560    }
561
562    command.arg(program).args(args);
563
564    log::debug!("wsl {:?}", command);
565    command
566}