Skip to main content

isothrum_machine/setup/
windows.rs

1//! What a setup does on Windows beyond installs: this account joining "Hyper-V Administrators"
2//! through one UAC prompt ([`join_hyperv_admins`]), so Vagrant drives Hyper-V for it without an
3//! elevated token from its next sign-in on; and the restart that finishes turning a Windows
4//! feature on ([`schedule_restart`], [`super::Action::Restart`]).
5
6use std::time::Duration;
7
8use crate::context::Context;
9use crate::exec::all_lines;
10use crate::install::{Step, StepFailed, run_step, step};
11
12/// Adds the account running it to "Hyper-V Administrators" (`S-1-5-32-578`, by SID: the group's
13/// name is translated), elevated through the UAC prompt (`-Verb RunAs`). The account is read
14/// before the prompt (an administrator approving it for a standard account runs the elevated half
15/// as themselves), and handed to the elevated half inside its own encoded script. One already in
16/// the group is fine; a declined prompt exits 1223 (`ERROR_CANCELLED`), which reads as cancelled.
17const JOIN_HYPERV_ADMINS: &str = "$a = [Security.Principal.WindowsIdentity]::GetCurrent().Name -replace '''', ''''''; \
18$s = '$ErrorActionPreference = ''Stop''; try { Add-LocalGroupMember -SID ''S-1-5-32-578'' -Member ''' + $a + ''' } catch [Microsoft.PowerShell.Commands.MemberExistsException] { }'; \
19$e = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($s)); \
20try { $p = Start-Process -FilePath powershell.exe -ArgumentList '-NoProfile','-NonInteractive','-EncodedCommand',$e -Verb RunAs -WindowStyle Hidden -Wait -PassThru; exit $p.ExitCode } catch { exit 1223 }";
21
22/// The step that adds this account to "Hyper-V Administrators" through one UAC prompt: the
23/// membership applies from the account's next sign-in.
24#[must_use]
25pub fn join_hyperv_admins_step() -> Step {
26    step("powershell", &["-NoProfile", "-NonInteractive", "-Command", JOIN_HYPERV_ADMINS])
27}
28
29/// Adds this account to "Hyper-V Administrators" ([`join_hyperv_admins_step`]), each line it
30/// prints handed to `on_line`.
31///
32/// # Errors
33///
34/// [`StepFailed`]: a declined prompt is [`StepFailed::Exited`] with
35/// [`crate::install::exit_codes::Known::Cancelled`].
36pub async fn join_hyperv_admins(cx: &Context, on_line: &mut (dyn FnMut(&str) + Send)) -> Result<(), StepFailed> {
37    run_step(cx, &join_hyperv_admins_step(), on_line).await.map(drop)
38}
39
40/// The longest note a restart shows while Windows counts down (`shutdown.exe` takes 512).
41pub const RESTART_NOTE_MAX: usize = 200;
42
43/// `shutdown.exe`'s refusal because a shutdown is already scheduled (`ERROR_SHUTDOWN_IS_SCHEDULED`).
44const ERROR_SHUTDOWN_IS_SCHEDULED: u32 = 1190;
45
46/// How a restart was asked for.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum Restart {
49    /// Windows counts down to it.
50    Scheduled,
51    /// One was scheduled already (another window's, the user's own): the same restart.
52    AlreadyScheduled,
53}
54
55/// Why a restart wasn't scheduled.
56#[derive(Debug, Clone, PartialEq, Eq)]
57#[non_exhaustive]
58pub enum RestartFailed {
59    /// The note isn't one line of at most [`RESTART_NOTE_MAX`] characters.
60    Note,
61    /// `shutdown.exe` didn't run, or refused: why.
62    Refused(String),
63}
64
65impl std::fmt::Display for RestartFailed {
66    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67        match self {
68            RestartFailed::Note => write!(f, "a restart's note is one line of at most {RESTART_NOTE_MAX} characters"),
69            RestartFailed::Refused(why) => write!(f, "the restart couldn't be scheduled: {why}"),
70        }
71    }
72}
73
74impl std::error::Error for RestartFailed {}
75
76/// Asks Windows to restart in `after` (`shutdown /r /t <s> /c <note>`), its countdown showing
77/// `note`. A restart scheduled already is [`Restart::AlreadyScheduled`], not a failure.
78///
79/// # Errors
80///
81/// [`RestartFailed`]: the note isn't one, or `shutdown.exe` didn't run or refused.
82pub async fn schedule_restart(cx: &Context, after: Duration, note: &str) -> Result<Restart, RestartFailed> {
83    let note = note.trim();
84    if note.is_empty() || note.chars().count() > RESTART_NOTE_MAX || note.chars().any(char::is_control) {
85        return Err(RestartFailed::Note);
86    }
87    let seconds = after.as_secs().to_string();
88    let captured = cx
89        .probe("shutdown", &["/r", "/t", &seconds, "/c", note])
90        .await
91        .map_err(|e| RestartFailed::Refused(e.to_string()))?;
92    if captured.success() {
93        Ok(Restart::Scheduled)
94    } else if win32_error(&all_lines(&captured)) == Some(ERROR_SHUTDOWN_IS_SCHEDULED) {
95        Ok(Restart::AlreadyScheduled)
96    } else {
97        Err(RestartFailed::Refused(captured.reason()))
98    }
99}
100
101/// The Win32 error `said` ends with: Windows' own tools end their message with it in
102/// parentheses (`A system shutdown has already been scheduled.(1190)`) in every display language.
103fn win32_error(said: &str) -> Option<u32> {
104    let said = said.trim_end().trim_end_matches('.');
105    let (_, number) = said.strip_suffix(')')?.rsplit_once('(')?;
106    number.trim().parse().ok()
107}
108
109#[cfg(test)]
110mod tests {
111    use isothrum_runner::fake::{FakeProcesses, Reply};
112
113    use super::*;
114    use crate::install::exit_codes::Known;
115    use crate::testing::answered_by;
116
117    #[test]
118    fn joining_hyperv_administrators_is_one_uac_prompt_by_the_groups_sid() {
119        let step = join_hyperv_admins_step();
120        assert_eq!(step.program, "powershell");
121        let script = step.args.last().unwrap();
122        for part in [
123            "Add-LocalGroupMember -SID ''S-1-5-32-578''",
124            "MemberExistsException",
125            "WindowsIdentity]::GetCurrent().Name",
126            "-Verb RunAs",
127            "-Wait -PassThru",
128            "catch { exit 1223 }",
129        ] {
130            assert!(script.contains(part), "{part} in {script}");
131        }
132        // Quoted for PowerShell alone: a double quote would be escaped for the C runtime instead.
133        assert!(!script.contains('"'), "{script}");
134    }
135
136    #[tokio::test]
137    async fn a_declined_prompt_to_join_reads_as_cancelled() {
138        let cx = answered_by(FakeProcesses::script().expect("powershell *", Reply::fail(1223, "")).build());
139        let err = join_hyperv_admins(&cx, &mut |_| {}).await.unwrap_err();
140        assert!(
141            matches!(
142                err,
143                StepFailed::Exited {
144                    known: Some(Known::Cancelled),
145                    ..
146                }
147            ),
148            "{err:?}"
149        );
150        let joined = answered_by(FakeProcesses::script().expect("powershell *", Reply::ok("")).build());
151        assert_eq!(join_hyperv_admins(&joined, &mut |_| {}).await, Ok(()));
152    }
153
154    #[tokio::test]
155    async fn a_restart_is_scheduled_with_its_note_or_found_scheduled_already() {
156        let fake = std::sync::Arc::new(FakeProcesses::script().expect("shutdown /r /t 5 /c", Reply::ok("")).build());
157        let cx = crate::testing::shared(std::sync::Arc::<FakeProcesses>::clone(&fake));
158        assert_eq!(
159            schedule_restart(&cx, Duration::from_secs(5), " Restarting to finish WSL 2. ").await,
160            Ok(Restart::Scheduled)
161        );
162        assert_eq!(fake.made("shutdown")[0].args.last().map(String::as_str), Some("Restarting to finish WSL 2."));
163
164        let french = "Un arrêt du système a déjà été planifié.(1190)\r";
165        let scheduled = answered_by(FakeProcesses::script().expect("shutdown *", Reply::fail(1, french)).build());
166        assert_eq!(
167            schedule_restart(&scheduled, Duration::from_secs(5), "note").await,
168            Ok(Restart::AlreadyScheduled)
169        );
170
171        let denied = answered_by(FakeProcesses::script().expect("shutdown *", Reply::fail(1, "Access is denied.(5)")).build());
172        assert!(
173            matches!(schedule_restart(&denied, Duration::from_secs(5), "note").await, Err(RestartFailed::Refused(why)) if why.contains("Access is denied"))
174        );
175    }
176
177    #[tokio::test]
178    async fn a_restart_note_is_one_short_line() {
179        let cx = answered_by(FakeProcesses::script().build());
180        for note in ["", "two\nlines", &"x".repeat(RESTART_NOTE_MAX + 1)] {
181            assert_eq!(schedule_restart(&cx, Duration::from_secs(5), note).await, Err(RestartFailed::Note), "{note:?}");
182        }
183    }
184
185    #[test]
186    fn the_win32_error_is_read_from_the_end_whatever_the_language() {
187        assert_eq!(win32_error("A system shutdown has already been scheduled.(1190)\r\n"), Some(1190));
188        assert_eq!(win32_error("listening on port 1190"), None);
189        assert_eq!(win32_error(""), None);
190    }
191}