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