Skip to main content

isothrum_machine/
wsl.rs

1//! Whether WSL 2 is ready on a Windows computer.
2//!
3//! No single signal can be trusted: `wsl.exe` ships with Windows whether WSL is set up or not,
4//! `wsl --version` only exists in the Store WSL, `wsl --status` may fail on a computer without a
5//! distribution, and a feature turned on reads as on before the restart that really starts it.
6//! So the check gathers several, none of which needs an administrator or reads localized text,
7//! and [`classify`] (pure, tested on every OS) weighs them:
8//! - `wsl --status` and `wsl --version`, by exit code only;
9//! - the WSL services in the registry: `LxssManager` (the WSL feature) and `WslService` (the
10//!   Store WSL);
11//! - the optional features `VirtualMachinePlatform` and `Microsoft-Windows-Subsystem-Linux` (WMI
12//!   `Win32_OptionalFeature`, readable without an administrator), and whether a hypervisor runs
13//!   (`Win32_ComputerSystem.HypervisorPresent`: the Virtual Machine Platform only starts one after
14//!   the restart);
15//! - the restart Windows' servicing waits for (`Component Based Servicing\RebootPending`), and
16//!   pending file renames, a weak sign (many installers, drivers and antivirus leave some at every
17//!   boot), only heeded right after the caller's own install;
18//! - what the caller did itself ([`Marks`]): whether its own "turn on WSL 2" ran since this boot,
19//!   and whether it already restarted Windows for WSL (then a restart is never asked for again).
20//!
21//! Every probe runs through the [`Context`]'s runner, within a time limit: a hung `wsl.exe` costs
22//! the check a few seconds, never the caller.
23
24use std::time::Duration;
25
26use isothrum_runner::ProcessSpec;
27use serde::{Deserialize, Serialize};
28
29use crate::context::Context;
30use crate::exec::Unanswered;
31use crate::host::HostOs;
32
33/// Where WSL 2 stands on this computer.
34#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
35#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS))]
36#[serde(rename_all = "camelCase")]
37pub enum WslState {
38    /// On and running.
39    Ready,
40    /// Turned on (or being turned on), but Windows has to restart to finish.
41    NeedsReboot,
42    /// Not set up.
43    Missing,
44    /// The signals don't agree, or couldn't be read.
45    Unknown,
46}
47
48/// How a probe command went.
49#[derive(Clone, Copy, PartialEq, Eq, Debug)]
50pub enum Run {
51    /// Exited 0.
52    Ok,
53    /// Exited with another code (or couldn't be started for another reason than missing).
54    Failed,
55    /// Ran out of time and was ended.
56    TimedOut,
57    /// Not on this computer.
58    Missing,
59}
60
61/// An optional feature's `Win32_OptionalFeature.InstallState`.
62#[derive(Clone, Copy, PartialEq, Eq, Debug)]
63pub enum Feature {
64    /// 1
65    Enabled,
66    /// 2
67    Disabled,
68    /// 3: not available on this edition, or not listed at all.
69    Absent,
70}
71
72/// What the caller did itself, which no probe can read: it keeps them (by boot) and hands them
73/// to [`probe`].
74#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
75pub struct Marks {
76    /// The caller's own "turn on WSL 2" ran since this boot.
77    pub installed_this_boot: bool,
78    /// The caller restarted Windows for WSL in an earlier boot, with no install since.
79    pub restarted_for_wsl: bool,
80}
81
82/// Every signal the check read. `None` is "couldn't tell" (unreadable, or the probe failed).
83#[derive(Clone, Copy, Debug)]
84pub struct Probes {
85    /// `wsl.exe --status`.
86    pub status: Run,
87    /// `wsl.exe --version`: only the Store WSL knows this option.
88    pub version: Run,
89    /// The WSL feature's service (`LxssManager`) is registered.
90    pub lxss_service: Option<bool>,
91    /// The Store WSL's service (`WslService`) is registered.
92    pub wsl_service: Option<bool>,
93    /// The Virtual Machine Platform feature's state.
94    pub vm_platform: Option<Feature>,
95    /// The Windows Subsystem for Linux feature's state.
96    pub wsl_feature: Option<Feature>,
97    /// A hypervisor runs (what the Virtual Machine Platform starts at boot).
98    pub hypervisor: Option<bool>,
99    /// Windows' servicing waits for a restart.
100    pub reboot_pending: Option<bool>,
101    /// Files wait to be replaced at the next restart (weak: many installers leave some).
102    pub renames_pending: Option<bool>,
103    /// The caller's own "turn on WSL 2" ran since this boot ([`Marks`]).
104    pub installed_this_boot: bool,
105    /// The caller restarted Windows for WSL in an earlier boot ([`Marks`]).
106    pub restarted_for_wsl: bool,
107}
108
109/// Where WSL 2 stands, from what the probes found.
110#[must_use]
111pub fn classify(p: &Probes) -> WslState {
112    // WSL itself: the Store package, or the Windows feature.
113    let store = p.version == Run::Ok || p.wsl_service == Some(true);
114    let inbox = p.lxss_service == Some(true) || p.wsl_feature == Some(Feature::Enabled);
115    let wsl = store || inbox;
116    // WSL 2 runs its VM on the Virtual Machine Platform.
117    let platform_on = p.vm_platform == Some(Feature::Enabled);
118    let platform_off = matches!(p.vm_platform, Some(Feature::Disabled | Feature::Absent));
119    let running = p.hypervisor == Some(true);
120    let hypervisor_running = p.hypervisor != Some(false);
121    let pending = p.reboot_pending == Some(true);
122
123    // The caller's own install ran this boot and Windows waits for a restart: whatever the
124    // features read meanwhile (they can read as on already), they only start after it. Renames
125    // count here only: right after that install they are likely its own.
126    if p.installed_this_boot && (pending || p.renames_pending == Some(true)) {
127        return WslState::NeedsReboot;
128    }
129    if wsl && platform_on && running {
130        // The platform is on and its hypervisor runs. A restart Windows waits for may be an
131        // update's: then WSL has to answer too, or (without a distribution `wsl --status` fails)
132        // be the Store WSL, which only installs once the platform is set up.
133        if !pending || p.status == Run::Ok || (store && !p.installed_this_boot) {
134            return WslState::Ready;
135        }
136    }
137    // WSL answers and nothing waits for a restart; the features couldn't be read.
138    let answers_with_features_unread = wsl && p.status == Run::Ok && p.reboot_pending == Some(false) && p.vm_platform.is_none();
139    if answers_with_features_unread && hypervisor_running {
140        return WslState::Ready;
141    }
142    if p.installed_this_boot {
143        return WslState::NeedsReboot;
144    }
145    // A restart is pending and WSL is partly there: that restart finishes it. Never a second time
146    // once the caller restarted for it: what is left isn't a restart's to fix. Nor when the
147    // platform reads off: a feature turned on reads as on before its restart, so the pending
148    // restart is someone else's (an update's) and leaves WSL 2 without its platform, as Docker
149    // Desktop then says ("Virtual Machine Platform is not enabled"). The caller's own install
150    // this boot was settled above.
151    if (wsl || platform_on) && pending && !platform_off && !p.restarted_for_wsl {
152        return WslState::NeedsReboot;
153    }
154    let wsl_failed = matches!(p.status, Run::Failed | Run::Missing);
155    let no_services = p.lxss_service == Some(false) && p.wsl_service == Some(false);
156    // Nothing of WSL, as both the services and wsl.exe say; or WSL without the platform (WSL 1
157    // only, or the Store WSL on a computer whose platform was never turned on), restart pending
158    // or not.
159    if (!wsl && !platform_on && wsl_failed && (no_services || platform_off)) || (wsl && platform_off) {
160        return WslState::Missing;
161    }
162    // Among the rest: on, yet no hypervisor (virtualization off in the firmware, most likely).
163    WslState::Unknown
164}
165
166/// Whether virtualization looks off in the firmware: the platform is on, no hypervisor runs, and
167/// no restart is still to come.
168#[must_use]
169pub fn virtualization_off(p: &Probes, state: WslState) -> bool {
170    state == WslState::Unknown && p.vm_platform == Some(Feature::Enabled) && p.hypervisor == Some(false)
171}
172
173/// The features and the hypervisor, through WMI (no administrator needed), printed as
174/// language-neutral `key=value` lines (see [`parse_cim`]). Each query fails on its own, and the
175/// script exits 0 whatever happened, so what it printed is always read.
176pub const CIM_SCRIPT: &str = "$ProgressPreference = 'SilentlyContinue'
177try {
178  $f = @(Get-CimInstance -ClassName Win32_OptionalFeature -Filter \"Name='VirtualMachinePlatform' OR Name='Microsoft-Windows-Subsystem-Linux'\" -ErrorAction Stop)
179  'features=ok'
180  foreach ($x in $f) { 'feature:' + $x.Name + '=' + [int]$x.InstallState }
181} catch {}
182try { 'hypervisor=' + [bool](Get-CimInstance -ClassName Win32_ComputerSystem -ErrorAction Stop).HypervisorPresent } catch {}
183exit 0
184";
185
186/// The features and the hypervisor, from [`CIM_SCRIPT`]'s output: `features=ok` once the feature
187/// query answered, then `feature:<name>=<InstallState>` for each feature it lists (an unlisted one
188/// is absent), and `hypervisor=True|False`. Partial output reads as far as it goes.
189#[must_use]
190pub fn parse_cim(out: &str) -> (Option<Feature>, Option<Feature>, Option<bool>) {
191    let lines: Vec<&str> = out.lines().map(str::trim).collect();
192    let answered = lines.contains(&"features=ok");
193    let feature = |name: &str| {
194        if !answered {
195            return None;
196        }
197        let prefix = format!("feature:{name}=");
198        match lines.iter().find_map(|l| l.strip_prefix(prefix.as_str())) {
199            None | Some("3") => Some(Feature::Absent),
200            Some("1") => Some(Feature::Enabled),
201            Some("2") => Some(Feature::Disabled),
202            Some(_) => None,
203        }
204    };
205    let hypervisor = lines.iter().find_map(|l| l.strip_prefix("hypervisor=")).and_then(|v| match v {
206        "True" => Some(true),
207        "False" => Some(false),
208        _ => None,
209    });
210    (feature("VirtualMachinePlatform"), feature("Microsoft-Windows-Subsystem-Linux"), hypervisor)
211}
212
213/// Where WSL 2 stands, and whether virtualization looks off in the firmware, with the signals
214/// read (for a log).
215#[derive(Clone, Copy, Debug)]
216#[non_exhaustive]
217pub struct Wsl {
218    /// Where it stands ([`classify`]).
219    pub state: WslState,
220    /// Virtualization looks off in the firmware ([`virtualization_off`]).
221    pub virtualization_off: bool,
222    /// The signals it was decided on.
223    pub probes: Probes,
224}
225
226/// How long `wsl.exe` may take.
227const WSL_TIMEOUT: Duration = Duration::from_secs(10);
228/// How long the WMI queries may take.
229const CIM_TIMEOUT: Duration = Duration::from_secs(20);
230/// How long a registry read may take.
231const REG_TIMEOUT: Duration = Duration::from_secs(10);
232
233/// The services' registry key.
234const SERVICES: &str = r"HKLM\SYSTEM\CurrentControlSet\Services";
235
236/// Where WSL 2 stands on the context's host, given what the caller did itself (`marks`): on
237/// Windows only, `None` elsewhere.
238pub async fn check(cx: &Context, marks: Marks) -> Option<Wsl> {
239    if cx.host.os != HostOs::Windows {
240        return None;
241    }
242    let probes = probe(cx, marks).await;
243    let state = classify(&probes);
244    Some(Wsl {
245        state,
246        virtualization_off: virtualization_off(&probes, state),
247        probes,
248    })
249}
250
251/// Every signal, the commands side by side. `wsl.exe` writes UTF-16 unless told otherwise: only
252/// its exit codes are read, but its output in a log stays readable.
253pub async fn probe(cx: &Context, marks: Marks) -> Probes {
254    let wsl = |arg: &str| {
255        let mut spec = ProcessSpec::new("wsl", [arg]);
256        spec.env.push(("WSL_UTF8".to_owned(), "1".to_owned()));
257        spec
258    };
259    let (status_spec, version_spec) = (wsl("--status"), wsl("--version"));
260    let cim_spec = ProcessSpec::new("powershell", ["-NoProfile", "-NonInteractive", "-EncodedCommand", &encoded(CIM_SCRIPT)]);
261    let (status, version, cim) = tokio::join!(
262        cx.probe_within(WSL_TIMEOUT, &status_spec),
263        cx.probe_within(WSL_TIMEOUT, &version_spec),
264        cx.probe_within(CIM_TIMEOUT, &cim_spec),
265    );
266    let cim_out = match &cim {
267        Ok(captured) if captured.success() => captured.stdout.join("\n"),
268        _ => String::new(),
269    };
270    let (vm_platform, wsl_feature, hypervisor) = parse_cim(&cim_out);
271    let lxss = format!(r"{SERVICES}\LxssManager");
272    let store = format!(r"{SERVICES}\WslService");
273    let servicing = r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending";
274    let session = r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager";
275    let (lxss, store, servicing) = ([lxss.as_str()], [store.as_str()], [servicing]);
276    let renames = [session, "/v", "PendingFileRenameOperations"];
277    let (lxss_service, wsl_service, reboot_pending, renames_pending) =
278        tokio::join!(registry(cx, &lxss), registry(cx, &store), registry(cx, &servicing), registry(cx, &renames),);
279    Probes {
280        status: outcome(&status),
281        version: outcome(&version),
282        lxss_service,
283        wsl_service,
284        vm_platform,
285        wsl_feature,
286        hypervisor,
287        reboot_pending,
288        renames_pending,
289        installed_this_boot: marks.installed_this_boot,
290        restarted_for_wsl: marks.restarted_for_wsl,
291    }
292}
293
294/// How a timed probe went.
295fn outcome(result: &Result<isothrum_runner::Captured, Unanswered>) -> Run {
296    match result {
297        Ok(captured) if captured.success() => Run::Ok,
298        Err(Unanswered::NotStarted(isothrum_runner::ProcessError::Missing { .. })) => Run::Missing,
299        Ok(_) | Err(Unanswered::NotStarted(_)) => Run::Failed,
300        Err(Unanswered::TimedOut(_)) => Run::TimedOut,
301    }
302}
303
304/// Whether a registry key (or, with `/v <name>`, a value) exists: `reg query` exits 0 when it
305/// does and 1 when it doesn't; `None` when `reg` couldn't tell (it didn't start, or ran out of
306/// time).
307async fn registry(cx: &Context, query: &[&str]) -> Option<bool> {
308    let spec = ProcessSpec::new("reg", std::iter::once("query").chain(query.iter().copied()));
309    match cx.probe_within(REG_TIMEOUT, &spec).await {
310        Ok(captured) => match captured.exit.code {
311            Some(0) => Some(true),
312            Some(1) => Some(false),
313            _ => None,
314        },
315        Err(_) => None,
316    }
317}
318
319/// A script for `powershell -EncodedCommand`: base64 of its UTF-16LE text (no quoting to get
320/// wrong on the command line).
321pub(crate) fn encoded(script: &str) -> String {
322    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
323    let bytes: Vec<u8> = script.encode_utf16().flat_map(u16::to_le_bytes).collect();
324    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
325    for chunk in bytes.chunks(3) {
326        let n = chunk.iter().enumerate().fold(0usize, |n, (i, b)| n | (usize::from(*b) << (16 - 8 * i)));
327        for i in 0..4 {
328            let sextet = ALPHABET.get((n >> (18 - 6 * i)) & 0x3f).copied().unwrap_or(b'=');
329            out.push(char::from(if i <= chunk.len() { sextet } else { b'=' }));
330        }
331    }
332    out
333}
334
335#[cfg(test)]
336mod tests;