From c610b4350d3e8d46a4ece89deaea6f4e7cba1670 Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 06:15:36 +0100 Subject: [PATCH] Updates & WSL: refuse non-version strings and odd staged versions, drain wsl.exe pipes, keep one [boot] command (#973) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ersin KOÇ --- crates/kiri-win/src/update.rs | 85 +++++++++++++++++++++++++++++++--- crates/kiri-win/src/wslsync.rs | 28 ++++++++++- crates/kiri/src/update.rs | 30 +++++++++++- 3 files changed, 134 insertions(+), 9 deletions(-) diff --git a/crates/kiri-win/src/update.rs b/crates/kiri-win/src/update.rs index d1fb638..c188c07 100644 --- a/crates/kiri-win/src/update.rs +++ b/crates/kiri-win/src/update.rs @@ -66,8 +66,27 @@ pub struct Release { pub size: u64, } -/// `1.2.10` > `1.2.9`; a missing part counts as 0. +/// Whether `v` reads as a version: `[v]N(.N)*`, optionally `-` and +/// dot-separated alphanumeric identifiers (`0.1.8-dev.42`). +fn is_version(v: &str) -> bool { + let s = v.strip_prefix('v').unwrap_or(v); + let (core, pre) = match s.split_once('-') { + Some((c, p)) => (c, Some(p)), + None => (s, None), + }; + let numeric = |seg: &str| !seg.is_empty() && seg.bytes().all(|b| b.is_ascii_digit()); + let ident = |id: &str| !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'); + core.split('.').all(numeric) && pre.is_none_or(|p| p.split('.').all(ident)) +} + +/// `1.2.10` > `1.2.9`; a missing part counts as 0, and a test build +/// (`0.1.8-dev.42`, scripts/ci/test-version.sh) sorts above its release. +/// A string that isn't a version is never newer, and nothing is newer +/// than one. pub fn newer(candidate: &str, current: &str) -> bool { + if !is_version(candidate) || !is_version(current) { + return false; + } let parts = |v: &str| -> Vec { v.trim_start_matches('v').split(['.', '-']).map(|p| p.parse().unwrap_or(0)).collect() }; let (a, b) = (parts(candidate), parts(current)); for i in 0..a.len().max(b.len()) { @@ -169,6 +188,7 @@ fn fetch_and_check(release: &Release, dir: &Path, progress: &mut dyn FnMut(u64, loop { if cancel.load(Ordering::Relaxed) { let _ = child.kill(); + let _ = child.wait(); return Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled")); } let got = std::fs::metadata(&part).map_or(0, |m| m.len()); @@ -207,10 +227,15 @@ fn staged_msi(version: &str) -> PathBuf { stage_dir().join(format!("Kiri-{version}.msi")) } +fn staged_in(dir: &Path) -> Option { + let raw = std::fs::read_to_string(dir.join("version")).ok()?; + let version = raw.trim().strip_prefix('v').unwrap_or(raw.trim()).to_owned(); + (is_version(&version) && dir.join(format!("Kiri-{version}.msi")).is_file() && newer(&version, CURRENT)).then_some(version) +} + /// The staged update's version, when there is one newer than this build. pub fn staged() -> Option { - let version = std::fs::read_to_string(stage_dir().join("version")).ok()?.trim().to_owned(); - (staged_msi(&version).is_file() && newer(&version, CURRENT)).then_some(version) + staged_in(&stage_dir()) } /// The staged MSI, checked again (it sat on disk since the download). @@ -623,6 +648,17 @@ pub(crate) fn output_within(cmd: &mut Command, limit: Duration) -> io::Result>| { + std::thread::spawn(move || { + let mut buf = Vec::new(); + if let Some(mut r) = pipe { + let _ = r.read_to_end(&mut buf); + } + buf + }) + }; + let out_reader = drain(child.stdout.take().map(|s| Box::new(s) as Box)); + let err_reader = drain(child.stderr.take().map(|s| Box::new(s) as Box)); let ms = u32::try_from(limit.as_millis()).unwrap_or(u32::MAX - 1); // SAFETY: waits on the child's own process handle, open while `child` lives. let waited = unsafe { windows_sys::Win32::System::Threading::WaitForSingleObject(child.as_raw_handle() as _, ms) }; @@ -632,10 +668,15 @@ pub(crate) fn output_within(cmd: &mut Command, limit: Duration) -> io::Result &'static str { /// spaces, a `#` comment, or the `\r` of a file saved with CRLF /// ([[:space:]] has it). On one line, with no backslash, as the rest of /// the script. -const BOOT_AWK: &str = "function key(l) { sub(/#.*/, \"\", l); gsub(/[[:space:]]/, \"\", l); return l } \ +const BOOT_AWK: &str = "function key(l) { if (NR == 1) sub(/^\u{feff}/, \"\", l); sub(/[#;].*/, \"\", l); gsub(/[[:space:]]/, \"\", l); return tolower(l) } \ function flush() { if (boot && !done) { print want; done = 1 } } \ + NR == 1 { sub(/^\u{feff}/, \"\") } \ substr(key($0), 1, 1) == \"[\" { flush(); boot = key($0) == \"[boot]\"; print; next } \ boot && index(key($0), \"command=\") == 1 { if (!done) { print want; done = 1 } next } \ { print } \ @@ -134,7 +135,8 @@ pub fn valid_distro_name(name: &str) -> bool { !name.is_empty() && name != "." && name != ".." - && !name.contains(['/', '\\', '\0']) + && !name.starts_with('-') + && !name.contains(['/', '\\', '\0', ':', '*', '?', '"', '<', '>', '|']) && !name.bytes().any(|b| b.is_ascii_control()) } @@ -505,6 +507,16 @@ mod tests { assert_eq!(run(Some("[boot] # Kiri's\ncommand=/old # mine\n")), format!("[boot] # Kiri's\n{want}\n")); // A commented-out command is left, and one added. assert_eq!(run(Some("[boot]\n# command = /off\n")), format!("[boot]\n# command = /off\n{want}\n")); + // Case-insensitive [Boot]/Command, UTF-8 BOM, and ';' comments. + assert_eq!(run(Some("[Boot]\nCommand = /old\nsystemd = false\n")), format!("[Boot]\n{want}\nsystemd = false\n")); + assert_eq!( + run(Some("\u{feff}[BOOT]\nCOMMAND = /old\n[automount]\noptions = metadata;umask=22\n")), + format!("[BOOT]\n{want}\n[automount]\noptions = metadata;umask=22\n") + ); + assert_eq!( + run(Some("; [boot]\n[boot] ; header\n; command = /off\ncommand = /old ; inline\n")), + format!("; [boot]\n[boot] ; header\n; command = /off\n{want}\n") + ); assert_eq!(run(None), format!("[boot]\n{want}\n")); let _ = std::fs::remove_dir_all(root.parent().unwrap()); } @@ -753,4 +765,16 @@ mod ro_tests { assert!(msg.contains(r#"wsl --mount "D:\KiriData\ext4.vhdx" --vhd --bare"#), "{msg}"); assert!(msg.contains("wsl --shutdown") && msg.contains("e2fsck -f -y -D") && msg.contains("Settings -> Storage"), "{msg}"); } + + #[test] + fn validates_distro_names_and_sync_script_has_no_backslash() { + for bad in ["", ".", "..", "-e", "--shutdown", "a/b", r"a\b", "bad:distro", "bad*distro", "bad?distro", "bad\"distro", "bad|distro"] { + assert!(!valid_distro_name(bad), "expected false for {bad:?}"); + } + for good in ["Ubuntu", "Ubuntu-24.04", "NixOS", "Arch_Linux", "my.distro"] { + assert!(valid_distro_name(good), "expected true for {good:?}"); + } + assert_eq!(parse_enabled_distros(br#"{"distros":["Ubuntu","--shutdown","bad:name","NixOS"]}"#), vec!["Ubuntu".to_owned(), "NixOS".to_owned()]); + assert!(!sync_script(Path::new("C:/Users/x/AppData/Local/Kiri"), "", true).contains('\\')); + } } diff --git a/crates/kiri/src/update.rs b/crates/kiri/src/update.rs index 366d1fb..3d3a679 100644 --- a/crates/kiri/src/update.rs +++ b/crates/kiri/src/update.rs @@ -55,8 +55,27 @@ pub struct Release { pub notes_url: String, } -/// `1.2.10` > `1.2.9`; a missing part counts as 0. +/// Whether `v` reads as a version: `[v]N(.N)*`, optionally `-` and +/// dot-separated alphanumeric identifiers (`0.1.8-dev.42`). +fn is_version(v: &str) -> bool { + let s = v.strip_prefix('v').unwrap_or(v); + let (core, pre) = match s.split_once('-') { + Some((c, p)) => (c, Some(p)), + None => (s, None), + }; + let numeric = |seg: &str| !seg.is_empty() && seg.bytes().all(|b| b.is_ascii_digit()); + let ident = |id: &str| !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'); + core.split('.').all(numeric) && pre.is_none_or(|p| p.split('.').all(ident)) +} + +/// `1.2.10` > `1.2.9`; a missing part counts as 0, and a test build +/// (`0.1.8-dev.42`, scripts/ci/test-version.sh) sorts above its release. +/// A string that isn't a version is never newer, and nothing is newer +/// than one. pub fn newer(candidate: &str, current: &str) -> bool { + if !is_version(candidate) || !is_version(current) { + return false; + } let parts = |v: &str| -> Vec { v.trim_start_matches('v').split(['.', '-']).map(|p| p.parse().unwrap_or(0)).collect() }; let (a, b) = (parts(candidate), parts(current)); for i in 0..a.len().max(b.len()) { @@ -563,8 +582,17 @@ mod tests { assert!(newer("0.2.0", "0.1.9")); assert!(newer("1.2.10", "1.2.9")); assert!(newer("v1.0.1", "1.0")); + assert!(!newer("1.0.0", "1.0")); assert!(!newer("0.1.0", "0.1.0")); assert!(!newer("0.1.0", "0.2.0")); + // A test build (scripts/ci/test-version.sh) sorts above its release. + assert!(newer("0.1.8-dev.42", "0.1.8")); + assert!(!newer("0.1.8", "0.1.8-dev.42")); + assert!(newer("0.1.8-dev.43", "0.1.8-dev.42")); + for bad in ["", "vv1.0.0", "1.+2.0", "1.2.", "1.2.0-", "1.2.0-rc..1", "99.0.0/../../evil", "99.0.0\\evil"] { + assert!(!newer(bad, "0.2.0"), "accepted invalid candidate {bad:?}"); + assert!(!newer("99.0.0", bad), "accepted invalid current {bad:?}"); + } } #[test]