From f90fcb487d8316e81a6be1656ab965f87735573e Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Wed, 4 Nov 2026 20:13:34 -0600 Subject: [PATCH] fix: sd0 truncation, PK write errors, and manifest writing - fix sd0 chunks being truncated on incompressible data - skip missing files in the PKI generator - report write errors when writing PK files; a BufWriter drops them - add Manifest::write and Manifest::add_file, writing files in the order of the original manifests, with LF or CRLF line endings - fix the lux-manifest example, which didn't compile with the compression option Co-Authored-By: Claude Opus 5.5 --- modules/pack/examples/lux-manifest.rs | 1 + modules/pack/src/pk/fs.rs | 4 + modules/pack/src/pki/gen.rs | 15 ++- modules/pack/src/sd0/fs.rs | 19 +++- modules/pack/src/txt/manifest/mod.rs | 135 +++++++++++++++++++++++++- 5 files changed, 171 insertions(+), 3 deletions(-) diff --git a/modules/pack/examples/lux-manifest.rs b/modules/pack/examples/lux-manifest.rs index 91d9c4a9..cfa4e914 100644 --- a/modules/pack/examples/lux-manifest.rs +++ b/modules/pack/examples/lux-manifest.rs @@ -83,6 +83,7 @@ fn main() -> color_eyre::Result<()> { let mut visitor = Visitor { conv: Converter { generate_segment_index: false, + compression: None, }, output, ignore_pk: !args.include_pk, diff --git a/modules/pack/src/pk/fs.rs b/modules/pack/src/pk/fs.rs index 0c93256c..07b207e5 100644 --- a/modules/pack/src/pk/fs.rs +++ b/modules/pack/src/pk/fs.rs @@ -92,6 +92,8 @@ impl PKHandle { writer.write(&mut buf)?; buf.write_all(&MAGIC_SEP)?; + // A BufWriter ignores write errors when dropped (e.g. out of disk space) + buf.flush()?; let end = buf.stream_position()?; assert!(end <= u32::MAX.into()); @@ -116,6 +118,8 @@ impl PKHandle { let mut buf = BufWriter::new(&mut self.file); write_pk_directory_tree(&mut buf, &self.directory)?; write_pk_trailer(&mut buf, &self.trailer)?; + // A BufWriter ignores write errors when dropped (e.g. out of disk space) + buf.flush()?; // FIXME: truncate file if necessary Ok(()) } diff --git a/modules/pack/src/pki/gen.rs b/modules/pack/src/pki/gen.rs index de273513..f54a8110 100644 --- a/modules/pack/src/pki/gen.rs +++ b/modules/pack/src/pki/gen.rs @@ -137,7 +137,20 @@ impl Config { p }; match &arg.kind { - ArgKind::File => state.on_file(&path, arg.effect), + ArgKind::File => { + // Only include files that actually exist; a CRC for a + // missing file can never be packed or cached, and a + // pack made up entirely of such entries would be + // listed in the PKI without ever existing on disk. + if arg.effect == ArgEffect::Include + && !join_with_str(root, &arg.name).is_file() + { + #[cfg(feature = "log")] + log::warn!("skipping missing file {}", path); + continue; + } + state.on_file(&path, arg.effect) + } ArgKind::Dir { recurse, filter } => { let real_path = join_with_str(root, &arg.name); diff --git a/modules/pack/src/sd0/fs.rs b/modules/pack/src/sd0/fs.rs index 2bbc284f..0099ef62 100644 --- a/modules/pack/src/sd0/fs.rs +++ b/modules/pack/src/sd0/fs.rs @@ -71,7 +71,24 @@ impl Converter { break; } - cmp.compress_vec(&raw, &mut compressed, FlushCompress::Finish)?; + // compress_vec only writes into the vector's spare capacity and + // never grows it. CHUNK_BOUND is zlib's compressBound, but the + // miniz_oxide backend can exceed it on incompressible input at + // low compression levels; without the loop the stream was + // silently truncated at capacity, producing a corrupt chunk. + let mut input: &[u8] = &raw; + loop { + let before_in = cmp.total_in(); + let status = cmp.compress_vec(input, &mut compressed, FlushCompress::Finish)?; + let consumed = (cmp.total_in() - before_in) as usize; + input = &input[consumed..]; + match status { + flate2::Status::StreamEnd => break, + flate2::Status::Ok | flate2::Status::BufError => { + compressed.reserve(CHUNK_LEN / 4); + } + } + } cmp.reset(); let compressed_size = compressed.len() as u32; diff --git a/modules/pack/src/txt/manifest/mod.rs b/modules/pack/src/txt/manifest/mod.rs index 74550cb0..0892f900 100644 --- a/modules/pack/src/txt/manifest/mod.rs +++ b/modules/pack/src/txt/manifest/mod.rs @@ -5,7 +5,7 @@ mod lines; use std::collections::BTreeMap; use std::fmt; use std::fs::File; -use std::io::{BufRead, BufReader}; +use std::io::{BufRead, BufReader, Write}; use std::path::Path; #[cfg(feature = "async")] @@ -20,6 +20,9 @@ use self::lines::{file_line, version_line}; pub use self::lines::{FileLine, VersionLine}; pub use crate::common::FileMeta; +#[cfg(feature = "md5sum")] +use crate::{common::FileMetaPair, md5::MD5Sum}; + #[derive(Debug, Copy, Clone, PartialEq, Eq)] /// A section of the manifest pub enum Section { @@ -94,6 +97,24 @@ where Ok(version) } +/// The line ending to use when writing a manifest +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub enum LineEnding { + /// `\n` + Lf, + /// `\r\n`, like the manifests served to the original patcher + CrLf, +} + +impl LineEnding { + fn as_str(self) -> &'static str { + match self { + Self::Lf => "\n", + Self::CrLf => "\r\n", + } + } +} + /// A manifest file in-memory #[derive(Debug, Clone, PartialEq, Eq)] pub struct Manifest { @@ -177,6 +198,51 @@ impl Manifest { let mut reader = BufReader::new(file); Self::from_buf_read(&mut reader) } + + /// Add a file, calculating the checksum of its line + /// + /// The checksum covers the path as given, so this is also how to change a + /// path's form (e.g. from `\\` to `/` separators). + #[cfg(feature = "md5sum")] + pub fn add_file(&mut self, path: String, meta: FileMetaPair) { + let line_hash = MD5Sum::compute(&format!("{path},{meta}")); + self.files.insert(path, (meta, line_hash)); + } + + /// Write this manifest, which [`Manifest::from_buf_read`] reads back + /// + /// Every line ends with the line ending, like the original manifests. Files + /// are ordered by their path with `\\` separators, whichever form the paths + /// are in. + /// + /// ``` + /// use std::{collections::BTreeMap, io::Cursor}; + /// use assembly_pack::txt::{LineEnding, Manifest, VersionLine}; + /// + /// let manifest = Manifest { + /// version: VersionLine::new(32, String::from("Name")), + /// files: BTreeMap::new(), + /// }; + /// let mut text = Vec::new(); + /// manifest.write(&mut text, LineEnding::CrLf).unwrap(); + /// assert_eq!( + /// String::from_utf8(text.clone()).unwrap(), + /// format!("[version]\r\n{}\r\n[files]\r\n", manifest.version) + /// ); + /// assert_eq!(Manifest::from_buf_read(&mut Cursor::new(text)).unwrap(), manifest); + /// ``` + pub fn write(&self, writer: &mut W, ending: LineEnding) -> std::io::Result<()> { + let eol = ending.as_str(); + let version = Section::Version.as_header(); + let files = Section::Files.as_header(); + write!(writer, "{version}{eol}{}{eol}{files}{eol}", self.version)?; + let mut lines: Vec<_> = self.files.iter().collect(); + lines.sort_by_cached_key(|(path, _)| path.replace('/', "\\")); + for (path, (meta, line_hash)) in lines { + write!(writer, "{path},{meta},{line_hash}{eol}")?; + } + Ok(()) + } } /// Load the manifest from a stream of lines @@ -197,3 +263,70 @@ where Ok(Manifest { version, files }) } + +#[cfg(all(test, feature = "md5sum"))] +mod write_tests { + use super::{LineEnding, Manifest, VersionLine}; + use crate::{ + common::{FileMeta, FileMetaPair}, + md5::MD5Sum, + }; + use std::{collections::BTreeMap, io::Cursor}; + + fn meta(text: &str) -> FileMeta { + FileMeta { size: text.len() as u32, hash: MD5Sum::compute(text) } + } + + fn sample() -> Manifest { + let mut manifest = Manifest { + version: VersionLine::new(82, String::from("1.2.3")), + files: BTreeMap::new(), + }; + manifest.add_file("client/b.txt".into(), FileMetaPair::new(meta("b"), meta("bb"))); + manifest.add_file("client/a.txt".into(), FileMetaPair::new(meta("a"), meta("aa"))); + manifest + } + + #[test] + fn roundtrips_with_both_line_endings() { + for ending in [LineEnding::Lf, LineEnding::CrLf] { + let manifest = sample(); + let mut text = Vec::new(); + manifest.write(&mut text, ending).unwrap(); + let read = Manifest::from_buf_read(&mut Cursor::new(text)).unwrap(); + assert_eq!(read, manifest); + } + } + + #[test] + fn order_does_not_depend_on_the_separator() { + let order = |a: &str, b: &str| { + let mut manifest = sample(); + manifest.files.clear(); + manifest.add_file(a.into(), FileMetaPair::new(meta("a"), meta("aa"))); + manifest.add_file(b.into(), FileMetaPair::new(meta("b"), meta("bb"))); + let mut text = Vec::new(); + manifest.write(&mut text, LineEnding::Lf).unwrap(); + let text = String::from_utf8(text).unwrap(); + text.lines().nth(3).unwrap().split(',').next().unwrap().to_owned() + }; + // '/' < '1' < '\\', so a plain sort differs between the two forms + assert_eq!(order("client/a/b.txt", "client/a1/c.txt"), "client/a1/c.txt"); + assert_eq!(order("client\\a\\b.txt", "client\\a1\\c.txt"), "client\\a1\\c.txt"); + } + + #[test] + fn line_checksum_covers_the_first_five_fields_and_lines_are_sorted() { + let mut text = Vec::new(); + sample().write(&mut text, LineEnding::CrLf).unwrap(); + let text = String::from_utf8(text).unwrap(); + assert!(text.ends_with("\r\n")); + let lines: Vec<&str> = text.trim_end().split("\r\n").collect(); + assert_eq!(lines.len(), 5); + assert!(lines[3].starts_with("client/a.txt,")); + for line in &lines[3..] { + let (content, sum) = line.rsplit_once(',').unwrap(); + assert_eq!(format!("{}", MD5Sum::compute(content)), sum); + } + } +}