use std::time::Duration;
use isothrum_runner::ProcessSpec;
use serde::{Deserialize, Serialize};
use crate::context::Context;
use crate::exec::Unanswered;
use crate::host::HostOs;
#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub enum WslState {
Ready,
NeedsReboot,
Missing,
Unknown,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Run {
Ok,
Failed,
TimedOut,
Missing,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Feature {
Enabled,
Disabled,
Absent,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct Marks {
pub installed_this_boot: bool,
pub restarted_for_wsl: bool,
}
#[derive(Clone, Copy, Debug)]
pub struct Probes {
pub status: Run,
pub version: Run,
pub lxss_service: Option<bool>,
pub wsl_service: Option<bool>,
pub vm_platform: Option<Feature>,
pub wsl_feature: Option<Feature>,
pub hypervisor: Option<bool>,
pub reboot_pending: Option<bool>,
pub renames_pending: Option<bool>,
pub installed_this_boot: bool,
pub restarted_for_wsl: bool,
}
#[must_use]
pub fn classify(p: &Probes) -> WslState {
let store = p.version == Run::Ok || p.wsl_service == Some(true);
let inbox = p.lxss_service == Some(true) || p.wsl_feature == Some(Feature::Enabled);
let wsl = store || inbox;
let platform_on = p.vm_platform == Some(Feature::Enabled);
let platform_off = matches!(p.vm_platform, Some(Feature::Disabled | Feature::Absent));
let running = p.hypervisor == Some(true);
let hypervisor_running = p.hypervisor != Some(false);
let pending = p.reboot_pending == Some(true);
if p.installed_this_boot && (pending || p.renames_pending == Some(true)) {
return WslState::NeedsReboot;
}
if wsl && platform_on && running {
if !pending || p.status == Run::Ok || (store && !p.installed_this_boot) {
return WslState::Ready;
}
}
let answers_with_features_unread = wsl && p.status == Run::Ok && p.reboot_pending == Some(false) && p.vm_platform.is_none();
if answers_with_features_unread && hypervisor_running {
return WslState::Ready;
}
if p.installed_this_boot {
return WslState::NeedsReboot;
}
if (wsl || platform_on) && pending && !platform_off && !p.restarted_for_wsl {
return WslState::NeedsReboot;
}
let wsl_failed = matches!(p.status, Run::Failed | Run::Missing);
let no_services = p.lxss_service == Some(false) && p.wsl_service == Some(false);
if (!wsl && !platform_on && wsl_failed && (no_services || platform_off)) || (wsl && platform_off) {
return WslState::Missing;
}
WslState::Unknown
}
#[must_use]
pub fn virtualization_off(p: &Probes, state: WslState) -> bool {
state == WslState::Unknown && p.vm_platform == Some(Feature::Enabled) && p.hypervisor == Some(false)
}
pub const CIM_SCRIPT: &str = "$ProgressPreference = 'SilentlyContinue'
try {
$f = @(Get-CimInstance -ClassName Win32_OptionalFeature -Filter \"Name='VirtualMachinePlatform' OR Name='Microsoft-Windows-Subsystem-Linux'\" -ErrorAction Stop)
'features=ok'
foreach ($x in $f) { 'feature:' + $x.Name + '=' + [int]$x.InstallState }
} catch {}
try { 'hypervisor=' + [bool](Get-CimInstance -ClassName Win32_ComputerSystem -ErrorAction Stop).HypervisorPresent } catch {}
exit 0
";
#[must_use]
pub fn parse_cim(out: &str) -> (Option<Feature>, Option<Feature>, Option<bool>) {
let lines: Vec<&str> = out.lines().map(str::trim).collect();
let answered = lines.contains(&"features=ok");
let feature = |name: &str| {
if !answered {
return None;
}
let prefix = format!("feature:{name}=");
match lines.iter().find_map(|l| l.strip_prefix(prefix.as_str())) {
None | Some("3") => Some(Feature::Absent),
Some("1") => Some(Feature::Enabled),
Some("2") => Some(Feature::Disabled),
Some(_) => None,
}
};
let hypervisor = lines.iter().find_map(|l| l.strip_prefix("hypervisor=")).and_then(|v| match v {
"True" => Some(true),
"False" => Some(false),
_ => None,
});
(feature("VirtualMachinePlatform"), feature("Microsoft-Windows-Subsystem-Linux"), hypervisor)
}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct Wsl {
pub state: WslState,
pub virtualization_off: bool,
pub probes: Probes,
}
const WSL_TIMEOUT: Duration = Duration::from_secs(10);
const CIM_TIMEOUT: Duration = Duration::from_secs(20);
const REG_TIMEOUT: Duration = Duration::from_secs(10);
const SERVICES: &str = r"HKLM\SYSTEM\CurrentControlSet\Services";
pub async fn check(cx: &Context, marks: Marks) -> Option<Wsl> {
if cx.host.os != HostOs::Windows {
return None;
}
let probes = probe(cx, marks).await;
let state = classify(&probes);
Some(Wsl {
state,
virtualization_off: virtualization_off(&probes, state),
probes,
})
}
pub async fn probe(cx: &Context, marks: Marks) -> Probes {
let wsl = |arg: &str| {
let mut spec = ProcessSpec::new("wsl", [arg]);
spec.env.push(("WSL_UTF8".to_owned(), "1".to_owned()));
spec
};
let (status_spec, version_spec) = (wsl("--status"), wsl("--version"));
let cim_spec = ProcessSpec::new("powershell", ["-NoProfile", "-NonInteractive", "-EncodedCommand", &encoded(CIM_SCRIPT)]);
let (status, version, cim) = tokio::join!(
cx.probe_within(WSL_TIMEOUT, &status_spec),
cx.probe_within(WSL_TIMEOUT, &version_spec),
cx.probe_within(CIM_TIMEOUT, &cim_spec),
);
let cim_out = match &cim {
Ok(captured) if captured.success() => captured.stdout.join("\n"),
_ => String::new(),
};
let (vm_platform, wsl_feature, hypervisor) = parse_cim(&cim_out);
let lxss = format!(r"{SERVICES}\LxssManager");
let store = format!(r"{SERVICES}\WslService");
let servicing = r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending";
let session = r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager";
let (lxss, store, servicing) = ([lxss.as_str()], [store.as_str()], [servicing]);
let renames = [session, "/v", "PendingFileRenameOperations"];
let (lxss_service, wsl_service, reboot_pending, renames_pending) =
tokio::join!(registry(cx, &lxss), registry(cx, &store), registry(cx, &servicing), registry(cx, &renames),);
Probes {
status: outcome(&status),
version: outcome(&version),
lxss_service,
wsl_service,
vm_platform,
wsl_feature,
hypervisor,
reboot_pending,
renames_pending,
installed_this_boot: marks.installed_this_boot,
restarted_for_wsl: marks.restarted_for_wsl,
}
}
fn outcome(result: &Result<isothrum_runner::Captured, Unanswered>) -> Run {
match result {
Ok(captured) if captured.success() => Run::Ok,
Err(Unanswered::NotStarted(isothrum_runner::ProcessError::Missing { .. })) => Run::Missing,
Ok(_) | Err(Unanswered::NotStarted(_)) => Run::Failed,
Err(Unanswered::TimedOut(_)) => Run::TimedOut,
}
}
async fn registry(cx: &Context, query: &[&str]) -> Option<bool> {
let spec = ProcessSpec::new("reg", std::iter::once("query").chain(query.iter().copied()));
match cx.probe_within(REG_TIMEOUT, &spec).await {
Ok(captured) => match captured.exit.code {
Some(0) => Some(true),
Some(1) => Some(false),
_ => None,
},
Err(_) => None,
}
}
pub(crate) fn encoded(script: &str) -> String {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let bytes: Vec<u8> = script.encode_utf16().flat_map(u16::to_le_bytes).collect();
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
let n = chunk.iter().enumerate().fold(0usize, |n, (i, b)| n | (usize::from(*b) << (16 - 8 * i)));
for i in 0..4 {
let sextet = ALPHABET.get((n >> (18 - 6 * i)) & 0x3f).copied().unwrap_or(b'=');
out.push(char::from(if i <= chunk.len() { sextet } else { b'=' }));
}
}
out
}
#[cfg(test)]
mod tests;