isothrum_machine/setup/
windows.rs1use std::time::Duration;
7
8use crate::context::Context;
9use crate::exec::all_lines;
10use crate::install::{Step, StepFailed, run_step, step};
11
12const 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#[must_use]
25pub fn join_hyperv_admins_step() -> Step {
26 step("powershell", &["-NoProfile", "-NonInteractive", "-Command", JOIN_HYPERV_ADMINS])
27}
28
29pub 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
40pub const RESTART_NOTE_MAX: usize = 200;
42
43const ERROR_SHUTDOWN_IS_SCHEDULED: u32 = 1190;
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum Restart {
49 Scheduled,
51 AlreadyScheduled,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
57#[non_exhaustive]
58pub enum RestartFailed {
59 Note,
61 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
76pub 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
101fn 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 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}