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