From 2eeff54b2bee5a1585ec3d152be7dec7c91d6928 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Tue, 13 Oct 2026 08:24:13 +1100 Subject: [PATCH 1/4] #366: SAM 3 mirrors accept a local folder (file:// or absolute path); vocab.json / merges.txt pinned A mirror entry may now be a local folder holding the checkpoint files, so people who fetched facebook/sam3 by hand can install it without a web server. Local copies go through the same size + SHA-256 checks; the two tokenizer files are now pinned to the official checkpoint. Sources: own design. (cherry picked from commit c47066a97aba89942c1fdba5e2028d643168f51a) Co-Authored-By: Claude Opus 5.5 --- crates/fetch/src/lib.rs | 69 ++++++++++++++++++++++++++++++--- crates/fetch/src/tests.rs | 35 +++++++++++++++++ crates/segment/src/fetch/mod.rs | 21 ++++++---- 3 files changed, 112 insertions(+), 13 deletions(-) diff --git a/crates/fetch/src/lib.rs b/crates/fetch/src/lib.rs index 12daff541f..5d44933136 100644 --- a/crates/fetch/src/lib.rs +++ b/crates/fetch/src/lib.rs @@ -50,12 +50,17 @@ const MAX_REDIRECTS: usize = 8; /// The mirrors to try, in order: `env`'s (base URLs separated by commas, spaces or newlines), then /// the mirrors file's (one base URL per line, `#` comments), then `defaults`; duplicates and -/// unusable URLs dropped, at most 16. +/// unusable URLs dropped, at most 16. A mirror can be `http(s)://`, `file://` or an +/// absolute folder path: files from a local folder are copied (then checked like a download). pub fn mirrors(env: Option<&str>, file: Option<&Path>, defaults: &[&str]) -> Vec { let mut out: Vec = Vec::new(); let mut add = |s: &str| { - let s = s.trim().trim_end_matches('/'); - if !s.is_empty() && Url::parse(s).is_ok() && !out.iter().any(|m| m == s) && out.len() < MAX_MIRRORS { + let s = s.trim(); + // a local folder (an absolute path) is the same as its `file://` URL + let s = if Path::new(s).is_absolute() { format!("file://{s}") } else { s.to_string() }; + let s = s.trim_end_matches('/'); + let usable = local_path(s).is_some() || Url::parse(s).is_ok(); + if !s.is_empty() && usable && !out.iter().any(|m| m == s) && out.len() < MAX_MIRRORS { out.push(s.to_string()); } }; @@ -202,7 +207,7 @@ fn download_source( return Err(DownloadError::Cancelled); } let mut report = |n: u64, announced: u64| { - let mirror = Url::parse(m).map(|u| u.display()).unwrap_or_default(); + let mirror = short(m); progress(&Progress { file: f.name.to_string(), done: before.saturating_add(n), @@ -282,6 +287,9 @@ fn bearer<'a>(token: Option<&'a str>, url: &Url, origin: &str) -> Option<&'a str /// A mirror for messages (no query string: it may hold a token). fn short(m: &str) -> String { + if local_path(m).is_some() { + return m.to_string(); + } Url::parse(m).map(|u| u.display()).unwrap_or_else(|_| "mirror".into()) } @@ -343,8 +351,11 @@ fn fetch_file(f: &FileSpec<'_>, url: &str, dir: &Path, opts: &Options, cancel: & } Err(_) => 0, }; - let fetched = f.size != Some(have) || have == 0; - if fetched { + let local = local_path(url); + let fetched = local.is_some() || f.size != Some(have) || have == 0; + if let Some(src) = local { + copy_local(&src, &part, limit, f.size, cancel, report)?; + } else if fetched { let limits = Limits { connect: opts.connect_timeout, stall: opts.stall_timeout, cancel }; let mut url = Url::parse(url).map_err(|e| Fail::NextMirror(e.to_string()))?; let origin = url.host.clone(); @@ -453,6 +464,52 @@ fn fetch_file(f: &FileSpec<'_>, url: &str, dir: &Path, opts: &Options, cancel: & Ok(()) } +/// The local path of a `file://` URL (absolute only; `file:///C:/x` → `C:/x` on Windows). +fn local_path(url: &str) -> Option { + let rest = url.strip_prefix("file://")?; + let rest = if rest.get(2..3) == Some(":") { rest.strip_prefix('/').unwrap_or(rest) } else { rest }; + let p = PathBuf::from(rest); + if p.is_absolute() && !rest.chars().any(char::is_control) { Some(p) } else { None } +} + +/// Copy a file from a local mirror into `part` (from the start; it is checked afterwards like a download). +fn copy_local(src: &Path, part: &Path, limit: u64, size: Option, cancel: &AtomicBool, report: &mut dyn FnMut(u64, u64)) -> Result<(), Fail> { + let disk = |e: std::io::Error| Fail::Disk(format!("{}: {e}", part.display())); + let meta = std::fs::metadata(src).map_err(|e| Fail::NextMirror(format!("{}: {e}", src.display())))?; + if !meta.is_file() { + return Err(Fail::NextMirror(format!("{} is not a file", src.display()))); + } + if meta.len() > limit || size.is_some_and(|s| s != meta.len()) { + return Err(Fail::NextMirror(format!("{} has the wrong size ({} bytes)", src.display(), meta.len()))); + } + let mut input = File::open(src).map_err(|e| Fail::NextMirror(format!("{}: {e}", src.display())))?; + let mut out = File::create(part).map_err(disk)?; + let announced = size.unwrap_or(meta.len()); + let mut have = 0u64; + report(0, announced); + let mut buf = vec![0u8; 1 << 20]; + loop { + if cancel.load(Ordering::Relaxed) { + drop(out); + let _ = std::fs::remove_file(part); + return Err(Fail::Cancelled); + } + let n = input.read(&mut buf).map_err(|e| Fail::NextMirror(format!("{}: {e}", src.display())))?; + if n == 0 { + break; + } + if have.saturating_add(n as u64) > limit { + drop(out); + let _ = std::fs::remove_file(part); + return Err(Fail::NextMirror(format!("{} grew past the expected {limit} bytes", src.display()))); + } + out.write_all(buf.get(..n).unwrap_or_default()).map_err(disk)?; + have = have.saturating_add(n as u64); + report(have, announced); + } + out.sync_all().map_err(disk) +} + fn http_fail(e: HttpError) -> Fail { match e { HttpError::Cancelled => Fail::Cancelled, diff --git a/crates/fetch/src/tests.rs b/crates/fetch/src/tests.rs index 08f869dcca..667e481a8a 100644 --- a/crates/fetch/src/tests.rs +++ b/crates/fetch/src/tests.rs @@ -408,3 +408,38 @@ fn hostile_file_specs_are_rejected_before_touching_disk() { assert!(!dir.exists()); } } + +#[test] +fn copies_from_a_local_folder_mirror_and_checks_the_hash() { + let src = tmp("local-src"); + let dst = tmp("local-dst"); + std::fs::create_dir_all(&src).unwrap(); + std::fs::write(src.join("model.bin"), payload()).unwrap(); + // a bare absolute path and a file:// URL are both mirrors + let m = mirrors(Some(src.to_str().unwrap()), None, &[]); + assert_eq!(m, vec![format!("file://{}", src.display())]); + let (r, prog) = run(&[pinned()], &m, &dst, &AtomicBool::new(false)); + r.unwrap(); + assert_eq!(std::fs::read(dst.join("model.bin")).unwrap(), payload()); + assert!(prog.last().is_some_and(|p| p.done == p.total)); + + // a damaged local copy is rejected and never moved into place + let bad = tmp("local-bad"); + std::fs::create_dir_all(&bad).unwrap(); + let mut damaged = payload(); + damaged[7] ^= 1; + std::fs::write(bad.join("model.bin"), damaged).unwrap(); + let dst2 = tmp("local-dst2"); + let (r, _) = run(&[pinned()], &[format!("file://{}", bad.display())], &dst2, &AtomicBool::new(false)); + assert!(matches!(r, Err(DownloadError::AllMirrorsFailed { .. })), "{r:?}"); + assert!(!dst2.join("model.bin").exists() && !dst2.join("model.bin.part").exists()); + + // a missing folder, a relative path and a directory in place of a file are errors, not panics + let (r, _) = run(&[pinned()], &["file:///nonexistent/model-mirror".to_string()], &dst2, &AtomicBool::new(false)); + assert!(r.is_err()); + assert!(mirrors(Some("file://relative/dir"), None, &[]).is_empty()); + std::fs::create_dir_all(src.join("dir.bin")).unwrap(); + let dir_spec = FileSpec { name: "dir.bin", size: None, sha256: None, max: 10 }; + let (r, _) = run(&[dir_spec], &[format!("file://{}", src.display())], &dst2, &AtomicBool::new(false)); + assert!(r.is_err()); +} diff --git a/crates/segment/src/fetch/mod.rs b/crates/segment/src/fetch/mod.rs index 35f2d2eb54..3d31a7a43b 100644 --- a/crates/segment/src/fetch/mod.rs +++ b/crates/segment/src/fetch/mod.rs @@ -11,14 +11,21 @@ use std::path::Path; /// The `facebook/sam3` checkpoint files [`crate::Sam3::load`] needs. /// -/// `model.safetensors` is pinned to the official checkpoint (Hugging Face LFS SHA-256). The two -/// tokenizer files are small text files without a pinned hash yet: they are only parsed by the -/// tokenizer (never executed) and capped in size. -// TODO(maintainer): pin `vocab.json` and `merges.txt` (size + SHA-256) when the files are -// uploaded to LightCraft's CDN. +/// All three are pinned (exact size + SHA-256) to the official `facebook/sam3` checkpoint files, +/// checked against a copy of them on 2026-10-13. pub const SAM3_FILES: &[FileSpec] = &[ - FileSpec { name: "vocab.json", size: None, sha256: None, max: 16 << 20 }, - FileSpec { name: "merges.txt", size: None, sha256: None, max: 16 << 20 }, + FileSpec { + name: "vocab.json", + size: Some(862_328), + sha256: Some("5047b556ce86ccaf6aa22b3ffccfc52d391ea4accdab9c2f2407da5b742d4363"), + max: 16 << 20, + }, + FileSpec { + name: "merges.txt", + size: Some(524_619), + sha256: Some("9fd691f7c8039210e0fced15865466c65820d09b63988b0174bfe25de299051a"), + max: 16 << 20, + }, FileSpec { name: crate::WEIGHTS_FILE, size: Some(SAM3_WEIGHTS_SIZE), From 190da91b2b9a24cf43c9289ce34d46178f32bdb1 Mon Sep 17 00:00:00 2001 From: Andrew Frahn Date: Mon, 26 Oct 2026 11:55:26 +1100 Subject: [PATCH 2/4] #366: file:// mirrors are percent-decoded, bare paths keep literal %; a failed local read leaves no partial file Review follow-up: a bare folder path is normalised to a file:// URL with '%' escaped, and file:// paths decode %XX (a broken escape, non-UTF-8 or control character is refused). A read error from a local mirror removes the partial file so the next mirror does not resume from it. Sources: own design. Co-Authored-By: Claude Opus 5.5 --- crates/fetch/src/lib.rs | 32 +++++++++++++++++++++++++++++--- crates/fetch/src/tests.rs | 11 +++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/fetch/src/lib.rs b/crates/fetch/src/lib.rs index 5d44933136..8a02dadf4c 100644 --- a/crates/fetch/src/lib.rs +++ b/crates/fetch/src/lib.rs @@ -57,7 +57,7 @@ pub fn mirrors(env: Option<&str>, file: Option<&Path>, defaults: &[&str]) -> Vec let mut add = |s: &str| { let s = s.trim(); // a local folder (an absolute path) is the same as its `file://` URL - let s = if Path::new(s).is_absolute() { format!("file://{s}") } else { s.to_string() }; + let s = if Path::new(s).is_absolute() { format!("file://{}", s.replace('%', "%25")) } else { s.to_string() }; let s = s.trim_end_matches('/'); let usable = local_path(s).is_some() || Url::parse(s).is_ok(); if !s.is_empty() && usable && !out.iter().any(|m| m == s) && out.len() < MAX_MIRRORS { @@ -468,10 +468,29 @@ fn fetch_file(f: &FileSpec<'_>, url: &str, dir: &Path, opts: &Options, cancel: & fn local_path(url: &str) -> Option { let rest = url.strip_prefix("file://")?; let rest = if rest.get(2..3) == Some(":") { rest.strip_prefix('/').unwrap_or(rest) } else { rest }; - let p = PathBuf::from(rest); + let rest = percent_decode(rest)?; + let p = PathBuf::from(&rest); if p.is_absolute() && !rest.chars().any(char::is_control) { Some(p) } else { None } } +/// Decode `%XX` escapes (a `file://` URL's path); `None` for a broken escape or non-UTF-8 result. +fn percent_decode(s: &str) -> Option { + let b = s.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while let Some(&c) = b.get(i) { + if c == b'%' { + let hex = std::str::from_utf8(b.get(i + 1..i + 3)?).ok()?; + out.push(u8::from_str_radix(hex, 16).ok()?); + i += 3; + } else { + out.push(c); + i += 1; + } + } + String::from_utf8(out).ok() +} + /// Copy a file from a local mirror into `part` (from the start; it is checked afterwards like a download). fn copy_local(src: &Path, part: &Path, limit: u64, size: Option, cancel: &AtomicBool, report: &mut dyn FnMut(u64, u64)) -> Result<(), Fail> { let disk = |e: std::io::Error| Fail::Disk(format!("{}: {e}", part.display())); @@ -494,7 +513,14 @@ fn copy_local(src: &Path, part: &Path, limit: u64, size: Option, cancel: &A let _ = std::fs::remove_file(part); return Err(Fail::Cancelled); } - let n = input.read(&mut buf).map_err(|e| Fail::NextMirror(format!("{}: {e}", src.display())))?; + let n = match input.read(&mut buf) { + Ok(n) => n, + Err(e) => { + drop(out); + let _ = std::fs::remove_file(part); + return Err(Fail::NextMirror(format!("{}: {e}", src.display()))); + } + }; if n == 0 { break; } diff --git a/crates/fetch/src/tests.rs b/crates/fetch/src/tests.rs index 667e481a8a..bc1642f3ac 100644 --- a/crates/fetch/src/tests.rs +++ b/crates/fetch/src/tests.rs @@ -443,3 +443,14 @@ fn copies_from_a_local_folder_mirror_and_checks_the_hash() { let (r, _) = run(&[dir_spec], &[format!("file://{}", src.display())], &dst2, &AtomicBool::new(false)); assert!(r.is_err()); } + +#[test] +fn file_urls_are_percent_decoded_but_bare_paths_keep_their_percent_signs() { + let bare = mirrors(Some("/models/50%20off"), None, &[]); + assert_eq!(bare.len(), 1); + assert_eq!(local_path(&bare[0]), Some(std::path::PathBuf::from("/models/50%20off"))); + assert_eq!(local_path("file:///models/my%20sam3"), Some(std::path::PathBuf::from("/models/my sam3"))); + for hostile in ["file:///x%", "file:///x%2", "file:///x%zz", "file:///x%ff", "file:///x%0a"] { + assert_eq!(local_path(hostile), None, "{hostile}"); + } +} From b182d2242c3cd3e6eedfeecb68c9c3bb99944b6f Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:36:06 +0700 Subject: [PATCH 3/4] fetch: keep a root mirror's separator, escape a local file name's %, never truncate through a hard-linked .part (CodeRabbit on #3010) --- crates/fetch/src/lib.rs | 25 +++++++++++++-- crates/fetch/src/tests.rs | 65 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 83 insertions(+), 7 deletions(-) diff --git a/crates/fetch/src/lib.rs b/crates/fetch/src/lib.rs index 5c48ff243d..6a50d81d17 100644 --- a/crates/fetch/src/lib.rs +++ b/crates/fetch/src/lib.rs @@ -59,7 +59,8 @@ pub fn mirrors(env: Option<&str>, file: Option<&Path>, defaults: &[&str]) -> Vec let s = s.trim(); // a local folder (an absolute path) is the same as its `file://` URL let s = if Path::new(s).is_absolute() { format!("file://{}", s.replace('%', "%25")) } else { s.to_string() }; - let s = s.trim_end_matches('/'); + let s = keep_root(s.trim_end_matches('/')); + let s = s.as_str(); let usable = local_path(s).is_some() || Url::parse(s).is_ok(); if !s.is_empty() && usable && !out.iter().any(|m| m == s) && out.len() < MAX_MIRRORS { out.push(s.to_string()); @@ -202,7 +203,7 @@ fn download_source( let mut errors = Vec::new(); let mut ok = false; 'mirrors: for m in mirrors { - let url = if exact_urls { m.clone() } else { format!("{m}/{}", f.name) }; + let url = if exact_urls { m.clone() } else { file_url_in(m, f.name) }; for _ in 0..opts.attempts.clamp(1, 16) { if cancel.load(Ordering::Relaxed) { return Err(DownloadError::Cancelled); @@ -467,6 +468,23 @@ fn fetch_file(f: &FileSpec<'_>, url: &str, dir: &Path, opts: &Options, cancel: & } /// The local path of a `file://` URL (absolute only; `file:///C:/x` → `C:/x` on Windows). +/// A mirror with its trailing separators taken off, except a filesystem root's: `file:///` and `file:///D:/` stay +/// as they are (without it neither is an absolute path). +fn keep_root(s: &str) -> String { + match s { + "file:" => "file:///".to_string(), + s if s.starts_with("file://") && s.ends_with(':') => format!("{s}/"), + s => s.to_string(), + } +} + +/// The URL of file `name` on mirror `m`: one separator between them (a root mirror already ends with one), and on a +/// local mirror the name's own `%` escaped, so the decoded path is that very name. +fn file_url_in(m: &str, name: &str) -> String { + let name = if local_path(m).is_some() { name.replace('%', "%25") } else { name.to_string() }; + if m.ends_with('/') { format!("{m}{name}") } else { format!("{m}/{name}") } +} + fn local_path(url: &str) -> Option { let rest = url.strip_prefix("file://")?; let rest = if rest.get(2..3) == Some(":") { rest.strip_prefix('/').unwrap_or(rest) } else { rest }; @@ -504,7 +522,8 @@ fn copy_local(src: &Path, part: &Path, limit: u64, size: Option, cancel: &A return Err(Fail::NextMirror(format!("{} has the wrong size ({} bytes)", src.display(), meta.len()))); } let mut input = File::open(src).map_err(|e| Fail::NextMirror(format!("{}: {e}", src.display())))?; - let mut out = File::create(part).map_err(disk)?; + // (a fresh file: an old one at that name may be a hard link to the source, which truncating would empty) + let mut out = new_part(part).map_err(disk)?; let announced = size.unwrap_or(meta.len()); let mut have = 0u64; report(0, announced); diff --git a/crates/fetch/src/tests.rs b/crates/fetch/src/tests.rs index b22af51929..4a965db49f 100644 --- a/crates/fetch/src/tests.rs +++ b/crates/fetch/src/tests.rs @@ -435,7 +435,7 @@ fn copies_from_a_local_folder_mirror_and_checks_the_hash() { // a bare absolute path and a file:// URL are both mirrors (passed as a default, which is not split on spaces // or commas the way the environment's list is: the temp folder may hold either) let m = mirrors(None, None, &[src.to_str().unwrap()]); - assert_eq!(m, vec![format!("file://{}", src.display())]); + assert_eq!(m, vec![file_url(&src)]); let (r, prog) = run(&[pinned()], &m, &dst, &AtomicBool::new(false)); r.unwrap(); assert_eq!(std::fs::read(dst.join("model.bin")).unwrap(), payload()); @@ -448,7 +448,7 @@ fn copies_from_a_local_folder_mirror_and_checks_the_hash() { damaged[7] ^= 1; std::fs::write(bad.join("model.bin"), damaged).unwrap(); let dst2 = tmp("local-dst2"); - let (r, _) = run(&[pinned()], &[format!("file://{}", bad.display())], &dst2, &AtomicBool::new(false)); + let (r, _) = run(&[pinned()], &[file_url(&bad)], &dst2, &AtomicBool::new(false)); assert!(matches!(r, Err(DownloadError::AllMirrorsFailed { .. })), "{r:?}"); assert!(!dst2.join("model.bin").exists() && !dst2.join("model.bin.part").exists()); @@ -458,13 +458,70 @@ fn copies_from_a_local_folder_mirror_and_checks_the_hash() { assert!(mirrors(Some("file://relative/dir"), None, &[]).is_empty()); std::fs::create_dir_all(src.join("dir.bin")).unwrap(); let dir_spec = FileSpec { name: "dir.bin", size: None, sha256: None, max: 10 }; - let (r, _) = run(&[dir_spec], &[format!("file://{}", src.display())], &dst2, &AtomicBool::new(false)); + let (r, _) = run(&[dir_spec], &[file_url(&src)], &dst2, &AtomicBool::new(false)); assert!(r.is_err()); for d in [&src, &dst, &bad, &dst2] { let _ = std::fs::remove_dir_all(d); } } +/// The `file://` URL of a local folder (its own `%` escaped, as [`mirrors`] does: the temp folder may hold one). +fn file_url(p: &Path) -> String { + format!("file://{}", p.display().to_string().replace('%', "%25")) +} + +/// A filesystem root is a usable mirror, and a file in it is found under one separator (CodeRabbit on #3010). +#[test] +fn a_root_folder_mirror_keeps_its_separator() { + assert_eq!(keep_root("file:"), "file:///"); + assert_eq!(keep_root("file:///D:"), "file:///D:/"); + assert_eq!(keep_root("file:///models"), "file:///models"); + assert_eq!(file_url_in("file:///", "model.bin"), "file:///model.bin"); + #[cfg(unix)] + { + assert_eq!(mirrors(None, None, &["/"]), ["file:///"]); + assert_eq!(local_path("file:///model.bin"), Some(PathBuf::from("/model.bin"))); + } +} + +/// A file name with a literal `%20` in it is copied from a local mirror under that very name, not as a space +/// (CodeRabbit on #3010). +#[test] +fn a_local_mirror_keeps_a_file_names_percent_signs() { + let src = tmp("local-percent-src"); + let dst = tmp("local-percent-dst"); + std::fs::create_dir_all(&src).unwrap(); + std::fs::write(src.join("model%20.bin"), payload()).unwrap(); + let p = payload(); + let spec = FileSpec { name: "model%20.bin", size: Some(p.len() as u64), sha256: Some(leak(sha_hex(&p))), max: p.len() as u64 }; + let (r, _) = run(&[spec], &[file_url(&src)], &dst, &AtomicBool::new(false)); + r.unwrap(); + assert_eq!(std::fs::read(dst.join("model%20.bin")).unwrap(), payload()); + for d in [&src, &dst] { + let _ = std::fs::remove_dir_all(d); + } +} + +/// A leftover `.part` that is a hard link to the local mirror's file is replaced, never truncated through: the +/// mirror's file keeps its bytes (CodeRabbit on #3010). +#[cfg(unix)] +#[test] +fn a_hard_linked_part_never_empties_the_local_source() { + let src = tmp("local-link-src"); + let dst = tmp("local-link-dst"); + std::fs::create_dir_all(&src).unwrap(); + std::fs::create_dir_all(&dst).unwrap(); + std::fs::write(src.join("model.bin"), payload()).unwrap(); + std::fs::hard_link(src.join("model.bin"), dst.join("model.bin.part")).unwrap(); + let (r, _) = run(&[pinned()], &[file_url(&src)], &dst, &AtomicBool::new(false)); + r.unwrap(); + assert_eq!(std::fs::read(src.join("model.bin")).unwrap(), payload(), "the mirror's file is untouched"); + assert_eq!(std::fs::read(dst.join("model.bin")).unwrap(), payload()); + for d in [&src, &dst] { + let _ = std::fs::remove_dir_all(d); + } +} + #[test] fn file_urls_are_percent_decoded_but_bare_paths_keep_their_percent_signs() { // (absolute on every platform: `/models/…` has no drive on Windows, where it is not an absolute path) @@ -473,7 +530,7 @@ fn file_urls_are_percent_decoded_but_bare_paths_keep_their_percent_signs() { assert_eq!(bare.len(), 1); assert_eq!(local_path(&bare[0]), Some(percent)); let spaced = std::env::temp_dir().join("my sam3"); - assert_eq!(local_path(&format!("file://{}", spaced.to_str().unwrap().replace(' ', "%20"))), Some(spaced)); + assert_eq!(local_path(&format!("file://{}", spaced.to_str().unwrap().replace('%', "%25").replace(' ', "%20"))), Some(spaced)); for hostile in ["file:///x%", "file:///x%2", "file:///x%zz", "file:///x%ff", "file:///x%0a"] { assert_eq!(local_path(hostile), None, "{hostile}"); } From 09dcf87fa4ab5ec2d38aa5886dd525594606352b Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:06:57 +0700 Subject: [PATCH 4/4] fetch: a local copy that comes out another length is removed, the next mirror starts over (CodeRabbit on #3010) --- crates/fetch/src/lib.rs | 7 +++++++ crates/fetch/src/tests.rs | 15 +++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/crates/fetch/src/lib.rs b/crates/fetch/src/lib.rs index 6a50d81d17..1a4922e7fc 100644 --- a/crates/fetch/src/lib.rs +++ b/crates/fetch/src/lib.rs @@ -554,6 +554,13 @@ fn copy_local(src: &Path, part: &Path, limit: u64, size: Option, cancel: &A have = have.saturating_add(n as u64); report(have, announced); } + // a source rewritten (or cut short) after its size was read: what was copied is not that file, and a partial + // left behind would be resumed by the next mirror, failing its hash; so it goes, and the next mirror starts over + if have != announced { + drop(out); + let _ = std::fs::remove_file(part); + return Err(Fail::NextMirror(format!("{} changed while it was copied ({have} of {announced} bytes)", src.display()))); + } out.sync_all().map_err(disk) } diff --git a/crates/fetch/src/tests.rs b/crates/fetch/src/tests.rs index 4a965db49f..8803a4c207 100644 --- a/crates/fetch/src/tests.rs +++ b/crates/fetch/src/tests.rs @@ -522,6 +522,21 @@ fn a_hard_linked_part_never_empties_the_local_source() { } } +/// A local source whose length on reading differs from the one its metadata gave (here a /proc file, whose size +/// reads as 0: as a file rewritten after its size was checked) is not kept as a partial for the next mirror to +/// resume (CodeRabbit on #3010). +#[cfg(target_os = "linux")] +#[test] +fn a_local_copy_that_comes_out_another_length_leaves_no_partial() { + let dst = tmp("local-changed-dst"); + std::fs::create_dir_all(&dst).unwrap(); + let part = dst.join("status.part"); + let r = copy_local(Path::new("/proc/self/status"), &part, 1 << 20, None, &AtomicBool::new(false), &mut |_, _| {}); + assert!(matches!(r, Err(Fail::NextMirror(_))), "the next mirror is tried"); + assert!(!part.exists(), "the partial is removed"); + let _ = std::fs::remove_dir_all(&dst); +} + #[test] fn file_urls_are_percent_decoded_but_bare_paths_keep_their_percent_signs() { // (absolute on every platform: `/models/…` has no drive on Windows, where it is not an absolute path)