| 1 | #![cfg_attr(not(windows), allow(dead_code))] |
| 2 | |
| 3 | use std::io; |
| 4 | use std::path::{Path, PathBuf}; |
| 5 | use std::process::Command; |
| 6 | use std::time::Duration; |
| 7 | |
| 8 | pub const POLL_INTERVAL: Duration = Duration::from_secs(15); |
| 9 | |
| 10 | const UPDATE_DIRECTORY: &str = "update"; |
| 11 | const EXE_NAME: &str = "teams.exe"; |
| 12 | const OLD_EXE_NAME: &str = "teams.old.exe"; |
| 13 | const PDB_NAME: &str = "teams.pdb"; |
| 14 | const VERSION_FILE_NAME: &str = "version.txt"; |
| 15 | pub const RELAUNCH_ENV: &str = "RUSTY_TEAMS_RELAUNCH"; |
| 16 | const CLEANUP_ATTEMPTS: u32 = 30; |
| 17 | const CLEANUP_INTERVAL: Duration = Duration::from_secs(1); |
| 18 | const QUIT_GRACE: Duration = Duration::from_secs(3); |
| 19 | const PREVIOUS_EXIT_TIMEOUT: Duration = Duration::from_secs(30); |
| 20 | |
| 21 | pub fn running_version() -> &'static str { |
| 22 | crate::version::build_version() |
| 23 | } |
| 24 | |
| 25 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 26 | pub enum UpdateStatus { |
| 27 | UpToDate, |
| 28 | Ready, |
| 29 | Installing, |
| 30 | Failed(String), |
| 31 | } |
| 32 | |
| 33 | #[derive(Debug, Clone, Copy)] |
| 34 | pub struct IdleInputs { |
| 35 | pub window_active: bool, |
| 36 | pub composer_empty: bool, |
| 37 | pub send_in_flight: bool, |
| 38 | } |
| 39 | |
| 40 | pub fn is_idle(inputs: IdleInputs) -> bool { |
| 41 | !inputs.window_active && inputs.composer_empty && !inputs.send_in_flight |
| 42 | } |
| 43 | |
| 44 | pub fn update_is_ready(running: &str, published: Option<&str>, update_exe_exists: bool) -> bool { |
| 45 | update_exe_exists |
| 46 | && published.is_some_and(|version| { |
| 47 | let version = version.trim(); |
| 48 | !version.is_empty() && version != running |
| 49 | }) |
| 50 | } |
| 51 | |
| 52 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 53 | pub struct UpdatePaths { |
| 54 | pub exe: PathBuf, |
| 55 | pub old_exe: PathBuf, |
| 56 | pub update_exe: PathBuf, |
| 57 | pub version_file: PathBuf, |
| 58 | pub pdb: PathBuf, |
| 59 | pub update_pdb: PathBuf, |
| 60 | } |
| 61 | |
| 62 | impl UpdatePaths { |
| 63 | pub fn beside(exe: &Path) -> UpdatePaths { |
| 64 | let directory = exe.parent().unwrap_or_else(|| Path::new(".")); |
| 65 | let update_directory = directory.join(UPDATE_DIRECTORY); |
| 66 | UpdatePaths { |
| 67 | exe: exe.to_owned(), |
| 68 | old_exe: directory.join(OLD_EXE_NAME), |
| 69 | update_exe: update_directory.join(EXE_NAME), |
| 70 | version_file: update_directory.join(VERSION_FILE_NAME), |
| 71 | pdb: directory.join(PDB_NAME), |
| 72 | update_pdb: update_directory.join(PDB_NAME), |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 78 | pub enum FileOperation { |
| 79 | RemoveIfExists(PathBuf), |
| 80 | Rename { from: PathBuf, to: PathBuf }, |
| 81 | ReplaceIfPresent { from: PathBuf, to: PathBuf }, |
| 82 | } |
| 83 | |
| 84 | pub trait FileSystem { |
| 85 | fn exists(&self, path: &Path) -> bool; |
| 86 | fn rename(&self, from: &Path, to: &Path) -> io::Result<()>; |
| 87 | fn remove_file(&self, path: &Path) -> io::Result<()>; |
| 88 | } |
| 89 | |
| 90 | pub struct RealFileSystem; |
| 91 | |
| 92 | impl FileSystem for RealFileSystem { |
| 93 | fn exists(&self, path: &Path) -> bool { |
| 94 | path.exists() |
| 95 | } |
| 96 | |
| 97 | fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { |
| 98 | std::fs::rename(from, to) |
| 99 | } |
| 100 | |
| 101 | fn remove_file(&self, path: &Path) -> io::Result<()> { |
| 102 | std::fs::remove_file(path) |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | pub fn swap_plan(paths: &UpdatePaths) -> Vec<FileOperation> { |
| 107 | vec![ |
| 108 | FileOperation::RemoveIfExists(paths.old_exe.clone()), |
| 109 | FileOperation::Rename { |
| 110 | from: paths.exe.clone(), |
| 111 | to: paths.old_exe.clone(), |
| 112 | }, |
| 113 | FileOperation::Rename { |
| 114 | from: paths.update_exe.clone(), |
| 115 | to: paths.exe.clone(), |
| 116 | }, |
| 117 | FileOperation::ReplaceIfPresent { |
| 118 | from: paths.update_pdb.clone(), |
| 119 | to: paths.pdb.clone(), |
| 120 | }, |
| 121 | FileOperation::RemoveIfExists(paths.version_file.clone()), |
| 122 | ] |
| 123 | } |
| 124 | |
| 125 | fn apply_operation(files: &dyn FileSystem, operation: &FileOperation) -> io::Result<()> { |
| 126 | match operation { |
| 127 | FileOperation::RemoveIfExists(path) => { |
| 128 | if files.exists(path) { |
| 129 | files.remove_file(path)?; |
| 130 | } |
| 131 | Ok(()) |
| 132 | } |
| 133 | FileOperation::Rename { from, to } => files.rename(from, to), |
| 134 | FileOperation::ReplaceIfPresent { from, to } => { |
| 135 | if files.exists(from) { |
| 136 | if files.exists(to) { |
| 137 | let _ = files.remove_file(to); |
| 138 | } |
| 139 | let _ = files.rename(from, to); |
| 140 | } |
| 141 | Ok(()) |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | /// Runs the plan. On failure undoes the completed renames and returns the error. |
| 147 | pub fn apply_plan( |
| 148 | files: &dyn FileSystem, |
| 149 | plan: &[FileOperation], |
| 150 | ) -> Result<Vec<FileOperation>, String> { |
| 151 | let mut completed = Vec::new(); |
| 152 | for operation in plan { |
| 153 | if let Err(error) = apply_operation(files, operation) { |
| 154 | roll_back(files, &completed); |
| 155 | return Err(format!("{operation:?}: {error}")); |
| 156 | } |
| 157 | completed.push(operation.clone()); |
| 158 | } |
| 159 | Ok(completed) |
| 160 | } |
| 161 | |
| 162 | pub fn roll_back(files: &dyn FileSystem, completed: &[FileOperation]) { |
| 163 | for operation in completed.iter().rev() { |
| 164 | if let FileOperation::Rename { from, to } = operation { |
| 165 | let _ = files.rename(to, from); |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | pub fn check(paths: &UpdatePaths) -> bool { |
| 171 | let published = std::fs::read_to_string(&paths.version_file).ok(); |
| 172 | update_is_ready( |
| 173 | running_version(), |
| 174 | published.as_deref(), |
| 175 | paths.update_exe.exists(), |
| 176 | ) |
| 177 | } |
| 178 | |
| 179 | pub fn current_paths() -> Option<UpdatePaths> { |
| 180 | std::env::current_exe() |
| 181 | .ok() |
| 182 | .map(|exe| UpdatePaths::beside(&exe)) |
| 183 | } |
| 184 | |
| 185 | pub fn install_and_relaunch(paths: &UpdatePaths) -> Result<(), String> { |
| 186 | let files = RealFileSystem; |
| 187 | let completed = apply_plan(&files, &swap_plan(paths))?; |
| 188 | match Command::new(&paths.exe) |
| 189 | .args(std::env::args_os().skip(1)) |
| 190 | .env(RELAUNCH_ENV, std::process::id().to_string()) |
| 191 | .spawn() |
| 192 | { |
| 193 | Ok(_) => Ok(()), |
| 194 | Err(error) => { |
| 195 | roll_back(&files, &completed); |
| 196 | Err(format!("Start: {error}")) |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | pub fn previous_process_id(relaunch_value: &str) -> Option<u32> { |
| 202 | relaunch_value.trim().parse().ok() |
| 203 | } |
| 204 | |
| 205 | pub fn wait_for_previous_exit(relaunch_value: &str) { |
| 206 | if let Some(process_id) = previous_process_id(relaunch_value) { |
| 207 | platform::wait_for_exit(process_id, PREVIOUS_EXIT_TIMEOUT); |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | pub fn exit_after_grace() { |
| 212 | std::thread::spawn(|| { |
| 213 | std::thread::sleep(QUIT_GRACE); |
| 214 | exit_now(); |
| 215 | }); |
| 216 | } |
| 217 | |
| 218 | /// Skips DLL unload, which takes seconds with WebRTC and WebView2 loaded and keeps the database locked. |
| 219 | pub fn exit_now() -> ! { |
| 220 | platform::terminate_current(); |
| 221 | std::process::exit(0) |
| 222 | } |
| 223 | |
| 224 | #[cfg(windows)] |
| 225 | mod platform { |
| 226 | use std::time::Duration; |
| 227 | |
| 228 | use windows::Win32::Foundation::CloseHandle; |
| 229 | use windows::Win32::System::Threading::{ |
| 230 | GetCurrentProcess, OpenProcess, PROCESS_SYNCHRONIZE, TerminateProcess, WaitForSingleObject, |
| 231 | }; |
| 232 | |
| 233 | pub fn terminate_current() { |
| 234 | let _ = unsafe { TerminateProcess(GetCurrentProcess(), 0) }; |
| 235 | } |
| 236 | |
| 237 | pub fn wait_for_exit(process_id: u32, timeout: Duration) { |
| 238 | let Ok(handle) = (unsafe { OpenProcess(PROCESS_SYNCHRONIZE, false, process_id) }) else { |
| 239 | return; |
| 240 | }; |
| 241 | unsafe { |
| 242 | WaitForSingleObject(handle, timeout.as_millis() as u32); |
| 243 | let _ = CloseHandle(handle); |
| 244 | } |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | #[cfg(not(windows))] |
| 249 | mod platform { |
| 250 | use std::time::Duration; |
| 251 | |
| 252 | pub fn wait_for_exit(_process_id: u32, _timeout: Duration) {} |
| 253 | |
| 254 | pub fn terminate_current() {} |
| 255 | } |
| 256 | |
| 257 | /// Reading the new exe once lets the virus scanner finish before the restart, which otherwise blocks process start for seconds. |
| 258 | pub fn prescan(update_exe: &Path) { |
| 259 | if let Ok(mut file) = std::fs::File::open(update_exe) { |
| 260 | let _ = io::copy(&mut file, &mut io::sink()); |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | pub fn clean_up_old_binary() { |
| 265 | let Some(paths) = current_paths() else { |
| 266 | return; |
| 267 | }; |
| 268 | if !paths.old_exe.exists() { |
| 269 | return; |
| 270 | } |
| 271 | std::thread::spawn(move || { |
| 272 | for _ in 0..CLEANUP_ATTEMPTS { |
| 273 | if std::fs::remove_file(&paths.old_exe).is_ok() || !paths.old_exe.exists() { |
| 274 | return; |
| 275 | } |
| 276 | std::thread::sleep(CLEANUP_INTERVAL); |
| 277 | } |
| 278 | }); |
| 279 | } |
| 280 | |
| 281 | #[cfg(test)] |
| 282 | mod tests { |
| 283 | use super::*; |
| 284 | use std::fs; |
| 285 | |
| 286 | fn idle() -> IdleInputs { |
| 287 | IdleInputs { |
| 288 | window_active: false, |
| 289 | composer_empty: true, |
| 290 | send_in_flight: false, |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | #[test] |
| 295 | fn idle_needs_all_three_conditions() { |
| 296 | assert!(is_idle(idle())); |
| 297 | assert!(!is_idle(IdleInputs { |
| 298 | window_active: true, |
| 299 | ..idle() |
| 300 | })); |
| 301 | assert!(!is_idle(IdleInputs { |
| 302 | composer_empty: false, |
| 303 | ..idle() |
| 304 | })); |
| 305 | assert!(!is_idle(IdleInputs { |
| 306 | send_in_flight: true, |
| 307 | ..idle() |
| 308 | })); |
| 309 | } |
| 310 | |
| 311 | #[test] |
| 312 | fn update_needs_a_different_version_and_an_exe() { |
| 313 | assert!(update_is_ready("a-1", Some("b-2\n"), true)); |
| 314 | assert!(!update_is_ready("a-1", Some("a-1\n"), true)); |
| 315 | assert!(!update_is_ready("a-1", Some("b-2"), false)); |
| 316 | assert!(!update_is_ready("a-1", None, true)); |
| 317 | assert!(!update_is_ready("a-1", Some(" \n"), true)); |
| 318 | } |
| 319 | |
| 320 | #[test] |
| 321 | fn plan_lists_the_operations_in_order() { |
| 322 | let paths = UpdatePaths::beside(Path::new("/app/teams.exe")); |
| 323 | assert_eq!(paths.update_exe, Path::new("/app/update/teams.exe")); |
| 324 | let plan = swap_plan(&paths); |
| 325 | assert_eq!(plan.len(), 5); |
| 326 | assert_eq!( |
| 327 | plan[1], |
| 328 | FileOperation::Rename { |
| 329 | from: paths.exe.clone(), |
| 330 | to: paths.old_exe.clone() |
| 331 | } |
| 332 | ); |
| 333 | assert_eq!( |
| 334 | plan[2], |
| 335 | FileOperation::Rename { |
| 336 | from: paths.update_exe.clone(), |
| 337 | to: paths.exe.clone() |
| 338 | } |
| 339 | ); |
| 340 | } |
| 341 | |
| 342 | fn install(directory: &Path) -> UpdatePaths { |
| 343 | let paths = UpdatePaths::beside(&directory.join("teams.exe")); |
| 344 | fs::create_dir_all(paths.update_exe.parent().unwrap()).unwrap(); |
| 345 | fs::write(&paths.exe, "old").unwrap(); |
| 346 | fs::write(&paths.update_exe, "new").unwrap(); |
| 347 | fs::write(&paths.version_file, "b-2").unwrap(); |
| 348 | paths |
| 349 | } |
| 350 | |
| 351 | #[test] |
| 352 | fn swap_replaces_the_exe_and_keeps_the_old_one() { |
| 353 | let directory = tempfile::tempdir().unwrap(); |
| 354 | let paths = install(directory.path()); |
| 355 | apply_plan(&RealFileSystem, &swap_plan(&paths)).unwrap(); |
| 356 | assert_eq!(fs::read_to_string(&paths.exe).unwrap(), "new"); |
| 357 | assert_eq!(fs::read_to_string(&paths.old_exe).unwrap(), "old"); |
| 358 | assert!(!paths.update_exe.exists()); |
| 359 | assert!(!paths.version_file.exists()); |
| 360 | } |
| 361 | |
| 362 | #[test] |
| 363 | fn swap_moves_the_symbols_along_and_works_without_them() { |
| 364 | let directory = tempfile::tempdir().unwrap(); |
| 365 | let paths = install(directory.path()); |
| 366 | apply_plan(&RealFileSystem, &swap_plan(&paths)).unwrap(); |
| 367 | assert!(!paths.pdb.exists()); |
| 368 | let paths = install(directory.path()); |
| 369 | fs::write(&paths.pdb, "old symbols").unwrap(); |
| 370 | fs::write(&paths.update_pdb, "new symbols").unwrap(); |
| 371 | apply_plan(&RealFileSystem, &swap_plan(&paths)).unwrap(); |
| 372 | assert_eq!(fs::read_to_string(&paths.pdb).unwrap(), "new symbols"); |
| 373 | assert!(!paths.update_pdb.exists()); |
| 374 | } |
| 375 | |
| 376 | #[test] |
| 377 | fn swap_replaces_a_leftover_old_exe() { |
| 378 | let directory = tempfile::tempdir().unwrap(); |
| 379 | let paths = install(directory.path()); |
| 380 | fs::write(&paths.old_exe, "stale").unwrap(); |
| 381 | apply_plan(&RealFileSystem, &swap_plan(&paths)).unwrap(); |
| 382 | assert_eq!(fs::read_to_string(&paths.old_exe).unwrap(), "old"); |
| 383 | } |
| 384 | |
| 385 | struct FailingRename { |
| 386 | fail_on: PathBuf, |
| 387 | } |
| 388 | |
| 389 | impl FileSystem for FailingRename { |
| 390 | fn exists(&self, path: &Path) -> bool { |
| 391 | path.exists() |
| 392 | } |
| 393 | |
| 394 | fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { |
| 395 | if from == self.fail_on { |
| 396 | return Err(io::Error::other("locked")); |
| 397 | } |
| 398 | std::fs::rename(from, to) |
| 399 | } |
| 400 | |
| 401 | fn remove_file(&self, path: &Path) -> io::Result<()> { |
| 402 | std::fs::remove_file(path) |
| 403 | } |
| 404 | } |
| 405 | |
| 406 | #[test] |
| 407 | fn failed_step_rolls_back_so_teams_exe_survives() { |
| 408 | let directory = tempfile::tempdir().unwrap(); |
| 409 | let paths = install(directory.path()); |
| 410 | let files = FailingRename { |
| 411 | fail_on: paths.update_exe.clone(), |
| 412 | }; |
| 413 | let error = apply_plan(&files, &swap_plan(&paths)).unwrap_err(); |
| 414 | assert!(error.contains("locked")); |
| 415 | assert_eq!(fs::read_to_string(&paths.exe).unwrap(), "old"); |
| 416 | assert!(!paths.old_exe.exists()); |
| 417 | assert_eq!(fs::read_to_string(&paths.update_exe).unwrap(), "new"); |
| 418 | assert!(paths.version_file.exists()); |
| 419 | } |
| 420 | |
| 421 | #[test] |
| 422 | fn relaunch_value_carries_the_previous_process_id() { |
| 423 | assert_eq!(previous_process_id("4242"), Some(4242)); |
| 424 | assert_eq!(previous_process_id(""), None); |
| 425 | } |
| 426 | |
| 427 | #[test] |
| 428 | fn running_version_is_set() { |
| 429 | assert!(!running_version().is_empty()); |
| 430 | } |
| 431 | } |