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.
147    if (wsl || platform_on) && pending && !p.restarted_for_wsl {
148        return WslState::NeedsReboot;
149    }
150    let wsl_failed = matches!(p.status, Run::Failed | Run::Missing);
151    let no_services = p.lxss_service == Some(false) && p.wsl_service == Some(false);
152    // Nothing of WSL, as both the services and wsl.exe say; or WSL 1 only, without the platform.
153    if (!wsl && !platform_on && wsl_failed && (no_services || platform_off)) || (wsl && platform_off && !pending) {
154        return WslState::Missing;
155    }
156    // Among the rest: on, yet no hypervisor (virtualization off in the firmware, most likely).
157    WslState::Unknown
158}
159
160/// Whether virtualization looks off in the firmware: the platform is on, no hypervisor runs, and
161/// no restart is still to come.
162#[must_use]
163pub fn virtualization_off(p: &Probes, state: WslState) -> bool {
164    state == WslState::Unknown && p.vm_platform == Some(Feature::Enabled) && p.hypervisor == Some(false)
165}
166
167/// The features and the hypervisor, through WMI (no administrator needed), printed as
168/// language-neutral `key=value` lines (see [`parse_cim`]). Each query fails on its own, and the
169/// script exits 0 whatever happened, so what it printed is always read.
170pub const CIM_SCRIPT: &str = "$ProgressPreference = 'SilentlyContinue'
171try {
172  $f = @(Get-CimInstance -ClassName Win32_OptionalFeature -Filter \"Name='VirtualMachinePlatform' OR Name='Microsoft-Windows-Subsystem-Linux'\" -ErrorAction Stop)
173  'features=ok'
174  foreach ($x in $f) { 'feature:' + $x.Name + '=' + [int]$x.InstallState }
175} catch {}
176try { 'hypervisor=' + [bool](Get-CimInstance -ClassName Win32_ComputerSystem -ErrorAction Stop).HypervisorPresent } catch {}
177exit 0
178";
179
180/// The features and the hypervisor, from [`CIM_SCRIPT`]'s output: `features=ok` once the feature
181/// query answered, then `feature:<name>=<InstallState>` for each feature it lists (an unlisted one
182/// is absent), and `hypervisor=True|False`. Partial output reads as far as it goes.
183#[must_use]
184pub fn parse_cim(out: &str) -> (Option<Feature>, Option<Feature>, Option<bool>) {
185    let lines: Vec<&str> = out.lines().map(str::trim).collect();
186    let answered = lines.contains(&"features=ok");
187    let feature = |name: &str| {
188        if !answered {
189            return None;
190        }
191        let prefix = format!("feature:{name}=");
192        match lines.iter().find_map(|l| l.strip_prefix(prefix.as_str())) {
193            None | Some("3") => Some(Feature::Absent),
194            Some("1") => Some(Feature::Enabled),
195            Some("2") => Some(Feature::Disabled),
196            Some(_) => None,
197        }
198    };
199    let hypervisor = lines.iter().find_map(|l| l.strip_prefix("hypervisor=")).and_then(|v| match v {
200        "True" => Some(true),
201        "False" => Some(false),
202        _ => None,
203    });
204    (feature("VirtualMachinePlatform"), feature("Microsoft-Windows-Subsystem-Linux"), hypervisor)
205}
206
207/// Where WSL 2 stands, and whether virtualization looks off in the firmware, with the signals
208/// read (for a log).
209#[derive(Clone, Copy, Debug)]
210#[non_exhaustive]
211pub struct Wsl {
212    /// Where it stands ([`classify`]).
213    pub state: WslState,
214    /// Virtualization looks off in the firmware ([`virtualization_off`]).
215    pub virtualization_off: bool,
216    /// The signals it was decided on.
217    pub probes: Probes,
218}
219
220/// How long `wsl.exe` may take.
221const WSL_TIMEOUT: Duration = Duration::from_secs(10);
222/// How long the WMI queries may take.
223const CIM_TIMEOUT: Duration = Duration::from_secs(20);
224/// How long a registry read may take.
225const REG_TIMEOUT: Duration = Duration::from_secs(10);
226
227/// The services' registry key.
228const SERVICES: &str = r"HKLM\SYSTEM\CurrentControlSet\Services";
229
230/// Where WSL 2 stands on the context's host, given what the caller did itself (`marks`): on
231/// Windows only, `None` elsewhere.
232pub async fn check(cx: &Context, marks: Marks) -> Option<Wsl> {
233    if cx.host.os != HostOs::Windows {
234        return None;
235    }
236    let probes = probe(cx, marks).await;
237    let state = classify(&probes);
238    Some(Wsl {
239        state,
240        virtualization_off: virtualization_off(&probes, state),
241        probes,
242    })
243}
244
245/// Every signal, the commands side by side. `wsl.exe` writes UTF-16 unless told otherwise: only
246/// its exit codes are read, but its output in a log stays readable.
247pub async fn probe(cx: &Context, marks: Marks) -> Probes {
248    let wsl = |arg: &str| {
249        let mut spec = ProcessSpec::new("wsl", [arg]);
250        spec.env.push(("WSL_UTF8".to_owned(), "1".to_owned()));
251        spec
252    };
253    let (status_spec, version_spec) = (wsl("--status"), wsl("--version"));
254    let cim_spec = ProcessSpec::new("powershell", ["-NoProfile", "-NonInteractive", "-EncodedCommand", &encoded(CIM_SCRIPT)]);
255    let (status, version, cim) = tokio::join!(
256        cx.probe_within(WSL_TIMEOUT, &status_spec),
257        cx.probe_within(WSL_TIMEOUT, &version_spec),
258        cx.probe_within(CIM_TIMEOUT, &cim_spec),
259    );
260    let cim_out = match &cim {
261        Ok(captured) if captured.success() => captured.stdout.join("\n"),
262        _ => String::new(),
263    };
264    let (vm_platform, wsl_feature, hypervisor) = parse_cim(&cim_out);
265    let lxss = format!(r"{SERVICES}\LxssManager");
266    let store = format!(r"{SERVICES}\WslService");
267    let servicing = r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending";
268    let session = r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager";
269    let (lxss, store, servicing) = ([lxss.as_str()], [store.as_str()], [servicing]);
270    let renames = [session, "/v", "PendingFileRenameOperations"];
271    let (lxss_service, wsl_service, reboot_pending, renames_pending) =
272        tokio::join!(registry(cx, &lxss), registry(cx, &store), registry(cx, &servicing), registry(cx, &renames),);
273    Probes {
274        status: outcome(&status),
275        version: outcome(&version),
276        lxss_service,
277        wsl_service,
278        vm_platform,
279        wsl_feature,
280        hypervisor,
281        reboot_pending,
282        renames_pending,
283        installed_this_boot: marks.installed_this_boot,
284        restarted_for_wsl: marks.restarted_for_wsl,
285    }
286}
287
288/// How a timed probe went.
289fn outcome(result: &Result<isothrum_runner::Captured, Unanswered>) -> Run {
290    match result {
291        Ok(captured) if captured.success() => Run::Ok,
292        Err(Unanswered::NotStarted(isothrum_runner::ProcessError::Missing { .. })) => Run::Missing,
293        Ok(_) | Err(Unanswered::NotStarted(_)) => Run::Failed,
294        Err(Unanswered::TimedOut(_)) => Run::TimedOut,
295    }
296}
297
298/// Whether a registry key (or, with `/v <name>`, a value) exists: `reg query` exits 0 when it
299/// does and 1 when it doesn't; `None` when `reg` couldn't tell (it didn't start, or ran out of
300/// time).
301async fn registry(cx: &Context, query: &[&str]) -> Option<bool> {
302    let spec = ProcessSpec::new("reg", std::iter::once("query").chain(query.iter().copied()));
303    match cx.probe_within(REG_TIMEOUT, &spec).await {
304        Ok(captured) => match captured.exit.code {
305            Some(0) => Some(true),
306            Some(1) => Some(false),
307            _ => None,
308        },
309        Err(_) => None,
310    }
311}
312
313/// A script for `powershell -EncodedCommand`: base64 of its UTF-16LE text (no quoting to get
314/// wrong on the command line).
315pub(crate) fn encoded(script: &str) -> String {
316    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
317    let bytes: Vec<u8> = script.encode_utf16().flat_map(u16::to_le_bytes).collect();
318    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
319    for chunk in bytes.chunks(3) {
320        let n = chunk.iter().enumerate().fold(0usize, |n, (i, b)| n | (usize::from(*b) << (16 - 8 * i)));
321        for i in 0..4 {
322            let sextet = ALPHABET.get((n >> (18 - 6 * i)) & 0x3f).copied().unwrap_or(b'=');
323            out.push(char::from(if i <= chunk.len() { sextet } else { b'=' }));
324        }
325    }
326    out
327}
328
329#[cfg(test)]
330mod tests;