From d6c11b40b73f7b94f040524cf1fc248888bd3afc Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 12:00:28 +0000 Subject: [PATCH 01/13] Share bounded seekable ZIP indexing --- crates/zip/README.md | 9 +++ crates/zip/src/lib.rs | 2 + crates/zip/src/metadata_reader.rs | 114 ++++++++++++++++++++++++++++++ 3 files changed, 125 insertions(+) create mode 100644 crates/zip/src/metadata_reader.rs diff --git a/crates/zip/README.md b/crates/zip/README.md index 079267b9f..6cffa7786 100644 --- a/crates/zip/README.md +++ b/crates/zip/README.md @@ -70,3 +70,12 @@ calls it first. `preflight`, `read_entry` and `Budget`: the ZIP half of the craft-archive proposal (#126, #129). `check_entry_count`: craft-opc's `guard`. Duplicate detection: craft-penpot's rule, made exact by walking the directory. The writer: craft-opc's `ZipOut`. + +## Seekable indexing + +`MetadataReader::new(reader, metadata_bytes)` wraps a `Read + Seek` source without loading its +payload into memory. During ZIP indexing it admits reads only from the last `metadata_bytes` +bytes and charges repeated reads against twice that number. Call `Indexing::finish` on the +returned handle after the ZIP index has been parsed to permit normal streaming payload reads. +The caller must still enforce entry-count, declared-size and overlap limits: the wrapper only +bounds metadata reads and does not validate the archive. diff --git a/crates/zip/src/lib.rs b/crates/zip/src/lib.rs index 452351ee3..73eb9840a 100644 --- a/crates/zip/src/lib.rs +++ b/crates/zip/src/lib.rs @@ -23,6 +23,7 @@ struct ReadmeExamples; mod archive; mod guard; +mod metadata_reader; pub mod preflight; mod write; @@ -30,6 +31,7 @@ pub use archive::{Archive, Limits}; pub use guard::check_entry_count; #[cfg(any(test, feature = "test-support"))] pub use guard::zip64_entry_count_sample; +pub use metadata_reader::{Indexing, MetadataReader}; pub use write::{Compression, Writer}; /// The payload of a ZIP's first entry when it is a stored file named `mimetype` of at most 256 diff --git a/crates/zip/src/metadata_reader.rs b/crates/zip/src/metadata_reader.rs new file mode 100644 index 000000000..6bba5759d --- /dev/null +++ b/crates/zip/src/metadata_reader.rs @@ -0,0 +1,114 @@ +//! Bound the reads a ZIP indexer may perform before accessing entry payloads. + +use std::io::{self, Read, Seek, SeekFrom}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +/// A seekable reader whose indexing phase is restricted to a tail window and read budget. +/// +/// Keep the returned [`Indexing`] handle until the ZIP central directory has been parsed, then +/// call [`Indexing::finish`] to allow normal entry reads. Repeated reads during indexing count +/// towards the allowance, including reads after seeks. This bounds metadata scanning without +/// buffering the whole file or restricting the size of its payload entries. +pub struct MetadataReader { + inner: R, + indexing: Arc, + metadata_start: u64, + remaining: u64, + position: u64, +} + +/// Controls the indexing restriction for the associated reader. +#[derive(Clone)] +pub struct Indexing(Arc); + +impl Indexing { + /// Permit reads outside the metadata window once indexing is finished. + pub fn finish(&self) { + self.0.store(false, Ordering::Release); + } +} + +impl MetadataReader { + /// Limit indexing to the last `metadata_bytes` bytes and at most twice that many bytes read. + pub fn new(mut inner: R, metadata_bytes: u64) -> io::Result<(Self, Indexing)> { + let end = inner.seek(SeekFrom::End(0))?; + let indexing = Arc::new(AtomicBool::new(true)); + let handle = Indexing(indexing.clone()); + Ok(( + Self { inner, indexing, metadata_start: end.saturating_sub(metadata_bytes), remaining: metadata_bytes.saturating_mul(2), position: end }, + handle, + )) + } +} + +impl Read for MetadataReader { + fn read(&mut self, bytes: &mut [u8]) -> io::Result { + if bytes.is_empty() { + return Ok(0); + } + let indexing = self.indexing.load(Ordering::Acquire); + if indexing && (self.position < self.metadata_start || self.remaining == 0) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "ZIP metadata exceeds the indexing limit")); + } + let length = if indexing { bytes.len().min(usize::try_from(self.remaining).unwrap_or(usize::MAX)) } else { bytes.len() }; + let read = self.inner.read(bytes.get_mut(..length).unwrap_or_default())?; + self.position = self.position.saturating_add(read as u64); + if indexing { + self.remaining -= read as u64; + } + Ok(read) + } +} + +impl Seek for MetadataReader { + fn seek(&mut self, from: SeekFrom) -> io::Result { + self.position = self.inner.seek(from)?; + Ok(self.position) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn indexing_cannot_read_payloads_outside_the_metadata_window() { + let (mut reader, indexing) = MetadataReader::new(Cursor::new(vec![7; 100]), 8).unwrap(); + reader.seek(SeekFrom::Start(91)).unwrap(); + assert!(reader.read(&mut [0; 1]).is_err()); + reader.seek(SeekFrom::Start(92)).unwrap(); + reader.read_exact(&mut [0; 8]).unwrap(); + indexing.finish(); + reader.seek(SeekFrom::Start(0)).unwrap(); + reader.read_exact(&mut [0; 100]).unwrap(); + } + + #[test] + fn zip_indexing_is_tail_bounded_then_payload_reads_stream() { + let mut writer = crate::Writer::new(); + writer.add("large.bin", &vec![42; 131_072], crate::Compression::Stored).unwrap(); + let bytes = writer.finish().unwrap(); + let (reader, indexing) = MetadataReader::new(Cursor::new(bytes), 16_384).unwrap(); + let config = zip::read::Config { archive_offset: zip::read::ArchiveOffset::Known(0) }; + let mut archive = zip::ZipArchive::with_config(config, reader).unwrap(); + assert!(archive.by_name("large.bin").is_err(), "indexing must not read the payload header"); + indexing.finish(); + let mut entry = archive.by_name("large.bin").unwrap(); + let mut payload = Vec::new(); + entry.read_to_end(&mut payload).unwrap(); + assert_eq!(payload, vec![42; 131_072]); + } + + #[test] + fn repeated_metadata_scans_share_one_read_allowance() { + let (mut reader, _indexing) = MetadataReader::new(Cursor::new(vec![7; 8]), 8).unwrap(); + for _ in 0..2 { + reader.seek(SeekFrom::Start(0)).unwrap(); + reader.read_exact(&mut [0; 8]).unwrap(); + } + reader.seek(SeekFrom::Start(0)).unwrap(); + assert!(reader.read(&mut [0; 1]).is_err()); + } +} From 2af057527956387e30a2916b1219b7e75014690d Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Thu, 1 Oct 2026 22:49:07 -0400 Subject: [PATCH 02/13] psd: import annotation reader primitives from PhotoCraft --- crates/psd/src/annotations.rs | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 crates/psd/src/annotations.rs diff --git a/crates/psd/src/annotations.rs b/crates/psd/src/annotations.rs new file mode 100644 index 000000000..c982d3338 --- /dev/null +++ b/crates/psd/src/annotations.rs @@ -0,0 +1,43 @@ +// Reader primitives extracted from PhotoCraft annotations_map.rs at aa87012a. +struct Reader<'a> { + d: &'a [u8], + p: usize, +} + +impl<'a> Reader<'a> { + fn take(&mut self, n: usize) -> Option<&'a [u8]> { + let s = self.d.get(self.p..self.p.checked_add(n)?)?; + self.p += n; + Some(s) + } + fn u8(&mut self) -> Option { + self.take(1).map(|b| b[0]) + } + fn u16(&mut self) -> Option { + self.take(2).map(|b| u16::from_be_bytes([b[0], b[1]])) + } + fn u32(&mut self) -> Option { + self.take(4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]])) + } + fn i32(&mut self) -> Option { + self.u32().map(|v| v as i32) + } + fn pascal(&mut self) -> Option { + let n = usize::from(self.u8()?); + let s = self.take(n)?; + if (n + 1) % 2 == 1 { + self.take(1)?; + } + Some(s.iter().map(|&c| c as char).collect()) + } +} + +fn pascal(out: &mut Vec, s: &str) { + let bytes: Vec = s.chars().map(|c| if (c as u32) < 256 { c as u32 as u8 } else { b'?' }).take(255).collect(); + out.push(bytes.len() as u8); + out.extend_from_slice(&bytes); + if (bytes.len() + 1) % 2 == 1 { + out.push(0); + } +} + From 2c3171d73442f4b44aa3a8b0f1b4fc35dd497628 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 13 Oct 2026 02:37:02 +0200 Subject: [PATCH 03/13] psd: retain the non-advancing annotation length guard --- crates/psd/src/annotations.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/psd/src/annotations.rs b/crates/psd/src/annotations.rs index c982d3338..b1d309c5a 100644 --- a/crates/psd/src/annotations.rs +++ b/crates/psd/src/annotations.rs @@ -41,3 +41,13 @@ fn pascal(out: &mut Vec, s: &str) { } } + +// Minimum-length guard imported from PhotoCraft b1b3dff8 (David Mann). +fn advancing_record_length(len: usize) -> Option<()> { + // The length counts itself and the type: anything shorter would put the cursor back on + // this entry, and a hostile count would then loop until memory runs out. + if len < 8 { + return None; + } + Some(()) +} From 22c9a0933d292d0875196201af09fb1455e8a710 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 07:43:59 -0500 Subject: [PATCH 04/13] psd: expose bounded annotation record views and serialization --- crates/psd/src/annotations.rs | 237 ++++++++++++++++++++++++---- crates/psd/src/annotations/tests.rs | 117 ++++++++++++++ crates/psd/src/lib.rs | 1 + 3 files changed, 325 insertions(+), 30 deletions(-) create mode 100644 crates/psd/src/annotations/tests.rs diff --git a/crates/psd/src/annotations.rs b/crates/psd/src/annotations.rs index b1d309c5a..57b466843 100644 --- a/crates/psd/src/annotations.rs +++ b/crates/psd/src/annotations.rs @@ -1,53 +1,230 @@ -// Reader primitives extracted from PhotoCraft annotations_map.rs at aa87012a. +//! Bounded, borrowed views and serialization of PSD global `Anno` records. +//! +//! Framing follows PhotoCraft's annotation reader (Brandon Thomas, aa87012a), with +//! David Mann's minimum-length guard and the per-entry span fix from PhotoCraft +//! #11138. Coordinates, colour conversion, text decoding and popup defaults are +//! deliberately caller policy. Unknown records can be carried through byte-exact. + +use crate::{PsdError, Result}; + +/// Explicit limits shared by readers and writers. +#[derive(Clone, Copy, Debug)] +pub struct Limits { + /// Maximum complete block size. + pub bytes: usize, + /// Maximum annotation count. + pub records: usize, +} +impl Default for Limits { + fn default() -> Self { + Self { bytes: 16 * 1024 * 1024, records: 4096 } + } +} + struct Reader<'a> { d: &'a [u8], p: usize, } - impl<'a> Reader<'a> { - fn take(&mut self, n: usize) -> Option<&'a [u8]> { - let s = self.d.get(self.p..self.p.checked_add(n)?)?; - self.p += n; - Some(s) + fn take(&mut self, n: usize) -> Result<&'a [u8]> { + let end = self.p.checked_add(n).ok_or(PsdError::LimitExceeded("annotation offset"))?; + let s = self.d.get(self.p..end).ok_or(PsdError::UnexpectedEof { offset: self.p, needed: n })?; + self.p = end; + Ok(s) } - fn u8(&mut self) -> Option { - self.take(1).map(|b| b[0]) + fn u8(&mut self) -> Result { + Ok(self.take(1)?.first().copied().unwrap_or_default()) } - fn u16(&mut self) -> Option { - self.take(2).map(|b| u16::from_be_bytes([b[0], b[1]])) + fn u16(&mut self) -> Result { + Ok(u16::from_be_bytes(self.take(2)?.try_into().map_err(|_| PsdError::invalid("annotation u16"))?)) } - fn u32(&mut self) -> Option { - self.take(4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]])) + fn u32(&mut self) -> Result { + Ok(u32::from_be_bytes(self.take(4)?.try_into().map_err(|_| PsdError::invalid("annotation u32"))?)) } - fn i32(&mut self) -> Option { - self.u32().map(|v| v as i32) + fn key(&mut self) -> Result<[u8; 4]> { + self.take(4)?.try_into().map_err(|_| PsdError::invalid("annotation key")) } - fn pascal(&mut self) -> Option { + fn rect(&mut self) -> Result<[i32; 4]> { + Ok([self.u32()? as i32, self.u32()? as i32, self.u32()? as i32, self.u32()? as i32]) + } + fn pascal(&mut self) -> Result<&'a [u8]> { let n = usize::from(self.u8()?); - let s = self.take(n)?; + let bytes = self.take(n)?; if (n + 1) % 2 == 1 { self.take(1)?; } - Some(s.iter().map(|&c| c as char).collect()) + Ok(bytes) } } -fn pascal(out: &mut Vec, s: &str) { - let bytes: Vec = s.chars().map(|c| if (c as u32) < 256 { c as u32 as u8 } else { b'?' }).take(255).collect(); - out.push(bytes.len() as u8); - out.extend_from_slice(&bytes); +/// A borrowed record, including its original length, padding and unknown fields. +#[derive(Clone, Copy, Debug)] +pub struct Record<'a> { + raw: &'a [u8], +} +impl<'a> Record<'a> { + /// Complete self-counting record, suitable for lossless passthrough. + pub fn raw(&self) -> &'a [u8] { + self.raw + } + /// Parse text records; other record kinds remain opaque. + pub fn text(&self) -> Result>> { + let mut r = Reader { d: self.raw, p: 4 }; + if r.key()? != *b"txtA" { + return Ok(None); + } + // Never read beyond this record, even if a text length points into its neighbour. + let open = r.u8()?; + let flags = r.u8()?; + let optional_blocks = r.u16()?; + let icon = r.rect()?; + let popup = r.rect()?; + let color_space = r.u16()?; + let color = [r.u16()?, r.u16()?, r.u16()?, r.u16()?]; + let author = r.pascal()?; + let name = r.pascal()?; + let modified = r.pascal()?; + let data_length = r.u32()?; + let data_key = r.key()?; + let size = usize::try_from(r.u32()?).map_err(|_| PsdError::LimitExceeded("annotation text"))?; + let data = r.take(size)?; + Ok(Some(Text { open, flags, optional_blocks, icon, popup, color_space, color, author, name, modified, data_length, data_key, data })) + } +} + +/// Wire-level text annotation. Text payload and Pascal strings remain bytes. +/// No text normalisation or application colour/coordinate policy is applied. +#[derive(Clone, Copy, Debug)] +pub struct Text<'a> { + /// Open state byte. + pub open: u8, + /// Flags byte. + pub flags: u8, + /// Optional block flags. + pub optional_blocks: u16, + /// Icon rectangle, top/left/bottom/right. + pub icon: [i32; 4], + /// Popup rectangle, top/left/bottom/right. + pub popup: [i32; 4], + /// PSD colour space. + pub color_space: u16, + /// Raw colour components. + pub color: [u16; 4], + /// Pascal author bytes, maximum 255. + pub author: &'a [u8], + /// Pascal name bytes, maximum 255. + pub name: &'a [u8], + /// Pascal modification-date bytes, maximum 255. + pub modified: &'a [u8], + /// Original self-counting data length, exposed for diagnostics. + /// The writer recomputes this field. + pub data_length: u32, + /// Usually `txtC`; retained without imposing application policy. + pub data_key: [u8; 4], + /// Payload, including any text byte-order mark. + pub data: &'a [u8], +} + +/// Parse complete framing before exposing records. Borrowed payloads do not allocate. +/// Trailing block bytes are accepted as in the existing PhotoCraft reader. +pub fn read(data: &[u8], limits: Limits) -> Result>> { + if data.len() > limits.bytes { + return Err(PsdError::LimitExceeded("annotation bytes")); + } + let mut r = Reader { d: data, p: 0 }; + r.u16()?; + r.u16()?; + let count = usize::try_from(r.u32()?).map_err(|_| PsdError::LimitExceeded("annotation count"))?; + if count > limits.records || count > data.len().saturating_sub(8) / 8 { + return Err(PsdError::LimitExceeded("annotation count")); + } + let mut out = Vec::new(); + out.try_reserve_exact(count).map_err(|_| PsdError::OutOfMemory("annotation records"))?; + for _ in 0..count { + let start = r.p; + let len = usize::try_from(r.u32()?).map_err(|_| PsdError::LimitExceeded("annotation length"))?; + // David Mann's zero-length guard: a self-counting record must advance. + if len < 8 { + return Err(PsdError::invalid("annotation record shorter than its header")); + } + r.p = start; + let record = Record { raw: r.take(len)? }; + record.text()?; // validate text spans, including data borrowed by later consumers + out.push(record); + } + Ok(out) +} + +fn append(out: &mut Vec, bytes: &[u8], limit: usize) -> Result<()> { + let len = out.len().checked_add(bytes.len()).ok_or(PsdError::LimitExceeded("annotation bytes"))?; + if len > limit { + return Err(PsdError::LimitExceeded("annotation bytes")); + } + out.try_reserve(bytes.len()).map_err(|_| PsdError::OutOfMemory("annotation bytes"))?; + out.extend_from_slice(bytes); + Ok(()) +} + +fn pascal(out: &mut Vec, bytes: &[u8], limit: usize) -> Result<()> { + let n = u8::try_from(bytes.len()).map_err(|_| PsdError::LimitExceeded("annotation Pascal string"))?; + append(out, &[n], limit)?; + append(out, bytes, limit)?; if (bytes.len() + 1) % 2 == 1 { - out.push(0); + append(out, &[0], limit)?; } + Ok(()) } - -// Minimum-length guard imported from PhotoCraft b1b3dff8 (David Mann). -fn advancing_record_length(len: usize) -> Option<()> { - // The length counts itself and the type: anything shorter would put the cursor back on - // this entry, and a hostile count would then loop until memory runs out. - if len < 8 { - return None; +/// Serialize one text record, computing both length fields. Caller supplies raw +/// text bytes and already-mapped colour/coordinates; nothing is truncated. +pub fn write_text(text: &Text<'_>, limits: Limits) -> Result> { + let mut out = Vec::new(); + append(&mut out, &[0; 4], limits.bytes)?; + append(&mut out, b"txtA", limits.bytes)?; + append(&mut out, &[text.open, text.flags], limits.bytes)?; + append(&mut out, &text.optional_blocks.to_be_bytes(), limits.bytes)?; + for value in text.icon.into_iter().chain(text.popup) { + append(&mut out, &value.to_be_bytes(), limits.bytes)?; } - Some(()) + append(&mut out, &text.color_space.to_be_bytes(), limits.bytes)?; + for value in text.color { + append(&mut out, &value.to_be_bytes(), limits.bytes)?; + } + for value in [text.author, text.name, text.modified] { + pascal(&mut out, value, limits.bytes)?; + } + let n = u32::try_from(text.data.len()).map_err(|_| PsdError::LimitExceeded("annotation text"))?; + let data_length = n.checked_add(12).ok_or(PsdError::LimitExceeded("annotation data length"))?; + append(&mut out, &data_length.to_be_bytes(), limits.bytes)?; + append(&mut out, &text.data_key, limits.bytes)?; + append(&mut out, &n.to_be_bytes(), limits.bytes)?; + append(&mut out, text.data, limits.bytes)?; + let len = u32::try_from(out.len()).map_err(|_| PsdError::LimitExceeded("annotation record length"))?; + out.get_mut(..4).ok_or_else(|| PsdError::invalid("annotation header"))?.copy_from_slice(&len.to_be_bytes()); + Ok(out) } + +/// Combine already-framed records into a version 2.1 block. Unknown record types +/// are preserved byte-exact; malformed text records are refused. +pub fn write(records: &[&[u8]], limits: Limits) -> Result> { + if records.len() > limits.records { + return Err(PsdError::LimitExceeded("annotation count")); + } + let count = u32::try_from(records.len()).map_err(|_| PsdError::LimitExceeded("annotation count"))?; + let mut out = Vec::new(); + append(&mut out, &[0, 2, 0, 1], limits.bytes)?; + append(&mut out, &count.to_be_bytes(), limits.bytes)?; + for raw in records { + let mut r = Reader { d: raw, p: 0 }; + let declared = usize::try_from(r.u32()?).map_err(|_| PsdError::LimitExceeded("annotation record length"))?; + if raw.len() < 8 || declared != raw.len() { + return Err(PsdError::invalid("annotation record length mismatch")); + } + Record { raw }.text()?; + append(&mut out, raw, limits.bytes)?; + } + Ok(out) +} + +#[cfg(test)] +mod tests; diff --git a/crates/psd/src/annotations/tests.rs b/crates/psd/src/annotations/tests.rs new file mode 100644 index 000000000..e207852d4 --- /dev/null +++ b/crates/psd/src/annotations/tests.rs @@ -0,0 +1,117 @@ +use super::*; + +fn note() -> Text<'static> { + Text { + open: 1, + flags: 0x1c, + optional_blocks: 1, + icon: [10, 20, 30, 36], + popup: [30, 40, 190, 280], + color_space: 0, + color: [65535, 1000, 3000, 0], + author: b"Writer", + name: b"", + modified: b"2026", + data_length: 0, + data_key: *b"txtC", + data: &[0xfe, 0xff, 0, 65, 0, 13, 0, 66], + } +} + +#[test] +fn text_and_unknown_sound_round_trip_without_copying_payloads() { + let limits = Limits::default(); + let text = write_text(¬e(), limits).unwrap(); + let sound = [0, 0, 0, 11, b's', b'n', b'd', b'A', 42, 3, 9]; + let block = write(&[&text, &sound], limits).unwrap(); + let parsed = read(&block, limits).unwrap(); + assert_eq!(parsed.len(), 2); + let view = parsed[0].text().unwrap().unwrap(); + assert_eq!(view.author, note().author); + assert_eq!(view.data, note().data); + assert_eq!(view.icon, note().icon); + assert_eq!(view.color, note().color); + assert_eq!(view.data_length, 20); + assert!(parsed[1].text().unwrap().is_none()); + assert_eq!(parsed[1].raw(), sound); + let slices: Vec<_> = parsed.iter().map(Record::raw).collect(); + assert_eq!(write(&slices, limits).unwrap(), block); + assert!(view.data.as_ptr() >= block.as_ptr()); + assert!(view.data.as_ptr() < block.as_ptr().wrapping_add(block.len())); +} + +#[test] +fn text_cannot_read_past_the_declared_entry_into_its_neighbour() { + // Regression from PhotoCraft #11138, without its app Note/Color policy. + let mut record = write_text(¬e(), Limits::default()).unwrap(); + let shortened = record.len() - note().data.len(); + record[..4].copy_from_slice(&(shortened as u32).to_be_bytes()); + let mut block = vec![0, 2, 0, 1, 0, 0, 0, 1]; + block.extend_from_slice(&record); + assert!(read(&block, Limits::default()).is_err()); + assert!(write(&[&record], Limits::default()).is_err()); +} + +#[test] +fn truncation_and_hostile_counts_lengths_fail_closed() { + let record = write_text(¬e(), Limits::default()).unwrap(); + let block = write(&[&record], Limits::default()).unwrap(); + for end in 0..block.len() { + assert!(read(&block[..end], Limits::default()).is_err(), "{end}"); + } + for len in [0u32, 1, 7, u32::MAX] { + let mut bad = block.clone(); + bad[8..12].copy_from_slice(&len.to_be_bytes()); + assert!(read(&bad, Limits::default()).is_err()); + } + let mut bad = block; + bad[4..8].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(read(&bad, Limits::default()).is_err()); +} + +#[test] +fn explicit_limits_and_pascal_length_are_not_silently_truncated() { + let record = write_text(¬e(), Limits::default()).unwrap(); + let block = write(&[&record], Limits::default()).unwrap(); + assert!(read(&block, Limits { records: 0, ..Limits::default() }).is_err()); + assert!(read(&block, Limits { bytes: block.len() - 1, ..Limits::default() }).is_err()); + assert!(write(&[&record], Limits { records: 0, ..Limits::default() }).is_err()); + assert!(write_text(¬e(), Limits { bytes: record.len() - 1, ..Limits::default() }).is_err()); + let long = [0; 256]; + let mut text = note(); + text.author = &long; + assert!(write_text(&text, Limits::default()).is_err()); +} + +#[test] +fn preserves_legacy_version_and_unused_data_header_acceptance() { + let record = write_text(¬e(), Limits::default()).unwrap(); + let mut block = write(&[&record], Limits::default()).unwrap(); + block[..4].copy_from_slice(&[0, 9, 0, 8]); + block.extend_from_slice(b"trailing"); + assert_eq!(read(&block, Limits::default()).unwrap()[0].raw(), record); +} + +#[test] +fn canonical_layout_matches_the_existing_photocraft_writer() { + // PhotoCraft annotations_map::write_note layout (Brandon Thomas, aa87012a). + // App RGB/position/text conversion happens before this shared wire writer. + let n = note(); + let mut expected = vec![0, 0, 0, 0]; + expected.extend_from_slice(b"txtA"); + expected.extend_from_slice(&[1, 0x1c, 0, 1]); + for value in [10i32, 20, 30, 36, 30, 40, 190, 280] { + expected.extend_from_slice(&value.to_be_bytes()); + } + for value in [0u16, 65535, 1000, 3000, 0] { + expected.extend_from_slice(&value.to_be_bytes()); + } + expected.extend_from_slice(b"\x06Writer\x00\x00\x00\x042026\x00"); + expected.extend_from_slice(&20u32.to_be_bytes()); + expected.extend_from_slice(b"txtC"); + expected.extend_from_slice(&8u32.to_be_bytes()); + expected.extend_from_slice(n.data); + let len = expected.len() as u32; + expected[..4].copy_from_slice(&len.to_be_bytes()); + assert_eq!(write_text(&n, Limits::default()).unwrap(), expected); +} diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rs index 93acd5f39..8126437ff 100644 --- a/crates/psd/src/lib.rs +++ b/crates/psd/src/lib.rs @@ -54,6 +54,7 @@ pub mod aco; pub mod act; pub mod adjust; pub mod animation; +pub mod annotations; pub mod ase; pub mod asl; pub mod atn; From 72ee990e036fc2305adf2180110b42d32d49716c Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Sun, 15 Nov 2026 07:55:30 -0500 Subject: [PATCH 05/13] Import binary plist parser changes from Craft Anything f64ae3bf --- crates/plist/LICENSE-APACHE | 177 ++++++++++++++++++++++++++ crates/plist/LICENSE-MIT | 21 ++++ crates/plist/src/binary.rs | 241 ++++++++++++++++++++++++++++++++++++ crates/plist/src/bytes.rs | 82 ++++++++++++ 4 files changed, 521 insertions(+) create mode 100644 crates/plist/LICENSE-APACHE create mode 100644 crates/plist/LICENSE-MIT create mode 100644 crates/plist/src/binary.rs create mode 100644 crates/plist/src/bytes.rs diff --git a/crates/plist/LICENSE-APACHE b/crates/plist/LICENSE-APACHE new file mode 100644 index 000000000..f433b1a53 --- /dev/null +++ b/crates/plist/LICENSE-APACHE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/crates/plist/LICENSE-MIT b/crates/plist/LICENSE-MIT new file mode 100644 index 000000000..8e6399401 --- /dev/null +++ b/crates/plist/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 ArtCraft Team and the Craft Anything contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/plist/src/binary.rs b/crates/plist/src/binary.rs new file mode 100644 index 000000000..21ac84a86 --- /dev/null +++ b/crates/plist/src/binary.rs @@ -0,0 +1,241 @@ +use crate::{FormatError, bytes::Reader}; + +pub const MAX_DEPTH: usize = 256; +pub const MAX_NODES: usize = 2_000_000; +pub const MAX_EXPANDED_BYTES: usize = 64 << 20; + +#[derive(Debug, Clone, PartialEq)] +pub enum Value { + Dict(Vec<(String, Value)>), + Array(Vec), + String(String), + Integer(i128), + Real(f64), + Bool(bool), + /// Seconds since 2001-01-01T00:00:00Z (binary), or the ISO text (XML). + Date(DateValue), + Data(Vec), + /// A keyed-archive object reference. + Uid(u64), + Null, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum DateValue { + Seconds(f64), + Text(String), +} + +impl Value { + pub fn get(&self, key: &str) -> Option<&Value> { + match self { + Value::Dict(d) => d.iter().find(|(k, _)| k == key).map(|(_, v)| v), + _ => None, + } + } + + pub fn as_str(&self) -> Option<&str> { + match self { + Value::String(s) => Some(s), + _ => None, + } + } + + pub fn as_array(&self) -> Option<&[Value]> { + match self { + Value::Array(a) => Some(a), + _ => None, + } + } + + pub fn as_uid(&self) -> Option { + match self { + Value::Uid(u) => Some(*u), + _ => None, + } + } + + pub fn as_int(&self) -> Option { + match self { + Value::Integer(i) => Some(*i), + _ => None, + } + } + +} +struct Bin<'a> { + r: Reader<'a>, + offsets: Vec, + ref_size: usize, + nodes: usize, +} + +/// Parse a `bplist00` binary property list. +pub fn parse_binary(data: &[u8]) -> Result { + if !data.starts_with(b"bplist") { + return Err(FormatError::Malformed("not a binary plist".into())); + } + let len = data.len(); + if len < 8 + 32 { + return Err(FormatError::Truncated("binary plist trailer".into())); + } + let r = Reader::new(data); + let t = len - 32; + let off_size = usize::from(r.u8(t + 6).unwrap_or(0)); + let ref_size = usize::from(r.u8(t + 7).unwrap_or(0)); + let num = r.u64_be(t + 8).unwrap_or(0); + let top = r.u64_be(t + 16).unwrap_or(0); + let table = r.u64_be(t + 24).unwrap_or(0); + if !(1..=8).contains(&off_size) || !(1..=8).contains(&ref_size) { + return Err(FormatError::Malformed("bad offset or reference size".into())); + } + let num = usize::try_from(num).map_err(|_| FormatError::Malformed("object count".into()))?; + let table = usize::try_from(table).map_err(|_| FormatError::Malformed("offset table".into()))?; + if num == 0 || num > len { + return Err(FormatError::Malformed(format!("{num} objects in a {len}-byte file"))); + } + let need = num.checked_mul(off_size).and_then(|n| n.checked_add(table)).ok_or_else(|| FormatError::Malformed("offset table".into()))?; + if need > t || table < 8 { + return Err(FormatError::Truncated("offset table runs past the trailer".into())); + } + let mut offsets = Vec::with_capacity(num); + for i in 0..num { + let o = read_be(&r, table + i * off_size, off_size).ok_or_else(|| FormatError::Truncated("offset table".into()))?; + let o = usize::try_from(o).map_err(|_| FormatError::Malformed("object offset".into()))?; + if o >= table { + return Err(FormatError::Malformed(format!("object {i} lies outside the object area"))); + } + offsets.push(o); + } + let top = usize::try_from(top).map_err(|_| FormatError::Malformed("top object".into()))?; + let mut b = Bin { r, offsets, ref_size, nodes: 0 }; + let mut stack = Vec::new(); + b.object(top, &mut stack) +} + +fn read_be(r: &Reader<'_>, off: usize, n: usize) -> Option { + let s = r.slice(off, n)?; + Some(s.iter().fold(0u64, |acc, &b| (acc << 8) | u64::from(b))) +} + +impl Bin<'_> { + fn count(&self, at: usize, low: u8) -> Result<(usize, usize), FormatError> { + if low != 0xf { + return Ok((usize::from(low), at + 1)); + } + let m = self.r.u8(at + 1).ok_or_else(|| FormatError::Truncated("length".into()))?; + if m & 0xf0 != 0x10 { + return Err(FormatError::Malformed("bad extended length marker".into())); + } + let n = 1usize << (m & 0x0f).min(3); + let v = read_be(&self.r, at + 2, n).ok_or_else(|| FormatError::Truncated("length".into()))?; + let v = usize::try_from(v).map_err(|_| FormatError::Malformed("length".into()))?; + Ok((v, at + 2 + n)) + } + + fn reference(&self, at: usize, i: usize) -> Result { + let off = i.checked_mul(self.ref_size).and_then(|x| x.checked_add(at)).ok_or_else(|| FormatError::Malformed("reference".into()))?; + let v = read_be(&self.r, off, self.ref_size).ok_or_else(|| FormatError::Truncated("object reference".into()))?; + usize::try_from(v).map_err(|_| FormatError::Malformed("reference".into())) + } + + fn object(&mut self, idx: usize, stack: &mut Vec) -> Result { + self.nodes += 1; + if self.nodes > MAX_NODES { + return Err(FormatError::TooLarge(format!("more than {MAX_NODES} plist nodes"))); + } + if stack.len() >= MAX_DEPTH { + return Err(FormatError::Malformed("nesting too deep".into())); + } + if stack.contains(&idx) { + return Err(FormatError::Malformed(format!("object {idx} contains itself"))); + } + let at = *self.offsets.get(idx).ok_or_else(|| FormatError::Malformed(format!("reference to missing object {idx}")))?; + let m = self.r.u8(at).ok_or_else(|| FormatError::Truncated("object marker".into()))?; + let (hi, lo) = (m >> 4, m & 0x0f); + let v = match hi { + 0x0 => match lo { + 0x0 => Value::Null, + 0x8 => Value::Bool(false), + 0x9 => Value::Bool(true), + _ => Value::Null, + }, + 0x1 => { + let n = 1usize << lo.min(4); + let bytes = self.r.slice(at + 1, n).ok_or_else(|| FormatError::Truncated("integer".into()))?; + let v = match n { + 8 => i128::from(i64::from_be_bytes(bytes.try_into().map_err(|_| FormatError::Truncated("integer".into()))?)), + 16 => i128::from_be_bytes(bytes.try_into().map_err(|_| FormatError::Truncated("integer".into()))?), + _ => i128::from(bytes.iter().fold(0u64, |acc, &b| (acc << 8) | u64::from(b))), + }; + Value::Integer(v) + } + 0x2 => { + let v = match lo { + 2 => self.r.u32_be(at + 1).map(|b| f64::from(f32::from_bits(b))), + 3 => self.r.u64_be(at + 1).map(f64::from_bits), + _ => None, + }; + Value::Real(v.ok_or_else(|| FormatError::Truncated("real".into()))?) + } + 0x3 => Value::Date(DateValue::Seconds(self.r.u64_be(at + 1).map(f64::from_bits).ok_or_else(|| FormatError::Truncated("date".into()))?)), + 0x4 => { + let (n, s) = self.count(at, lo)?; + Value::Data(self.r.slice(s, n).ok_or_else(|| FormatError::Truncated("data".into()))?.to_vec()) + } + 0x5 => { + let (n, s) = self.count(at, lo)?; + Value::String(String::from_utf8_lossy(self.r.slice(s, n).ok_or_else(|| FormatError::Truncated("string".into()))?).into_owned()) + } + 0x6 => { + let (n, s) = self.count(at, lo)?; + let bytes = self + .r + .slice(s, n.checked_mul(2).ok_or_else(|| FormatError::Malformed("string".into()))?) + .ok_or_else(|| FormatError::Truncated("string".into()))?; + let units: Vec = bytes.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)).collect(); + Value::String(String::from_utf16_lossy(&units)) + } + 0x8 => { + let n = usize::from(lo) + 1; + Value::Uid(read_be(&self.r, at + 1, n).ok_or_else(|| FormatError::Truncated("uid".into()))?) + } + 0xa | 0xc => { + let (n, s) = self.count(at, lo)?; + if n > self.offsets.len().saturating_mul(4).max(16) || s.saturating_add(n.saturating_mul(self.ref_size)) > self.r.len() { + return Err(FormatError::Malformed("array larger than the file".into())); + } + stack.push(idx); + let mut out = Vec::with_capacity(n); + for i in 0..n { + let child = self.reference(s, i)?; + out.push(self.object(child, stack)?); + } + stack.pop(); + Value::Array(out) + } + 0xd => { + let (n, s) = self.count(at, lo)?; + if s.saturating_add(n.saturating_mul(self.ref_size).saturating_mul(2)) > self.r.len() { + return Err(FormatError::Malformed("dictionary larger than the file".into())); + } + stack.push(idx); + let mut out = Vec::with_capacity(n); + for i in 0..n { + let k = self.reference(s, i)?; + let v = self.reference(s, i + n)?; + let key = match self.object(k, stack)? { + Value::String(s) => s, + other => format!("{:?}", other.to_json()), + }; + out.push((key, self.object(v, stack)?)); + } + stack.pop(); + Value::Dict(out) + } + _ => return Err(FormatError::Malformed(format!("unknown object marker {m:#04x}"))), + }; + Ok(v) + } +} + diff --git a/crates/plist/src/bytes.rs b/crates/plist/src/bytes.rs new file mode 100644 index 000000000..b9de989c3 --- /dev/null +++ b/crates/plist/src/bytes.rs @@ -0,0 +1,82 @@ +//! Checked little/big-endian reads over untrusted bytes. Every read returns `None` when out of range. + +#[derive(Debug, Clone, Copy)] +pub struct Reader<'a> { + data: &'a [u8], +} + +impl<'a> Reader<'a> { + pub fn new(data: &'a [u8]) -> Self { + Reader { data } + } + + pub fn len(&self) -> usize { + self.data.len() + } + + pub fn is_empty(&self) -> bool { + self.data.is_empty() + } + + pub fn data(&self) -> &'a [u8] { + self.data + } + + pub fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> { + let end = off.checked_add(len)?; + self.data.get(off..end) + } + + pub fn u8(&self, off: usize) -> Option { + self.data.get(off).copied() + } + + fn arr(&self, off: usize) -> Option<[u8; N]> { + self.slice(off, N)?.try_into().ok() + } + + pub fn u16_le(&self, off: usize) -> Option { + self.arr(off).map(u16::from_le_bytes) + } + + pub fn u32_le(&self, off: usize) -> Option { + self.arr(off).map(u32::from_le_bytes) + } + + pub fn u64_le(&self, off: usize) -> Option { + self.arr(off).map(u64::from_le_bytes) + } + + pub fn u16_be(&self, off: usize) -> Option { + self.arr(off).map(u16::from_be_bytes) + } + + pub fn u32_be(&self, off: usize) -> Option { + self.arr(off).map(u32::from_be_bytes) + } + + pub fn u64_be(&self, off: usize) -> Option { + self.arr(off).map(u64::from_be_bytes) + } + + /// A NUL-terminated string starting at `off`, at most `max` bytes, lossily decoded. + pub fn cstr(&self, off: usize, max: usize) -> Option { + let rest = self.data.get(off..)?; + let rest = rest.get(..max.min(rest.len()))?; + let end = rest.iter().position(|&b| b == 0).unwrap_or(rest.len()); + Some(String::from_utf8_lossy(rest.get(..end)?).into_owned()) + } + + /// Unsigned LEB128 at `off`: (value, bytes consumed). At most 10 bytes. + pub fn uleb128(&self, off: usize) -> Option<(u64, usize)> { + let mut result = 0u64; + for i in 0..10usize { + let b = self.u8(off.checked_add(i)?)?; + result |= u64::from(b & 0x7f).checked_shl(7 * i as u32)?; + if b & 0x80 == 0 { + return Some((result, i + 1)); + } + } + None + } +} From feea4e316df5c0a2ce6466f409a96bc58bde0bae Mon Sep 17 00:00:00 2001 From: BFlat Date: Sun, 15 Nov 2026 07:55:30 -0500 Subject: [PATCH 06/13] Import binary plist parser changes from Craft Anything 15de3661 --- crates/plist/src/binary.rs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/crates/plist/src/binary.rs b/crates/plist/src/binary.rs index 21ac84a86..9b792410a 100644 --- a/crates/plist/src/binary.rs +++ b/crates/plist/src/binary.rs @@ -102,13 +102,15 @@ pub fn parse_binary(data: &[u8]) -> Result { for i in 0..num { let o = read_be(&r, table + i * off_size, off_size).ok_or_else(|| FormatError::Truncated("offset table".into()))?; let o = usize::try_from(o).map_err(|_| FormatError::Malformed("object offset".into()))?; - if o >= table { + if o < 8 || o >= table { return Err(FormatError::Malformed(format!("object {i} lies outside the object area"))); } offsets.push(o); } let top = usize::try_from(top).map_err(|_| FormatError::Malformed("top object".into()))?; - let mut b = Bin { r, offsets, ref_size, nodes: 0 }; + // Object payloads and references must not borrow bytes from the offset table or trailer. + let objects = data.get(..table).ok_or_else(|| FormatError::Truncated("object area".into()))?; + let mut b = Bin { r: Reader::new(objects), offsets, ref_size, nodes: 0 }; let mut stack = Vec::new(); b.object(top, &mut stack) } @@ -127,7 +129,10 @@ impl Bin<'_> { if m & 0xf0 != 0x10 { return Err(FormatError::Malformed("bad extended length marker".into())); } - let n = 1usize << (m & 0x0f).min(3); + if m & 0x0f > 3 { + return Err(FormatError::Malformed("extended length width exceeds 64 bits".into())); + } + let n = 1usize << (m & 0x0f); let v = read_be(&self.r, at + 2, n).ok_or_else(|| FormatError::Truncated("length".into()))?; let v = usize::try_from(v).map_err(|_| FormatError::Malformed("length".into()))?; Ok((v, at + 2 + n)) @@ -161,7 +166,10 @@ impl Bin<'_> { _ => Value::Null, }, 0x1 => { - let n = 1usize << lo.min(4); + if lo > 4 { + return Err(FormatError::Malformed("integer width exceeds 128 bits".into())); + } + let n = 1usize << lo; let bytes = self.r.slice(at + 1, n).ok_or_else(|| FormatError::Truncated("integer".into()))?; let v = match n { 8 => i128::from(i64::from_be_bytes(bytes.try_into().map_err(|_| FormatError::Truncated("integer".into()))?)), @@ -197,6 +205,9 @@ impl Bin<'_> { Value::String(String::from_utf16_lossy(&units)) } 0x8 => { + if lo > 7 { + return Err(FormatError::Malformed("uid width exceeds 64 bits".into())); + } let n = usize::from(lo) + 1; Value::Uid(read_be(&self.r, at + 1, n).ok_or_else(|| FormatError::Truncated("uid".into()))?) } From d307449ee4c4ad7e09ceb2b8fafa1c3e3f66e169 Mon Sep 17 00:00:00 2001 From: RRFZ <247457381+Plastic-time@users.noreply.github.com> Date: Sun, 15 Nov 2026 07:55:30 -0500 Subject: [PATCH 07/13] Import binary plist parser changes from Craft Anything 0a8cc088 --- crates/plist/src/binary.rs | 56 +++++++++++++++++++++++++++++++++++--- 1 file changed, 52 insertions(+), 4 deletions(-) diff --git a/crates/plist/src/binary.rs b/crates/plist/src/binary.rs index 9b792410a..4fb85fd93 100644 --- a/crates/plist/src/binary.rs +++ b/crates/plist/src/binary.rs @@ -68,10 +68,17 @@ struct Bin<'a> { offsets: Vec, ref_size: usize, nodes: usize, + /// Data and text bytes still allowed to be copied out. + bytes_left: usize, } /// Parse a `bplist00` binary property list. pub fn parse_binary(data: &[u8]) -> Result { + parse_binary_within(data, MAX_EXPANDED_BYTES.max(data.len().saturating_mul(3))) +} + +/// Parse a binary property list, producing at most `byte_budget` bytes of data and decoded text. +fn parse_binary_within(data: &[u8], byte_budget: usize) -> Result { if !data.starts_with(b"bplist") { return Err(FormatError::Malformed("not a binary plist".into())); } @@ -110,7 +117,7 @@ pub fn parse_binary(data: &[u8]) -> Result { let top = usize::try_from(top).map_err(|_| FormatError::Malformed("top object".into()))?; // Object payloads and references must not borrow bytes from the offset table or trailer. let objects = data.get(..table).ok_or_else(|| FormatError::Truncated("object area".into()))?; - let mut b = Bin { r: Reader::new(objects), offsets, ref_size, nodes: 0 }; + let mut b = Bin { r: Reader::new(objects), offsets, ref_size, nodes: 0, bytes_left: byte_budget }; let mut stack = Vec::new(); b.object(top, &mut stack) } @@ -120,6 +127,21 @@ fn read_be(r: &Reader<'_>, off: usize, n: usize) -> Option { Some(s.iter().fold(0u64, |acc, &b| (acc << 8) | u64::from(b))) } +/// UTF-8 size of `String::from_utf8_lossy(bytes)`: each damaged sequence becomes a U+FFFD. +fn lossy_utf8_len(bytes: &[u8]) -> usize { + bytes.utf8_chunks().fold(0usize, |n, c| { + let replacement = if c.invalid().is_empty() { 0 } else { char::REPLACEMENT_CHARACTER.len_utf8() }; + n.saturating_add(c.valid().len()).saturating_add(replacement) + }) +} + +/// UTF-8 size of `String::from_utf16_lossy` over big-endian code units: a lone surrogate becomes +/// a U+FFFD. +fn lossy_utf16_len(bytes: &[u8]) -> usize { + let units = bytes.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)); + char::decode_utf16(units).fold(0usize, |n, c| n.saturating_add(c.map_or(char::REPLACEMENT_CHARACTER.len_utf8(), char::len_utf8))) +} + impl Bin<'_> { fn count(&self, at: usize, low: u8) -> Result<(usize, usize), FormatError> { if low != 0xf { @@ -144,6 +166,22 @@ impl Bin<'_> { usize::try_from(v).map_err(|_| FormatError::Malformed("reference".into())) } + /// Refuse a container whose `children` would pass MAX_NODES, before space is reserved for them. + fn room_for_nodes(&self, children: usize) -> Result<(), FormatError> { + if children > MAX_NODES.saturating_sub(self.nodes) { + return Err(FormatError::TooLarge(format!("more than {MAX_NODES} plist nodes"))); + } + Ok(()) + } + + /// Spend `n` bytes of the data and text budget before copying them out. + fn spend(&mut self, n: usize) -> Result<(), FormatError> { + self.bytes_left = + self.bytes_left.checked_sub(n).ok_or_else(|| FormatError::TooLarge("repeated data and text expand past the plist byte budget".into()))?; + Ok(()) + } + + /// Read object `idx`. `stack` holds the containers on the current path, so a cycle is refused. fn object(&mut self, idx: usize, stack: &mut Vec) -> Result { self.nodes += 1; if self.nodes > MAX_NODES { @@ -189,11 +227,15 @@ impl Bin<'_> { 0x3 => Value::Date(DateValue::Seconds(self.r.u64_be(at + 1).map(f64::from_bits).ok_or_else(|| FormatError::Truncated("date".into()))?)), 0x4 => { let (n, s) = self.count(at, lo)?; - Value::Data(self.r.slice(s, n).ok_or_else(|| FormatError::Truncated("data".into()))?.to_vec()) + let bytes = self.r.slice(s, n).ok_or_else(|| FormatError::Truncated("data".into()))?; + self.spend(bytes.len())?; + Value::Data(bytes.to_vec()) } 0x5 => { let (n, s) = self.count(at, lo)?; - Value::String(String::from_utf8_lossy(self.r.slice(s, n).ok_or_else(|| FormatError::Truncated("string".into()))?).into_owned()) + let bytes = self.r.slice(s, n).ok_or_else(|| FormatError::Truncated("string".into()))?; + self.spend(lossy_utf8_len(bytes))?; + Value::String(String::from_utf8_lossy(bytes).into_owned()) } 0x6 => { let (n, s) = self.count(at, lo)?; @@ -201,6 +243,7 @@ impl Bin<'_> { .r .slice(s, n.checked_mul(2).ok_or_else(|| FormatError::Malformed("string".into()))?) .ok_or_else(|| FormatError::Truncated("string".into()))?; + self.spend(lossy_utf16_len(bytes))?; let units: Vec = bytes.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)).collect(); Value::String(String::from_utf16_lossy(&units)) } @@ -213,9 +256,13 @@ impl Bin<'_> { } 0xa | 0xc => { let (n, s) = self.count(at, lo)?; - if n > self.offsets.len().saturating_mul(4).max(16) || s.saturating_add(n.saturating_mul(self.ref_size)) > self.r.len() { + // Writers store equal values once, so an array may name one object many times: + // only its references have to fit in the file. MAX_NODES and the byte budget bound + // the expansion. + if s.saturating_add(n.saturating_mul(self.ref_size)) > self.r.len() { return Err(FormatError::Malformed("array larger than the file".into())); } + self.room_for_nodes(n)?; stack.push(idx); let mut out = Vec::with_capacity(n); for i in 0..n { @@ -230,6 +277,7 @@ impl Bin<'_> { if s.saturating_add(n.saturating_mul(self.ref_size).saturating_mul(2)) > self.r.len() { return Err(FormatError::Malformed("dictionary larger than the file".into())); } + self.room_for_nodes(n.saturating_mul(2))?; stack.push(idx); let mut out = Vec::with_capacity(n); for i in 0..n { From e20c7c1a6e4dcf2c430da3423f04aad30a4b24a2 Mon Sep 17 00:00:00 2001 From: Afloat Date: Sun, 15 Nov 2026 07:55:30 -0500 Subject: [PATCH 08/13] Import binary plist parser changes from Craft Anything 0c386e8a --- crates/plist/src/binary.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/plist/src/binary.rs b/crates/plist/src/binary.rs index 4fb85fd93..26129ad83 100644 --- a/crates/plist/src/binary.rs +++ b/crates/plist/src/binary.rs @@ -82,6 +82,9 @@ fn parse_binary_within(data: &[u8], byte_budget: usize) -> Result { 0x0 => Value::Null, 0x8 => Value::Bool(false), 0x9 => Value::Bool(true), - _ => Value::Null, + _ => return Err(FormatError::Malformed(format!("unknown simple plist object {m:#04x}"))), }, 0x1 => { if lo > 4 { @@ -224,7 +227,7 @@ impl Bin<'_> { }; Value::Real(v.ok_or_else(|| FormatError::Truncated("real".into()))?) } - 0x3 => Value::Date(DateValue::Seconds(self.r.u64_be(at + 1).map(f64::from_bits).ok_or_else(|| FormatError::Truncated("date".into()))?)), + 0x3 if lo == 3 => Value::Date(DateValue::Seconds(self.r.u64_be(at + 1).map(f64::from_bits).ok_or_else(|| FormatError::Truncated("date".into()))?)), 0x4 => { let (n, s) = self.count(at, lo)?; let bytes = self.r.slice(s, n).ok_or_else(|| FormatError::Truncated("data".into()))?; @@ -285,7 +288,7 @@ impl Bin<'_> { let v = self.reference(s, i + n)?; let key = match self.object(k, stack)? { Value::String(s) => s, - other => format!("{:?}", other.to_json()), + _ => return Err(FormatError::Unsupported("non-string dictionary keys cannot be represented in this plist view".into())), }; out.push((key, self.object(v, stack)?)); } From b2f888d788042c6df64ffa1aa9f8ddf537d48864 Mon Sep 17 00:00:00 2001 From: BFlat Date: Sun, 15 Nov 2026 07:55:30 -0500 Subject: [PATCH 09/13] Import plist regression from Craft Anything 15de3661 --- crates/plist/tests/plist_marker_widths.rs | 47 +++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 crates/plist/tests/plist_marker_widths.rs diff --git a/crates/plist/tests/plist_marker_widths.rs b/crates/plist/tests/plist_marker_widths.rs new file mode 100644 index 000000000..5873371e7 --- /dev/null +++ b/crates/plist/tests/plist_marker_widths.rs @@ -0,0 +1,47 @@ +use craft_plist::{Value, parse_binary}; + +fn single_object(object: &[u8]) -> Vec { + let mut data = b"bplist00".to_vec(); + data.extend_from_slice(object); + let table = data.len() as u64; + data.push(8); + data.extend_from_slice(&[0, 0, 0, 0, 0, 0, 1, 1]); + data.extend_from_slice(&1u64.to_be_bytes()); + data.extend_from_slice(&0u64.to_be_bytes()); + data.extend_from_slice(&table.to_be_bytes()); + data +} + +#[test] +fn unsupported_integer_widths_are_not_clamped() { + for marker in 0x15..=0x1f { + let mut object = vec![marker]; + object.extend_from_slice(&[0; 16]); + assert!(parse_binary(&single_object(&object)).is_err(), "accepted {marker:#x}"); + } +} + +#[test] +fn extended_lengths_and_uids_do_not_lose_high_bytes() { + let mut length = vec![0x4f, 0x14]; + length.extend_from_slice(&[0; 16]); + assert!(parse_binary(&single_object(&length)).is_err()); + for marker in 0x88..=0x8f { + let mut object = vec![marker, 1]; + object.resize(usize::from(marker & 15) + 2, 0); + assert!(parse_binary(&single_object(&object)).is_err(), "accepted {marker:#x}"); + } +} + +#[test] +fn supported_maximum_widths_keep_their_values() { + let mut integer = vec![0x14]; + integer.extend_from_slice(&i128::MAX.to_be_bytes()); + assert!(matches!(parse_binary(&single_object(&integer)), Ok(Value::Integer(i)) if i == i128::MAX)); + let mut uid = vec![0x87]; + uid.extend_from_slice(&u64::MAX.to_be_bytes()); + assert!(matches!(parse_binary(&single_object(&uid)), Ok(Value::Uid(i)) if i == u64::MAX)); + let mut empty = vec![0x4f, 0x13]; + empty.extend_from_slice(&0u64.to_be_bytes()); + assert!(matches!(parse_binary(&single_object(&empty)), Ok(Value::Data(d)) if d.is_empty())); +} From 0bc19896102774e5ffe12ed012fc6cb036e6b9d3 Mon Sep 17 00:00:00 2001 From: BFlat Date: Sun, 15 Nov 2026 07:55:30 -0500 Subject: [PATCH 10/13] Import plist regression from Craft Anything 15de3661 --- crates/plist/tests/plist_object_bounds.rs | 34 +++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 crates/plist/tests/plist_object_bounds.rs diff --git a/crates/plist/tests/plist_object_bounds.rs b/crates/plist/tests/plist_object_bounds.rs new file mode 100644 index 000000000..52d30cb80 --- /dev/null +++ b/crates/plist/tests/plist_object_bounds.rs @@ -0,0 +1,34 @@ +use craft_plist::{Value, parse_binary}; +use craft_anything_testkit::apple as fx; + +fn single_object(object: &[u8], offset: u8) -> Vec { + let mut data = b"bplist00".to_vec(); + data.extend_from_slice(object); + let table = data.len() as u64; + data.push(offset); + data.extend_from_slice(&[0, 0, 0, 0, 0, 0, 1, 1]); + data.extend_from_slice(&1u64.to_be_bytes()); + data.extend_from_slice(&0u64.to_be_bytes()); + data.extend_from_slice(&table.to_be_bytes()); + data +} + +#[test] +fn binary_values_cannot_consume_the_offset_table_or_trailer() { + for object in [&[0x54, b'x'][..], &[0x43, 0x42], &[0x13], &[0x87], &[0x62, 0, b'x']] { + assert!(parse_binary(&single_object(object, 8)).is_err(), "accepted object {object:02x?}"); + } +} + +#[test] +fn binary_offsets_cannot_point_inside_the_file_header() { + assert!(parse_binary(&single_object(&[0x00], 0)).is_err()); + assert!(matches!(parse_binary(&single_object(&[0x00], 8)), Ok(Value::Null))); +} + +#[test] +fn objects_ending_at_the_table_boundary_are_valid() { + assert!(matches!(parse_binary(&single_object(&[0x51, b'x'], 8)), Ok(Value::String(s)) if s == "x")); + let sample = fx::sample_plist(); + assert_eq!(parse_binary(&fx::to_bplist(&sample)).unwrap().get("Count").and_then(Value::as_int), Some(-42)); +} From 1ec7ab92b5a316d41642c388561fc5c2a2ad8492 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 07:57:29 -0500 Subject: [PATCH 11/13] Expose bounded cross-platform binary plist reader with explicit limits --- ATTRIBUTION.md | 4 + Cargo.lock | 7 ++ Cargo.toml | 1 + crates/plist/Cargo.toml | 14 ++++ crates/plist/README.md | 11 +++ crates/plist/src/binary.rs | 90 +++++++++++++++-------- crates/plist/src/bytes.rs | 45 ------------ crates/plist/src/lib.rs | 33 +++++++++ crates/plist/tests/limits.rs | 57 ++++++++++++++ crates/plist/tests/plist_object_bounds.rs | 3 - 10 files changed, 188 insertions(+), 77 deletions(-) create mode 100644 crates/plist/Cargo.toml create mode 100644 crates/plist/README.md create mode 100644 crates/plist/src/lib.rs create mode 100644 crates/plist/tests/limits.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 77d3578cb..c087ecda1 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -95,3 +95,7 @@ and the exact transfer revision are recorded in each vendored crate's SOURCE.jso | `crates/raw/docs/raf-corpus.sha256` (hashes only; the files are not bundled) | The photographers who contributed each file to raw.pixls.us | [raw.pixls.us](https://raw.pixls.us/) | CC0-1.0 | | `crates/drawingml/src/preset_text.txt` | DeckCraft contributors (Nikita Rakitin); generated by `crates/drawingml/tests/fixtures/make_preset_guides.py` from the guide formulas of ECMA-376 Part 1 `presetShapeDefinitions.xml` | [storytold/deckcraft#650](https://github.com/storytold/deckcraft/pull/650) | MIT OR Apache-2.0 (the formulas are the format's definition in ECMA-376) | | `crates/drawingml/tests/fixtures/preset_table.txt` | DeckCraft contributors (Nikita Rakitin); generated by `crates/drawingml/tests/fixtures/make_preset_table.py` from ECMA-376 Part 1 `presetShapeDefinitions.xml` | [storytold/deckcraft#650](https://github.com/storytold/deckcraft/pull/650) | MIT OR Apache-2.0 (the formulas are the format's definition in ECMA-376) | + +## Binary Apple property lists + +`crates/plist` is extracted from `storytold/craft-anything` (`crates/formats/src/plist.rs` and checked byte reads), at source main `88d1d9cac852aec1c7fd97886db451e005e49d2a`. MIT OR Apache-2.0; source license texts are retained in the crate. Primary import Git authors preserve Brandon Thomas, BFlat, RRFZ and Afloat. Regression imports preserve BFlat. XML, JSON projection, calendar formatting and app policy were not imported into the public API. diff --git a/Cargo.lock b/Cargo.lock index 4936ffe2b..529e1a2e0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2357,6 +2357,13 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-plist" +version = "0.1.0" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-platform" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 77b20da79..c5a585d7b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,7 @@ craft-proto = { path = "crates/proto" } acadrust = "=0.6.6" log = "0.4" # internal: add each crate here as `craft- = { path = "crates/" }` +craft-plist = { path = "crates/plist" } craft-platform = { path = "crates/platform" } craft-aep = { path = "crates/aep" } craft-affinity = { path = "crates/affinity" } diff --git a/crates/plist/Cargo.toml b/crates/plist/Cargo.toml new file mode 100644 index 000000000..7ae95aae0 --- /dev/null +++ b/crates/plist/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "craft-plist" +description = "Bounded cross-platform binary Apple property-list reader" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +thiserror.workspace = true diff --git a/crates/plist/README.md b/crates/plist/README.md new file mode 100644 index 000000000..dc5c52007 --- /dev/null +++ b/crates/plist/README.md @@ -0,0 +1,11 @@ +# craft-plist + +A cross-platform bounded binary (`bplist00`) reader, extracted from Craft Anything's existing implementation and hardening history. Typed dictionaries retain order and duplicate keys; `get` returns the first match. Strings retain the source reader's lossy decoding policy. Shared references expand under node and decoded-byte budgets, and cycles are rejected. + +`parse_binary_with_limits` accepts explicit input, object, expanded-node, nesting and decoded-byte limits. Recursion always has a hard ceiling of 256 even if a caller supplies a larger depth. Counts are checked before container reservation; allocations can return a resource error. Limits are per parse, not a promise of a precise process RSS cap. + +This first PR contains reading only. XML parsing/writing and keyed-archive interpretation are not implemented. JSON projection, date formatting, OS file access and preference/locale selection are not part of this crate. Existing updater/Photo streaming `plist` users remain unchanged. + +Initial consumers: PhotoCraft's AppleLanguages binary-reader path; later Craft Anything binary parsing and LightCraft XML presets (after XML support/parity). Photo must retain its 4 MiB input policy and first-language selection. + +Source: `storytold/craft-anything` at `88d1d9cac852aec1c7fd97886db451e005e49d2a`, `crates/formats/src/plist.rs` and checked byte reader. Source license files retained. Imported changes retain Brandon Thomas, BFlat, RRFZ and Afloat as primary Git authors; imported regression tests are BFlat's. No external specification implementation copied. diff --git a/crates/plist/src/binary.rs b/crates/plist/src/binary.rs index 26129ad83..3e65f1a9e 100644 --- a/crates/plist/src/binary.rs +++ b/crates/plist/src/binary.rs @@ -1,8 +1,4 @@ -use crate::{FormatError, bytes::Reader}; - -pub const MAX_DEPTH: usize = 256; -pub const MAX_NODES: usize = 2_000_000; -pub const MAX_EXPANDED_BYTES: usize = 64 << 20; +use crate::{FormatError, Limits, bytes::Reader}; #[derive(Debug, Clone, PartialEq)] pub enum Value { @@ -61,7 +57,6 @@ impl Value { _ => None, } } - } struct Bin<'a> { r: Reader<'a>, @@ -70,19 +65,23 @@ struct Bin<'a> { nodes: usize, /// Data and text bytes still allowed to be copied out. bytes_left: usize, + limits: Limits, } /// Parse a `bplist00` binary property list. pub fn parse_binary(data: &[u8]) -> Result { - parse_binary_within(data, MAX_EXPANDED_BYTES.max(data.len().saturating_mul(3))) + parse_binary_with_limits(data, Limits::default()) } -/// Parse a binary property list, producing at most `byte_budget` bytes of data and decoded text. -fn parse_binary_within(data: &[u8], byte_budget: usize) -> Result { +/// Parse a binary property list, with caller-selected input, object, expansion and nesting limits. +pub fn parse_binary_with_limits(data: &[u8], limits: Limits) -> Result { + if data.len() > limits.max_input_bytes { + return Err(FormatError::TooLarge("input bytes".into())); + } if !data.starts_with(b"bplist") { return Err(FormatError::Malformed("not a binary plist".into())); } - if !data.starts_with(b"bplist0") { + if !data.starts_with(b"bplist00") { return Err(FormatError::Unsupported("unknown binary plist version".into())); } let len = data.len(); @@ -104,11 +103,14 @@ fn parse_binary_within(data: &[u8], byte_budget: usize) -> Result len { return Err(FormatError::Malformed(format!("{num} objects in a {len}-byte file"))); } + if num > limits.max_objects { + return Err(FormatError::TooLarge("object count".into())); + } let need = num.checked_mul(off_size).and_then(|n| n.checked_add(table)).ok_or_else(|| FormatError::Malformed("offset table".into()))?; if need > t || table < 8 { return Err(FormatError::Truncated("offset table runs past the trailer".into())); } - let mut offsets = Vec::with_capacity(num); + let mut offsets = reserved(num)?; for i in 0..num { let o = read_be(&r, table + i * off_size, off_size).ok_or_else(|| FormatError::Truncated("offset table".into()))?; let o = usize::try_from(o).map_err(|_| FormatError::Malformed("object offset".into()))?; @@ -120,8 +122,8 @@ fn parse_binary_within(data: &[u8], byte_budget: usize) -> Result { usize::try_from(v).map_err(|_| FormatError::Malformed("reference".into())) } - /// Refuse a container whose `children` would pass MAX_NODES, before space is reserved for them. + /// Refuse a container whose `children` would pass the node limit, before space is reserved for them. fn room_for_nodes(&self, children: usize) -> Result<(), FormatError> { - if children > MAX_NODES.saturating_sub(self.nodes) { - return Err(FormatError::TooLarge(format!("more than {MAX_NODES} plist nodes"))); + if children > self.limits.max_nodes.saturating_sub(self.nodes) { + return Err(FormatError::TooLarge("expanded node count".into())); } Ok(()) } @@ -187,10 +189,10 @@ impl Bin<'_> { /// Read object `idx`. `stack` holds the containers on the current path, so a cycle is refused. fn object(&mut self, idx: usize, stack: &mut Vec) -> Result { self.nodes += 1; - if self.nodes > MAX_NODES { - return Err(FormatError::TooLarge(format!("more than {MAX_NODES} plist nodes"))); + if self.nodes > self.limits.max_nodes { + return Err(FormatError::TooLarge("expanded node count".into())); } - if stack.len() >= MAX_DEPTH { + if stack.len() >= self.limits.max_depth.min(256) { return Err(FormatError::Malformed("nesting too deep".into())); } if stack.contains(&idx) { @@ -227,18 +229,32 @@ impl Bin<'_> { }; Value::Real(v.ok_or_else(|| FormatError::Truncated("real".into()))?) } - 0x3 if lo == 3 => Value::Date(DateValue::Seconds(self.r.u64_be(at + 1).map(f64::from_bits).ok_or_else(|| FormatError::Truncated("date".into()))?)), + 0x3 if lo == 3 => { + Value::Date(DateValue::Seconds(self.r.u64_be(at + 1).map(f64::from_bits).ok_or_else(|| FormatError::Truncated("date".into()))?)) + } 0x4 => { let (n, s) = self.count(at, lo)?; let bytes = self.r.slice(s, n).ok_or_else(|| FormatError::Truncated("data".into()))?; self.spend(bytes.len())?; - Value::Data(bytes.to_vec()) + { + let mut out = reserved(bytes.len())?; + out.extend_from_slice(bytes); + Value::Data(out) + } } 0x5 => { let (n, s) = self.count(at, lo)?; let bytes = self.r.slice(s, n).ok_or_else(|| FormatError::Truncated("string".into()))?; - self.spend(lossy_utf8_len(bytes))?; - Value::String(String::from_utf8_lossy(bytes).into_owned()) + let size = lossy_utf8_len(bytes); + self.spend(size)?; + let mut out = reserved_string(size)?; + for chunk in bytes.utf8_chunks() { + out.push_str(chunk.valid()); + if !chunk.invalid().is_empty() { + out.push(char::REPLACEMENT_CHARACTER); + } + } + Value::String(out) } 0x6 => { let (n, s) = self.count(at, lo)?; @@ -246,9 +262,14 @@ impl Bin<'_> { .r .slice(s, n.checked_mul(2).ok_or_else(|| FormatError::Malformed("string".into()))?) .ok_or_else(|| FormatError::Truncated("string".into()))?; - self.spend(lossy_utf16_len(bytes))?; - let units: Vec = bytes.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)).collect(); - Value::String(String::from_utf16_lossy(&units)) + let size = lossy_utf16_len(bytes); + self.spend(size)?; + let mut out = reserved_string(size)?; + let units = bytes.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)); + for ch in char::decode_utf16(units) { + out.push(ch.unwrap_or(char::REPLACEMENT_CHARACTER)); + } + Value::String(out) } 0x8 => { if lo > 7 { @@ -260,14 +281,14 @@ impl Bin<'_> { 0xa | 0xc => { let (n, s) = self.count(at, lo)?; // Writers store equal values once, so an array may name one object many times: - // only its references have to fit in the file. MAX_NODES and the byte budget bound + // only its references have to fit in the file. the node limit and the byte budget bound // the expansion. if s.saturating_add(n.saturating_mul(self.ref_size)) > self.r.len() { return Err(FormatError::Malformed("array larger than the file".into())); } self.room_for_nodes(n)?; stack.push(idx); - let mut out = Vec::with_capacity(n); + let mut out = reserved(n)?; for i in 0..n { let child = self.reference(s, i)?; out.push(self.object(child, stack)?); @@ -282,7 +303,7 @@ impl Bin<'_> { } self.room_for_nodes(n.saturating_mul(2))?; stack.push(idx); - let mut out = Vec::with_capacity(n); + let mut out = reserved(n)?; for i in 0..n { let k = self.reference(s, i)?; let v = self.reference(s, i + n)?; @@ -301,3 +322,14 @@ impl Bin<'_> { } } +fn reserved(n: usize) -> Result, FormatError> { + let mut v = Vec::new(); + v.try_reserve_exact(n).map_err(|_| FormatError::TooLarge("allocation".into()))?; + Ok(v) +} + +fn reserved_string(n: usize) -> Result { + let mut s = String::new(); + s.try_reserve_exact(n).map_err(|_| FormatError::TooLarge("string allocation".into()))?; + Ok(s) +} diff --git a/crates/plist/src/bytes.rs b/crates/plist/src/bytes.rs index b9de989c3..bdfecc668 100644 --- a/crates/plist/src/bytes.rs +++ b/crates/plist/src/bytes.rs @@ -14,14 +14,6 @@ impl<'a> Reader<'a> { self.data.len() } - pub fn is_empty(&self) -> bool { - self.data.is_empty() - } - - pub fn data(&self) -> &'a [u8] { - self.data - } - pub fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> { let end = off.checked_add(len)?; self.data.get(off..end) @@ -35,22 +27,6 @@ impl<'a> Reader<'a> { self.slice(off, N)?.try_into().ok() } - pub fn u16_le(&self, off: usize) -> Option { - self.arr(off).map(u16::from_le_bytes) - } - - pub fn u32_le(&self, off: usize) -> Option { - self.arr(off).map(u32::from_le_bytes) - } - - pub fn u64_le(&self, off: usize) -> Option { - self.arr(off).map(u64::from_le_bytes) - } - - pub fn u16_be(&self, off: usize) -> Option { - self.arr(off).map(u16::from_be_bytes) - } - pub fn u32_be(&self, off: usize) -> Option { self.arr(off).map(u32::from_be_bytes) } @@ -58,25 +34,4 @@ impl<'a> Reader<'a> { pub fn u64_be(&self, off: usize) -> Option { self.arr(off).map(u64::from_be_bytes) } - - /// A NUL-terminated string starting at `off`, at most `max` bytes, lossily decoded. - pub fn cstr(&self, off: usize, max: usize) -> Option { - let rest = self.data.get(off..)?; - let rest = rest.get(..max.min(rest.len()))?; - let end = rest.iter().position(|&b| b == 0).unwrap_or(rest.len()); - Some(String::from_utf8_lossy(rest.get(..end)?).into_owned()) - } - - /// Unsigned LEB128 at `off`: (value, bytes consumed). At most 10 bytes. - pub fn uleb128(&self, off: usize) -> Option<(u64, usize)> { - let mut result = 0u64; - for i in 0..10usize { - let b = self.u8(off.checked_add(i)?)?; - result |= u64::from(b & 0x7f).checked_shl(7 * i as u32)?; - if b & 0x80 == 0 { - return Some((result, i + 1)); - } - } - None - } } diff --git a/crates/plist/src/lib.rs b/crates/plist/src/lib.rs new file mode 100644 index 000000000..3e4c6cd85 --- /dev/null +++ b/crates/plist/src/lib.rs @@ -0,0 +1,33 @@ +//! Bounded binary Apple property lists, independent of operating-system preferences. +//! XML and writing are intentionally not implemented in this first extraction. +//! File discovery, locale selection, bundle validation and application policy stay in callers. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod binary; +mod bytes; +pub use binary::{DateValue, Value, parse_binary, parse_binary_with_limits}; + +/// Caller-selected resource limits. Zero values refuse the corresponding resource. +#[derive(Clone, Copy, Debug)] +pub struct Limits { + pub max_input_bytes: usize, + pub max_objects: usize, + pub max_nodes: usize, + pub max_depth: usize, + pub max_expanded_bytes: usize, +} +impl Default for Limits { + fn default() -> Self { + Self { max_input_bytes: 16 << 20, max_objects: 100_000, max_nodes: 100_000, max_depth: 64, max_expanded_bytes: 64 << 20 } + } +} +#[derive(Debug, thiserror::Error)] +pub enum FormatError { + #[error("malformed property list: {0}")] + Malformed(String), + #[error("truncated property list: {0}")] + Truncated(String), + #[error("unsupported property list: {0}")] + Unsupported(String), + #[error("property list resource limit: {0}")] + TooLarge(String), +} diff --git a/crates/plist/tests/limits.rs b/crates/plist/tests/limits.rs new file mode 100644 index 000000000..0c4fefd7c --- /dev/null +++ b/crates/plist/tests/limits.rs @@ -0,0 +1,57 @@ +use craft_plist::{Limits, Value, parse_binary, parse_binary_with_limits}; +fn plist(objects: &[&[u8]]) -> Vec { + let mut b = b"bplist00".to_vec(); + let mut offsets = Vec::new(); + for obj in objects { + offsets.push(b.len() as u8); + b.extend_from_slice(obj); + } + let table = b.len() as u64; + b.extend_from_slice(&offsets); + b.extend_from_slice(&[0, 0, 0, 0, 0, 0, 1, 1]); + b.extend_from_slice(&(objects.len() as u64).to_be_bytes()); + b.extend_from_slice(&0u64.to_be_bytes()); + b.extend_from_slice(&table.to_be_bytes()); + b +} +#[test] +fn languages_and_every_truncation() { + let b = plist(&[&[0xd1, 1, 2], b"\x5eAppleLanguages", &[0xa1, 3], b"\x55ja-JP"]); + let p = parse_binary(&b).unwrap(); + assert_eq!(p.get("AppleLanguages").unwrap().as_array().unwrap()[0].as_str(), Some("ja-JP")); + for n in 0..b.len() { + assert!(parse_binary(&b[..n]).is_err(), "prefix {n}"); + } +} +#[test] +fn cycles_and_repeated_references() { + assert!(parse_binary(&plist(&[&[0xa1, 0]])).is_err()); + let b = plist(&[&[0xa3, 1, 1, 1], b"\x51x"]); + assert_eq!(parse_binary(&b).unwrap(), Value::Array(vec![Value::String("x".into()); 3])); + assert!(parse_binary_with_limits(&b, Limits { max_nodes: 3, ..Limits::default() }).is_err()); + assert!(parse_binary_with_limits(&b, Limits { max_expanded_bytes: 2, ..Limits::default() }).is_err()); +} +#[test] +fn explicit_limits_and_version() { + let b = plist(&[&[0xa1, 1], b"\x51x"]); + for l in [ + Limits { max_input_bytes: b.len() - 1, ..Limits::default() }, + Limits { max_objects: 1, ..Limits::default() }, + Limits { max_depth: 1, ..Limits::default() }, + Limits { max_nodes: 0, ..Limits::default() }, + ] { + assert!(parse_binary_with_limits(&b, l).is_err()); + } + let mut future = b; + future[7] = b'1'; + assert!(parse_binary(&future).is_err()); +} +#[test] +fn utf16_and_lossy_expansion_spend_budget() { + let b = plist(&[&[0x62, 0xd8, 0x3d, 0xde, 0x00]]); + assert_eq!(parse_binary(&b).unwrap().as_str(), Some("😀")); + assert!(parse_binary_with_limits(&b, Limits { max_expanded_bytes: 3, ..Limits::default() }).is_err()); + let bad = plist(&[&[0x51, 0xff]]); + assert_eq!(parse_binary(&bad).unwrap().as_str(), Some("�")); + assert!(parse_binary_with_limits(&bad, Limits { max_expanded_bytes: 2, ..Limits::default() }).is_err()); +} diff --git a/crates/plist/tests/plist_object_bounds.rs b/crates/plist/tests/plist_object_bounds.rs index 52d30cb80..d35fd91b1 100644 --- a/crates/plist/tests/plist_object_bounds.rs +++ b/crates/plist/tests/plist_object_bounds.rs @@ -1,5 +1,4 @@ use craft_plist::{Value, parse_binary}; -use craft_anything_testkit::apple as fx; fn single_object(object: &[u8], offset: u8) -> Vec { let mut data = b"bplist00".to_vec(); @@ -29,6 +28,4 @@ fn binary_offsets_cannot_point_inside_the_file_header() { #[test] fn objects_ending_at_the_table_boundary_are_valid() { assert!(matches!(parse_binary(&single_object(&[0x51, b'x'], 8)), Ok(Value::String(s)) if s == "x")); - let sample = fx::sample_plist(); - assert_eq!(parse_binary(&fx::to_bplist(&sample)).unwrap().get("Count").and_then(Value::as_int), Some(-42)); } From cc4fc29cdba60f70e3af3b5d975c60bd0085cb1b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 08:00:09 -0500 Subject: [PATCH 12/13] Add bounded selective plist array lookup for locale parity --- crates/plist/src/binary.rs | 62 ++++++++++++++++++++++++++++++++++-- crates/plist/src/lib.rs | 2 +- crates/plist/tests/limits.rs | 18 +++++++++++ 3 files changed, 78 insertions(+), 4 deletions(-) diff --git a/crates/plist/src/binary.rs b/crates/plist/src/binary.rs index 3e65f1a9e..3fe6aed92 100644 --- a/crates/plist/src/binary.rs +++ b/crates/plist/src/binary.rs @@ -75,6 +75,12 @@ pub fn parse_binary(data: &[u8]) -> Result { /// Parse a binary property list, with caller-selected input, object, expansion and nesting limits. pub fn parse_binary_with_limits(data: &[u8], limits: Limits) -> Result { + let (mut b, top) = reader(data, limits)?; + let mut stack = reserved(limits.max_depth.min(256))?; + b.object(top, &mut stack) +} + +fn reader(data: &[u8], limits: Limits) -> Result<(Bin<'_>, usize), FormatError> { if data.len() > limits.max_input_bytes { return Err(FormatError::TooLarge("input bytes".into())); } @@ -122,9 +128,8 @@ pub fn parse_binary_with_limits(data: &[u8], limits: Limits) -> Result, off: usize, n: usize) -> Option { @@ -333,3 +338,54 @@ fn reserved_string(n: usize) -> Result { s.try_reserve_exact(n).map_err(|_| FormatError::TooLarge("string allocation".into()))?; Ok(s) } + +/// Select the first string in one top-level dictionary array without expanding unrelated values. +/// First matching dictionary key wins. Missing/wrong-typed values return `None`; malformed +/// selected objects and resource exhaustion return errors. Unselected value graphs are not +/// validated. This permits preference readers to ignore unrelated future object kinds. +pub fn first_string_in_array(data: &[u8], key: &str, limits: Limits) -> Result, FormatError> { + let (mut b, top) = reader(data, limits)?; + let (kind, n, start) = b.header(top)?; + if kind != 0xd { + return Ok(None); + } + if n > limits.max_nodes { + return Err(FormatError::TooLarge("dictionary lookup entries".into())); + } + let bytes = n.checked_mul(2).and_then(|n| n.checked_mul(b.ref_size)).ok_or_else(|| FormatError::Malformed("dictionary references".into()))?; + b.r.slice(start, bytes).ok_or_else(|| FormatError::Truncated("dictionary references".into()))?; + for i in 0..n { + let k = b.reference(start, i)?; + if b.selected_string(k)?.as_deref() != Some(key) { + continue; + } + let value = b.reference(start, n + i)?; + let (kind, count, payload) = b.header(value)?; + if kind != 0xa || count == 0 { + return Ok(None); + } + let first = b.reference(payload, 0)?; + return b.selected_string(first); + } + Ok(None) +} +impl Bin<'_> { + fn header(&self, idx: usize) -> Result<(u8, usize, usize), FormatError> { + let at = *self.offsets.get(idx).ok_or_else(|| FormatError::Malformed("missing object".into()))?; + let marker = self.r.u8(at).ok_or_else(|| FormatError::Truncated("object marker".into()))?; + let kind = marker >> 4; + // Only containers and strings use an extended length. Unknown types are not traversed. + let (n, start) = if matches!(kind, 0x5 | 0x6 | 0xa | 0xd) { self.count(at, marker & 15)? } else { (usize::from(marker & 15), at + 1) }; + Ok((kind, n, start)) + } + fn selected_string(&mut self, idx: usize) -> Result, FormatError> { + let (kind, _, _) = self.header(idx)?; + if !matches!(kind, 0x5 | 0x6) { + return Ok(None); + } + match self.object(idx, &mut Vec::new())? { + Value::String(s) => Ok(Some(s)), + _ => Ok(None), + } + } +} diff --git a/crates/plist/src/lib.rs b/crates/plist/src/lib.rs index 3e4c6cd85..f3af79ddc 100644 --- a/crates/plist/src/lib.rs +++ b/crates/plist/src/lib.rs @@ -4,7 +4,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod binary; mod bytes; -pub use binary::{DateValue, Value, parse_binary, parse_binary_with_limits}; +pub use binary::{DateValue, Value, first_string_in_array, parse_binary, parse_binary_with_limits}; /// Caller-selected resource limits. Zero values refuse the corresponding resource. #[derive(Clone, Copy, Debug)] diff --git a/crates/plist/tests/limits.rs b/crates/plist/tests/limits.rs index 0c4fefd7c..dc1882698 100644 --- a/crates/plist/tests/limits.rs +++ b/crates/plist/tests/limits.rs @@ -55,3 +55,21 @@ fn utf16_and_lossy_expansion_spend_budget() { assert_eq!(parse_binary(&bad).unwrap().as_str(), Some("�")); assert!(parse_binary_with_limits(&bad, Limits { max_expanded_bytes: 2, ..Limits::default() }).is_err()); } + +#[test] +fn selective_lookup_ignores_unrelated_graphs_and_preserves_first_match() { + use craft_plist::first_string_in_array; + let b = plist(&[&[0xd2, 1, 2, 3, 4], b"\x55Other", b"\x5eAppleLanguages", &[0xaf], &[0xa2, 5, 6], b"\x55ja-JP", &[0xff]]); + assert!(parse_binary(&b).is_err()); + assert_eq!(first_string_in_array(&b, "AppleLanguages", Limits::default()).unwrap().as_deref(), Some("ja-JP")); + let duplicate = plist(&[&[0xd2, 1, 1, 2, 3], b"\x5eAppleLanguages", &[0xa1, 4], &[0xa1, 5], b"\x55zh-TW", b"\x55ko-KR"]); + assert_eq!(first_string_in_array(&duplicate, "AppleLanguages", Limits::default()).unwrap().as_deref(), Some("zh-TW")); + assert!(first_string_in_array(&b, "AppleLanguages", Limits { max_expanded_bytes: 1, ..Limits::default() }).is_err()); +} + +#[test] +fn selective_lookup_requires_an_array_not_a_set() { + use craft_plist::first_string_in_array; + let b = plist(&[&[0xd1, 1, 2], b"\x5eAppleLanguages", &[0xc1, 3], b"\x55ja-JP"]); + assert_eq!(first_string_in_array(&b, "AppleLanguages", Limits::default()).unwrap(), None); +} From 4cf2a6f4cb26bc0503191049edccf85d4d0b21a8 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 13:06:02 +0000 Subject: [PATCH 13/13] Inspect seekable archive entry budgets and overlaps --- crates/zip/src/lib.rs | 2 + crates/zip/src/seekable.rs | 75 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 crates/zip/src/seekable.rs diff --git a/crates/zip/src/lib.rs b/crates/zip/src/lib.rs index 73eb9840a..0a348dc1f 100644 --- a/crates/zip/src/lib.rs +++ b/crates/zip/src/lib.rs @@ -25,6 +25,7 @@ mod archive; mod guard; mod metadata_reader; pub mod preflight; +mod seekable; mod write; pub use archive::{Archive, Limits}; @@ -32,6 +33,7 @@ pub use guard::check_entry_count; #[cfg(any(test, feature = "test-support"))] pub use guard::zip64_entry_count_sample; pub use metadata_reader::{Indexing, MetadataReader}; +pub use seekable::{InspectError, inspect_seekable}; pub use write::{Compression, Writer}; /// The payload of a ZIP's first entry when it is a stored file named `mimetype` of at most 256 diff --git a/crates/zip/src/seekable.rs b/crates/zip/src/seekable.rs new file mode 100644 index 000000000..2750a0123 --- /dev/null +++ b/crates/zip/src/seekable.rs @@ -0,0 +1,75 @@ +//! Checks for an already indexed, seekable ZIP archive. + +use std::io::{Read, Seek}; + +/// Why an indexed seekable archive exceeded its caller's limits. +#[derive(Debug, thiserror::Error)] +pub enum InspectError { + #[error("the archive has {actual} entries, more than {limit}")] + TooManyEntries { actual: usize, limit: usize }, + #[error("declared entry sizes exceed {limit} bytes")] + DeclaredBytesExceeded { limit: u64 }, + #[error("ZIP entries overlap")] + OverlappingEntries, + #[error("ZIP index: {0}")] + Zip(#[from] zip::result::ZipError), +} + +/// Check every declared payload, including entries the caller may ignore, and reject overlapping +/// entry headers and compressed ranges. This is a post-index check; it does not replace a pre-index count guard or +/// bound bytes actually decompressed by a caller. +pub fn inspect_seekable(archive: &mut zip::ZipArchive, max_entries: usize, max_declared_bytes: u64) -> Result<(), InspectError> { + if archive.len() > max_entries { + return Err(InspectError::TooManyEntries { actual: archive.len(), limit: max_entries }); + } + let mut remaining = max_declared_bytes; + for index in 0..archive.len() { + remaining = + remaining.checked_sub(archive.by_index_raw(index)?.size()).ok_or(InspectError::DeclaredBytesExceeded { limit: max_declared_bytes })?; + } + if archive.has_overlapping_entries()? { + return Err(InspectError::OverlappingEntries); + } + Ok(()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + use std::io::{Cursor, Write}; + + #[test] + fn counts_all_declared_entries_and_detects_aliases() { + let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new())); + let options = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + writer.start_file("first", options).unwrap(); + writer.write_all(b"payload").unwrap(); + writer.shallow_copy_file("first", "alias").unwrap(); + let bytes = writer.finish().unwrap().into_inner(); + let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).unwrap(); + assert!(matches!(inspect_seekable(&mut archive, 1, 14), Err(InspectError::TooManyEntries { .. }))); + assert!(matches!(inspect_seekable(&mut archive, 2, 13), Err(InspectError::DeclaredBytesExceeded { .. }))); + assert!(matches!(inspect_seekable(&mut archive, 2, 14), Err(InspectError::OverlappingEntries))); + } + + #[test] + fn empty_aliases_still_overlap_at_the_header() { + let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new())); + writer.start_file("empty", zip::write::SimpleFileOptions::default()).unwrap(); + writer.shallow_copy_file("empty", "alias").unwrap(); + let mut archive = zip::ZipArchive::new(Cursor::new(writer.finish().unwrap().into_inner())).unwrap(); + assert!(matches!(inspect_seekable(&mut archive, 2, 0), Err(InspectError::OverlappingEntries))); + } + + #[test] + fn permits_exact_limits_and_empty_archive() { + let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new())); + writer.start_file("a", zip::write::SimpleFileOptions::default()).unwrap(); + writer.write_all(b"123").unwrap(); + let mut archive = zip::ZipArchive::new(Cursor::new(writer.finish().unwrap().into_inner())).unwrap(); + assert!(inspect_seekable(&mut archive, 1, 3).is_ok()); + let empty = zip::ZipWriter::new(Cursor::new(Vec::new())).finish().unwrap().into_inner(); + assert!(inspect_seekable(&mut zip::ZipArchive::new(Cursor::new(empty)).unwrap(), 0, 0).is_ok()); + } +}