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