Skip to main content

isothrum_machine/install/
windows.rs

1//! Installs and removals on Windows: winget's packages, WSL's own installer and Hyper-V's Windows
2//! feature (DISM), each elevated through Windows' own UAC prompt, and HashiCorp's signed MSI for
3//! VMware's utility. A declined prompt exits `ERROR_CANCELLED` (1223), which reads as cancelled
4//! ([`super::exit_codes::Known::Cancelled`]).
5//!
6//! winget is never told to accept anything for its user: no `--accept-package-agreements`, no
7//! `--accept-source-agreements`. No package a setup installs, nor the `winget` source, has an
8//! agreement today; one that asks for it stops the install, and its user accepts it running
9//! winget themselves ([`super::exit_codes::Known::AgreementToAccept`]). Docker's manifest adds
10//! `--accept-license` to its installer's switches, so Docker's are given in full instead
11//! ([`DOCKER_SWITCHES`]): Docker Desktop shows its agreement at its first start.
12
13use crate::host::{Arch, HostOs};
14use crate::install::steps::{NotServed, Step, step};
15use crate::install::{Dependency, Refusal, vmware_utility};
16use crate::providers::ProviderRow;
17
18/// `winget <verb> <id>`, from the `winget` source alone. Without `--source`, winget asks every
19/// source it has, the Microsoft Store's (`msstore`) too, and one that fails stops the command: on a
20/// clean Windows 11 the Store source's certificate pinning failed (0x8a15005e, "The server
21/// certificate did not match any of the expected values") and Docker Desktop's install with it.
22/// Every package a setup installs is in the `winget` source.
23#[must_use]
24pub fn winget(verb: &str, id: &str, extra: &[&str]) -> Step {
25    let mut args = vec![verb, "-e", "--id", id, "--source", "winget"];
26    args.extend_from_slice(extra);
27    step("winget", &args)
28}
29
30/// Docker Desktop's installer switches, in place of its winget manifest's (`install --quiet`, and
31/// `--accept-license --backend=wsl-2 --no-windows-containers` as its custom ones): the same but
32/// `--accept-license`, which would accept Docker's Subscription Service Agreement for its user.
33pub const DOCKER_SWITCHES: &str = "install --quiet --backend=wsl-2 --no-windows-containers";
34
35/// Turns WSL's and the Virtual Machine Platform's features on and installs the WSL 2 kernel,
36/// through Windows' UAC prompt; the features take effect at the next restart. `-PassThru` surfaces
37/// `wsl.exe`'s own exit code (without it PowerShell exits 0 whatever happened).
38const WSL_ON: &str = "try { $p = Start-Process -FilePath wsl.exe -ArgumentList '--install','--no-distribution' -Verb RunAs -Wait -PassThru; exit $p.ExitCode } catch { exit 1223 }";
39
40/// Turns Hyper-V on with Windows' own servicing tool (DISM), elevated: its "restart to finish"
41/// (3010) is a success. On Windows Home, which has no Hyper-V, it stops before anything runs with
42/// [`NOT_SERVED`](super::steps::NOT_SERVED) (69), for a UI to word.
43const HYPERV_ON: &str = "if ((Get-ItemProperty 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion').EditionID -like 'Core*') { exit 69 }; try { $p = Start-Process -FilePath dism.exe -ArgumentList '/Online','/Enable-Feature','/FeatureName:Microsoft-Hyper-V','/All','/NoRestart','/Quiet' -Verb RunAs -Wait -PassThru; if ($p.ExitCode -eq 3010) { exit 0 }; exit $p.ExitCode } catch { exit 1223 }";
44
45/// Why `dep` isn't installed on a CPU `arch`: its vendor ships no build for Windows on it
46/// ([`Dependency::no_build`]); on Windows on Arm, the hypervisor it is or serves (VMware's utility
47/// serves VMware Workstation) isn't built for it ([`ProviderRow::of`]).
48fn not_on_arm(dep: Dependency, arch: Arch) -> Option<Refusal> {
49    if let Some(why) = dep.no_build(HostOs::Windows, arch) {
50        return Some(Refusal::NoBuild {
51            dependency: dep,
52            os: HostOs::Windows,
53            arch,
54            why,
55        });
56    }
57    let provider = dep.serves().or_else(|| dep.hypervisor())?;
58    (arch == Arch::Arm64 && !ProviderRow::of(provider).windows_on_arm).then_some(Refusal::NotOnWindowsOnArm { dependency: dep, provider })
59}
60
61/// The install of `dep` on Windows, on a CPU `arch`: its winget package, or WSL's, Hyper-V's and
62/// VMware's utility's own elevated installers.
63///
64/// # Errors
65///
66/// [`Refusal`]: why it can't be installed here.
67pub fn install(dep: Dependency, arch: Arch) -> Result<Vec<Step>, Refusal> {
68    dep.runs_here(HostOs::Windows)?;
69    if let Some(refusal) = not_on_arm(dep, arch) {
70        return Err(refusal);
71    }
72    if let Some(id) = dep.row().winget {
73        let switches: &[&str] = if dep == Dependency::Docker { &["--override", DOCKER_SWITCHES] } else { &[] };
74        return Ok(vec![winget("install", id, switches)]);
75    }
76    match dep {
77        Dependency::Wsl => Ok(vec![step("powershell", &["-NoProfile", "-Command", WSL_ON])]),
78        Dependency::Hyperv => Ok(vec![
79            step("powershell", &["-NoProfile", "-Command", HYPERV_ON]).not_served(NotServed::HypervEdition),
80        ]),
81        Dependency::VmwareUtility => Ok(vec![vmware_utility::windows_install()]),
82        Dependency::Utm
83        | Dependency::Libvirt
84        | Dependency::Qemu
85        | Dependency::Docker
86        | Dependency::Vagrant
87        | Dependency::Terraform
88        | Dependency::Virtualbox
89        | Dependency::Awscli
90        | Dependency::Azurecli
91        | Dependency::Gcloud => Err(Refusal::NotHere {
92            dependency: dep,
93            os: HostOs::Windows,
94        }),
95    }
96}
97
98/// The removal of `dep` on Windows: its winget package, VMware's utility by its MSI's product
99/// code; the Windows features are their user's to turn off in Windows Features.
100///
101/// # Errors
102///
103/// [`Refusal::WindowsFeature`] for WSL and Hyper-V, [`Refusal::NotHere`] for what doesn't run on
104/// Windows.
105pub fn uninstall(dep: Dependency) -> Result<Vec<Step>, Refusal> {
106    if let Some(id) = dep.row().winget {
107        return Ok(vec![winget("uninstall", id, &[])]);
108    }
109    match dep {
110        Dependency::VmwareUtility => Ok(vec![vmware_utility::windows_uninstall()]),
111        Dependency::Wsl | Dependency::Hyperv => Err(Refusal::WindowsFeature { dependency: dep }),
112        _ => Err(Refusal::NotHere {
113            dependency: dep,
114            os: HostOs::Windows,
115        }),
116    }
117}
118
119#[cfg(test)]
120mod tests;