Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions modules/pack/examples/lux-manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 4 additions & 0 deletions modules/pack/src/pk/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());

Expand All @@ -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(())
}
Expand Down
15 changes: 14 additions & 1 deletion modules/pack/src/pki/gen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
19 changes: 18 additions & 1 deletion modules/pack/src/sd0/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
135 changes: 134 additions & 1 deletion modules/pack/src/txt/manifest/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand All @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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<W: 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
Expand All @@ -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);
}
}
}
Loading