Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

fix(io): recognize reordered PhotoCraft archives (#137)

MikeeI28a63fe27e89
diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs
index fe382cf87..8fd60f401 100644
--- a/crates/format/src/lib.rs
+++ b/crates/format/src/lib.rs
@@ -91,13 +91,20 @@ impl Default for LoadOptions {
}
}
-/// `true` if `bytes` look like a `.pcraft` ZIP bundle (a ZIP whose first
-/// entry is `manifest.json`, which is how we write them).
+/// `true` when ZIP bytes contain a `manifest.json` entry.
+///
+/// Bundles written here place the manifest first; re-zipped bundles may reorder entries.
pub fn is_pcraft(bytes: &[u8]) -> bool {
- bytes.len() > 30 && bytes.starts_with(b"PK\x03\x04") && {
- let n = u16::from_le_bytes([bytes[26], bytes[27]]) as usize;
- bytes.get(30..30 + n) == Some(b"manifest.json")
+ if !bytes.starts_with(b"PK\x03\x04") {
+ return false;
}
+ if bytes.len() >= 30 {
+ let name_len = u16::from_le_bytes([bytes[26], bytes[27]]) as usize;
+ if bytes.get(30..30 + name_len) == Some(b"manifest.json") {
+ return true;
+ }
+ }
+ zip::ZipReader::new(bytes).is_ok_and(|archive| archive.find("manifest.json").is_some())
}
/// Save to an in-memory ZIP bundle (one-shot; use [`PcraftWriter`] for
diff --git a/crates/format/src/zip.rs b/crates/format/src/zip.rs
index 0ef291021..3f6161aa7 100644
--- a/crates/format/src/zip.rs
+++ b/crates/format/src/zip.rs
@@ -126,10 +126,10 @@ pub struct ZipReader<'a> {
}
fn u16_at(b: &[u8], o: usize) -> Result<u16, FormatError> {
- b.get(o..o + 2).map(|s| u16::from_le_bytes([s[0], s[1]])).ok_or_else(|| FormatError::corrupt("truncated zip"))
+ o.checked_add(2).and_then(|end| b.get(o..end)).map(|s| u16::from_le_bytes([s[0], s[1]])).ok_or_else(|| FormatError::corrupt("truncated zip"))
}
fn u32_at(b: &[u8], o: usize) -> Result<u32, FormatError> {
- b.get(o..o + 4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])).ok_or_else(|| FormatError::corrupt("truncated zip"))
+ o.checked_add(4).and_then(|end| b.get(o..end)).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])).ok_or_else(|| FormatError::corrupt("truncated zip"))
}
impl<'a> ZipReader<'a> {
@@ -146,12 +146,11 @@ impl<'a> ZipReader<'a> {
let count = u16_at(bytes, eocd + 10)? as usize;
let cd_size = u32_at(bytes, eocd + 12)? as usize;
let cd_off = u32_at(bytes, eocd + 16)? as usize;
- if cd_off.checked_add(cd_size).is_none_or(|e| e > eocd) {
- return Err(FormatError::corrupt("zip central directory out of range"));
- }
+ let cd_end = cd_off.checked_add(cd_size).filter(|end| *end <= eocd).ok_or_else(|| FormatError::corrupt("zip central directory out of range"))?;
let mut entries = Vec::with_capacity(count.min(bytes.len() / 46));
let mut p = cd_off;
for _ in 0..count {
+ let header_end = p.checked_add(46).filter(|end| *end <= cd_end).ok_or_else(|| FormatError::corrupt("truncated zip central directory entry"))?;
if u32_at(bytes, p)? != CENTRAL_SIG {
return Err(FormatError::corrupt("bad zip central directory entry"));
}
@@ -164,23 +163,36 @@ impl<'a> ZipReader<'a> {
let elen = u16_at(bytes, p + 30)? as usize;
let clen = u16_at(bytes, p + 32)? as usize;
let local = u32_at(bytes, p + 42)? as usize;
- let name = bytes.get(p + 46..p + 46 + nlen).ok_or_else(|| FormatError::corrupt("truncated zip name"))?;
+ let name_end = header_end.checked_add(nlen).filter(|end| *end <= cd_end).ok_or_else(|| FormatError::corrupt("zip entry name out of range"))?;
+ let name = bytes.get(header_end..name_end).ok_or_else(|| FormatError::corrupt("truncated zip name"))?;
let name = String::from_utf8_lossy(name).into_owned();
if flags & 1 != 0 {
return Err(FormatError::Unsupported("encrypted zip entries".into()));
}
+ // Bound each entry by the declared central-directory extent before advancing.
+ let entry_end = name_end
+ .checked_add(elen)
+ .and_then(|end| end.checked_add(clen))
+ .filter(|end| *end <= cd_end)
+ .ok_or_else(|| FormatError::corrupt("zip central directory entry out of range"))?;
// Local header gives the real data offset.
if u32_at(bytes, local)? != LOCAL_SIG {
return Err(FormatError::corrupt("bad zip local header"));
}
- let lnlen = u16_at(bytes, local + 26)? as usize;
- let lelen = u16_at(bytes, local + 28)? as usize;
- let data_offset = local + 30 + lnlen + lelen;
- if data_offset.checked_add(compressed).is_none_or(|e| e > bytes.len()) {
+ let local_name_len = local.checked_add(26).ok_or_else(|| FormatError::corrupt("zip local header offset overflow"))?;
+ let local_extra_len = local.checked_add(28).ok_or_else(|| FormatError::corrupt("zip local header offset overflow"))?;
+ let lnlen = u16_at(bytes, local_name_len)? as usize;
+ let lelen = u16_at(bytes, local_extra_len)? as usize;
+ let data_offset = local
+ .checked_add(30)
+ .and_then(|offset| offset.checked_add(lnlen))
+ .and_then(|offset| offset.checked_add(lelen))
+ .ok_or_else(|| FormatError::corrupt("zip data offset overflow"))?;
+ if data_offset.checked_add(compressed).is_none_or(|end| end > bytes.len()) {
return Err(FormatError::corrupt(format!("zip entry `{name}` out of range")));
}
entries.push(Entry { name, method, crc, compressed, uncompressed, data_offset });
- p += 46 + nlen + elen + clen;
+ p = entry_end;
}
Ok(ZipReader { bytes, entries })
}
@@ -258,4 +270,10 @@ mod tests {
let r = ZipReader::new(&bytes).unwrap();
assert!(r.read_by_name("a", 100).is_err());
}
+
+ #[test]
+ fn offset_access_rejects_overflow() {
+ assert!(u16_at(&[], usize::MAX).is_err());
+ assert!(u32_at(&[], usize::MAX - 3).is_err());
+ }
}
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index 162c28726..62181b539 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -108,7 +108,8 @@ pub fn is_psd(bytes: &[u8]) -> bool {
/// Imports a file. PSD/PSB and camera raws are detected by magic; everything
/// else is decoded with `photocraft-codecs`.
pub fn import(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {
- if photocraft_format::is_pcraft(bytes) {
+ // A declared native extension must reach its loader so malformed bundles retain format errors.
+ if has_extension(name, photocraft_format::EXTENSION) || photocraft_format::is_pcraft(bytes) {
return Ok(ImportResult { document: photocraft_format::load_from_bytes(bytes)?, warnings: Vec::new() });
}
if is_psd(bytes) {
@@ -127,6 +128,10 @@ fn extension(name_or_ext: &str) -> String {
name_or_ext.rsplit(['.', '/', '\\']).next().unwrap_or(name_or_ext).to_ascii_lowercase()
}
+fn has_extension(name: &str, expected: &str) -> bool {
+ name.rsplit(['/', '\\']).next().and_then(|name| name.rsplit_once('.')).is_some_and(|(base, ext)| !base.is_empty() && ext.eq_ignore_ascii_case(expected))
+}
+
/// Exports `doc` to the format named by `name_or_ext` (a file name, path or
/// bare extension).
pub fn export(doc: &Document, name_or_ext: &str, opts: &ExportOptions) -> Result<ExportResult, IoError> {
diff --git a/crates/io/tests/comps_artboards.rs b/crates/io/tests/comps_artboards.rs
index 5dfcd6b5b..cdb90ce3d 100644
--- a/crates/io/tests/comps_artboards.rs
+++ b/crates/io/tests/comps_artboards.rs
@@ -216,4 +216,22 @@ fn synthetic_pcraft_roundtrip_keeps_everything() {
let c = &fresh.layer_comps[0];
assert_eq!(c.states.len(), fresh.layer_count());
assert!(c.states.iter().all(|s| fresh.layer(s.layer).is_some()));
+
+ // Native identity is independent of ZIP entry order and the filename extension.
+ let zip = photocraft_format::zip::ZipReader::new(&bytes).unwrap();
+ let mut reordered = photocraft_format::zip::ZipWriter::new();
+ reordered.add("extra.txt", b"not the manifest").unwrap();
+ for entry in &zip.entries {
+ reordered.add(&entry.name, &zip.read(entry, bytes.len()).unwrap()).unwrap();
+ }
+ let reordered = reordered.finish().unwrap();
+ for name in ["x.PCRAFT", "no-extension"] {
+ let imported = import(name, &reordered).unwrap().document;
+ assert_eq!(imported.layer_comps, d.layer_comps);
+ assert_eq!(imported.layers[1].artboard(), d.layers[1].artboard());
+ }
+
+ let png = export(&d, "x.png", &ExportOptions::default()).unwrap().bytes;
+ assert!(import("pcraft", &png).is_ok());
+ assert!(matches!(import("broken.pcraft", b"not a native bundle"), Err(photocraft_io::IoError::Pcraft(_))));
}