1use 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#[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 Ready,
40 NeedsReboot,
42 Missing,
44 Unknown,
46}
47
48#[derive(Clone, Copy, PartialEq, Eq, Debug)]
50pub enum Run {
51 Ok,
53 Failed,
55 TimedOut,
57 Missing,
59}
60
61#[derive(Clone, Copy, PartialEq, Eq, Debug)]
63pub enum Feature {
64 Enabled,
66 Disabled,
68 Absent,
70}
71
72#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
75pub struct Marks {
76 pub installed_this_boot: bool,
78 pub restarted_for_wsl: bool,
80}
81
82#[derive(Clone, Copy, Debug)]
84pub struct Probes {
85 pub status: Run,
87 pub version: Run,
89 pub lxss_service: Option<bool>,
91 pub wsl_service: Option<bool>,
93 pub vm_platform: Option<Feature>,
95 pub wsl_feature: Option<Feature>,
97 pub hypervisor: Option<bool>,
99 pub reboot_pending: Option<bool>,
101 pub renames_pending: Option<bool>,
103 pub installed_this_boot: bool,
105 pub restarted_for_wsl: bool,
107}
108
109#[must_use]
111pub fn classify(p: &Probes) -> WslState {
112 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 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 if p.installed_this_boot && (pending || p.renames_pending == Some(true)) {
127 return WslState::NeedsReboot;
128 }
129 if wsl && platform_on && running {
130 if !pending || p.status == Run::Ok || (store && !p.installed_this_boot) {
134 return WslState::Ready;
135 }
136 }
137 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 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 if (!wsl && !platform_on && wsl_failed && (no_services || platform_off)) || (wsl && platform_off) {
160 return WslState::Missing;
161 }
162 WslState::Unknown
164}
165
166#[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
173pub 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#[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#[derive(Clone, Copy, Debug)]
216#[non_exhaustive]
217pub struct Wsl {
218 pub state: WslState,
220 pub virtualization_off: bool,
222 pub probes: Probes,
224}
225
226const WSL_TIMEOUT: Duration = Duration::from_secs(10);
228const CIM_TIMEOUT: Duration = Duration::from_secs(20);
230const REG_TIMEOUT: Duration = Duration::from_secs(10);
232
233const SERVICES: &str = r"HKLM\SYSTEM\CurrentControlSet\Services";
235
236pub 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
251pub 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
294fn 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
304async 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
319pub(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;