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 && !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 if (!wsl && !platform_on && wsl_failed && (no_services || platform_off)) || (wsl && platform_off && !pending) {
154 return WslState::Missing;
155 }
156 WslState::Unknown
158}
159
160#[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
167pub 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#[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#[derive(Clone, Copy, Debug)]
210#[non_exhaustive]
211pub struct Wsl {
212 pub state: WslState,
214 pub virtualization_off: bool,
216 pub probes: Probes,
218}
219
220const WSL_TIMEOUT: Duration = Duration::from_secs(10);
222const CIM_TIMEOUT: Duration = Duration::from_secs(20);
224const REG_TIMEOUT: Duration = Duration::from_secs(10);
226
227const SERVICES: &str = r"HKLM\SYSTEM\CurrentControlSet\Services";
229
230pub 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
245pub 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
288fn 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
298async 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
313pub(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;