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