mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Move PhotoCraft XML preflight to craft-xml
This commit is contained in:
7 files changed
+31
-179
No files matched your search
Generated
+1
@@ -5603,6 +5603,7 @@ dependencies = [
|
||||
"craft-svg",
|
||||
"craft-tiff",
|
||||
"craft-xcf",
|
||||
"craft-xml",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"kurbo 0.13.1",
|
||||
|
||||
@@ -44,6 +44,7 @@ craft-print = { git = "https://github.com/storytold/craft-libs", rev = "80a8ecfe
|
||||
# HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784).
|
||||
craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "80a8ecfe0" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "80a8ecfe0", features = ["raster", "write-raster"] }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "80a8ecfe0" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "80a8ecfe0" }
|
||||
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "80a8ecfe0" }
|
||||
craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "80a8ecfe0" }
|
||||
|
||||
@@ -45,6 +45,7 @@ craft-xcf = { workspace = true }
|
||||
craft-pdn = { workspace = true }
|
||||
craft-svg = { workspace = true }
|
||||
craft-tiff = { workspace = true }
|
||||
craft-xml = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
ttf-parser = "0.25.1"
|
||||
serde_json = { workspace = true }
|
||||
@@ -52,8 +53,6 @@ blake3 = { version = "1.8", default-features = false, features = ["pure"] }
|
||||
# svg.rs inflates `.svgz` itself (with a size cap) so the XML can be checked before it is parsed;
|
||||
# pdn.rs inflates Paint.NET's gzip pixel chunks.
|
||||
flate2 = { workspace = true }
|
||||
# ora.rs reads OpenRaster's stack.xml (already in the tree through usvg).
|
||||
roxmltree = "0.21"
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# The SVG fallback font search keeps each font file's character map (already in the tree through usvg).
|
||||
ttf-parser = { version = "0.25", default-features = false }
|
||||
@@ -65,6 +64,8 @@ kurbo = { version = "0.13", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
lopdf = { version = "0.38", default-features = false }
|
||||
# PDF XMP serialization assertions parse output XML in tests.
|
||||
roxmltree = "0.21"
|
||||
miniz_oxide = "0.9"
|
||||
crc32fast = "1.5"
|
||||
photocraft-affinity = { workspace = true, features = ["synth"] }
|
||||
|
||||
@@ -270,11 +270,11 @@ fn number(s: &str) -> Option<f32> {
|
||||
}
|
||||
|
||||
/// `"0, 0"` items of an `rdf:Seq` → curve points.
|
||||
fn curve(node: roxmltree::Node<'_, '_>) -> Option<Vec<[f32; 2]>> {
|
||||
let seq = node.children().find(|c| c.is_element() && c.tag_name().namespace() == Some(RDF_NS) && c.tag_name().name() == "Seq")?;
|
||||
fn curve(node: &craft_xml::El) -> Option<Vec<[f32; 2]>> {
|
||||
let seq = node.child("rdf:Seq")?;
|
||||
let mut points = Vec::new();
|
||||
for li in seq.children().filter(|c| c.is_element() && c.tag_name().name() == "li") {
|
||||
let text = li.text().unwrap_or("");
|
||||
for li in seq.children("rdf:li") {
|
||||
let text = li.text();
|
||||
let (x, y) = text.split_once(',')?;
|
||||
points.push([number(x)?, number(y)?]);
|
||||
}
|
||||
@@ -336,21 +336,26 @@ pub fn load(params: &mut CameraRaw, bytes: &[u8]) -> Result<LoadReport, String>
|
||||
return Err("the settings file is too large".into());
|
||||
}
|
||||
let text = std::str::from_utf8(bytes).map_err(|_| "not a Camera Raw settings file (not UTF-8 text)".to_string())?;
|
||||
// Some writers put a byte order mark or an `<?xpacket?>` wrapper first; roxmltree takes both.
|
||||
// Adobe writers may add a UTF-8 BOM and an xpacket processing-instruction wrapper.
|
||||
let text = text.trim_start_matches('\u{feff}');
|
||||
let doc = crate::xml::parse(text, roxmltree::ParsingOptions::default()).map_err(|e| format!("not a Camera Raw settings file ({e})"))?;
|
||||
let namespaces = [("rdf", RDF_NS), ("crs", CRS_NS), ("x", META_NS)];
|
||||
let canonical = craft_xml::Canonical::new(&namespaces);
|
||||
let options = craft_xml::Options { doctype: craft_xml::Doctype::RejectInternalSubset, ..craft_xml::Options::canonical(&canonical) };
|
||||
let limits = craft_xml::Limits { max_input: MAX_XMP_BYTES, max_depth: crate::svg::MAX_XML_DEPTH, ..craft_xml::Limits::default() };
|
||||
let options = options.with_limits(limits).strict();
|
||||
let doc = options.parse(text.as_bytes()).map_err(|e| format!("not a Camera Raw settings file ({e})"))?;
|
||||
let mut next = params.clone();
|
||||
let mut report = LoadReport::default();
|
||||
let mut found = false;
|
||||
let mut crop_fields = CropFields::default();
|
||||
for desc in doc.descendants().filter(|n| n.is_element() && n.tag_name().namespace() == Some(RDF_NS) && n.tag_name().name() == "Description") {
|
||||
for a in desc.attributes().filter(|a| a.namespace() == Some(CRS_NS)) {
|
||||
for desc in doc.find_all("rdf:Description") {
|
||||
for (attribute, value) in desc.attrs.iter().filter(|(name, _)| name.starts_with("crs:")) {
|
||||
found = true;
|
||||
apply(&mut next, &mut report, &mut crop_fields, a.name(), a.value());
|
||||
apply(&mut next, &mut report, &mut crop_fields, attribute.trim_start_matches("crs:"), value);
|
||||
}
|
||||
for c in desc.children().filter(|c| c.is_element() && c.tag_name().namespace() == Some(CRS_NS)) {
|
||||
for c in desc.elements().filter(|c| c.name.starts_with("crs:")) {
|
||||
found = true;
|
||||
let name = c.tag_name().name();
|
||||
let name = c.name.trim_start_matches("crs:");
|
||||
if let Some((_, field)) = CURVES.iter().find(|(n, _)| *n == name) {
|
||||
match curve(c) {
|
||||
Some(points) => {
|
||||
@@ -359,13 +364,13 @@ pub fn load(params: &mut CameraRaw, bytes: &[u8]) -> Result<LoadReport, String>
|
||||
}
|
||||
None => report.ignored.push(name.to_string()),
|
||||
}
|
||||
} else if c.children().any(|g| g.is_element()) {
|
||||
} else if c.elements().next().is_some() {
|
||||
// Structured settings (masks, looks, lens profiles…) have no counterpart.
|
||||
if !METADATA.contains(&name) {
|
||||
report.ignored.push(name.to_string());
|
||||
}
|
||||
} else {
|
||||
apply(&mut next, &mut report, &mut crop_fields, name, c.text().unwrap_or(""));
|
||||
apply(&mut next, &mut report, &mut crop_fields, name, &c.text());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -398,11 +403,12 @@ pub fn is_photocraft_xmp(bytes: &[u8]) -> bool {
|
||||
return false;
|
||||
}
|
||||
let Ok(text) = std::str::from_utf8(bytes) else { return false };
|
||||
let Ok(doc) = roxmltree::Document::parse(text.trim_start_matches('\u{feff}')) else { return false };
|
||||
doc.descendants()
|
||||
.find(|n| n.is_element() && n.tag_name().namespace() == Some(META_NS) && n.tag_name().name() == "xmpmeta")
|
||||
.and_then(|n| n.attribute((META_NS, "xmptk")))
|
||||
== Some(TOOLKIT)
|
||||
let namespaces = [("x", META_NS), ("rdf", RDF_NS), ("crs", CRS_NS)];
|
||||
let canonical = craft_xml::Canonical::new(&namespaces);
|
||||
let options = craft_xml::Options { doctype: craft_xml::Doctype::RejectInternalSubset, ..craft_xml::Options::canonical(&canonical) };
|
||||
let limits = craft_xml::Limits { max_input: MAX_XMP_BYTES, max_depth: crate::svg::MAX_XML_DEPTH, ..craft_xml::Limits::default() };
|
||||
let Ok(doc) = options.with_limits(limits).strict().parse(text.trim_start_matches('\u{feff}').as_bytes()) else { return false };
|
||||
std::iter::once(&doc).chain(doc.descendants()).find(|n| n.is("x:xmpmeta")).and_then(|n| n.attr("x:xmptk")) == Some(TOOLKIT)
|
||||
}
|
||||
|
||||
/// Write `params` as a Camera Raw settings file Photoshop's Load Settings… reads.
|
||||
|
||||
@@ -89,7 +89,6 @@ pub mod tiff_layers;
|
||||
pub mod vector_map;
|
||||
pub mod vector_preview;
|
||||
mod xcf;
|
||||
pub mod xml;
|
||||
|
||||
pub use export_estimate::estimate_export_bytes;
|
||||
use photocraft_codecs::{CodecError, EncodeOptions};
|
||||
|
||||
@@ -406,7 +406,7 @@ fn the_plates_are_described_in_xmp_with_their_ink_colour_and_solidity() {
|
||||
assert!(pos("/Separation /Black#20#28Ink") < pos("/Separation /Underbase#20White"));
|
||||
// One packet, well-formed enough for an XML parser.
|
||||
assert_eq!(xmp.matches("<?xpacket begin").count(), 1);
|
||||
assert!(crate::xml::parse(&xmp[xmp.find("<x:xmpmeta").unwrap()..xmp.rfind("</x:xmpmeta>").unwrap() + 12], Default::default()).is_ok(), "{xmp}");
|
||||
assert!(craft_xml::parse(&xmp.as_bytes()[xmp.find("<x:xmpmeta").unwrap()..xmp.rfind("</x:xmpmeta>").unwrap() + 12]).is_ok(), "{xmp}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -442,7 +442,7 @@ fn the_plate_description_joins_the_rdf_element_however_the_packet_spells_it() {
|
||||
d.channels.push(spot("Varnish", photocraft_color::Color::rgb(0.9, 0.9, 0.6), &[1.0; 8]));
|
||||
// The packet must parse as namespaced XML with the plates a description inside its RDF element.
|
||||
let plates_in_rdf = |xmp: &str| {
|
||||
let tree = crate::xml::parse(xmp.trim_start_matches('\u{feff}'), roxmltree::ParsingOptions::default()).unwrap_or_else(|e| panic!("{e}: {xmp}"));
|
||||
let tree = roxmltree::Document::parse(xmp.trim_start_matches('\u{feff}')).unwrap_or_else(|e| panic!("{e}: {xmp}"));
|
||||
let plates = tree
|
||||
.descendants()
|
||||
.find(|n| n.tag_name().namespace() == Some(crate::pdf::SPOT_PLATES_NS) && n.tag_name().name() == "plates")
|
||||
|
||||
@@ -1,156 +0,0 @@
|
||||
//! XML parsing with a nesting cap. roxmltree recurses once per element level, so a few thousand
|
||||
//! nested tags (a 30 KB file or command param) overflow a 2 MB thread stack, an abort no guard
|
||||
//! can catch. Every roxmltree caller that reads a file or a param goes through [`parse`].
|
||||
|
||||
use roxmltree::{Document, ParsingOptions};
|
||||
|
||||
/// Deepest element nesting accepted, the same as for SVG drawings: real files stay far below.
|
||||
pub const MAX_DEPTH: usize = crate::svg::MAX_XML_DEPTH;
|
||||
|
||||
/// Parses `text`, refusing nesting deeper than [`MAX_DEPTH`] before roxmltree sees it.
|
||||
///
|
||||
/// With `opts.allow_dtd` an internal DTD subset is refused too: its entities can expand into
|
||||
/// markup the depth check never sees. An external DOCTYPE (a public or system id) still parses.
|
||||
pub fn parse<'i>(text: &'i str, opts: ParsingOptions<'i>) -> Result<Document<'i>, String> {
|
||||
if opts.allow_dtd && internal_subset(text.as_bytes()) {
|
||||
return Err("internal DTD subsets aren't supported".into());
|
||||
}
|
||||
if crate::svg::nesting_depth(text.as_bytes(), MAX_DEPTH).map_err(|e| e.to_string())? > MAX_DEPTH {
|
||||
return Err(format!("elements are nested more than {MAX_DEPTH} levels deep"));
|
||||
}
|
||||
Document::parse_with_options(text, opts).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Does a DOCTYPE have an internal subset (`<!DOCTYPE x [ … ]>`)? Every `<!DOCTYPE` in the text
|
||||
/// is checked, not only the one a walk over the prolog reaches: a quoted `?>` in the XML
|
||||
/// declaration must not hide it. One inside a comment may be refused needlessly; that fails safe.
|
||||
///
|
||||
/// Each `<!DOCTYPE` starts a scan over what follows: the name and the quoted public/system ids
|
||||
/// come first, a `[` outside quotes opens the subset, a `>` ends a DOCTYPE without one. Scans in
|
||||
/// the same quote state go on alike, so one pass keeps just three flags (outside quotes, in `"`,
|
||||
/// in `'`) and stays linear however many `<!DOCTYPE`s a comment holds.
|
||||
fn internal_subset(xml: &[u8]) -> bool {
|
||||
const DOCTYPE: &[u8] = b"<!DOCTYPE";
|
||||
let (mut bare, mut double, mut single) = (false, false, false);
|
||||
for (at, &b) in xml.iter().enumerate() {
|
||||
if at.checked_sub(DOCTYPE.len()).and_then(|start| xml.get(start..at)) == Some(DOCTYPE) {
|
||||
bare = true;
|
||||
}
|
||||
if bare && b == b'[' {
|
||||
return true;
|
||||
}
|
||||
(bare, double, single) = (
|
||||
(bare && !matches!(b, b'"' | b'\'' | b'>')) || (double && b == b'"') || (single && b == b'\''),
|
||||
(double && b != b'"') || (bare && b == b'"'),
|
||||
(single && b != b'\'') || (bare && b == b'\''),
|
||||
);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn nested(levels: usize) -> String {
|
||||
format!("<a>{}{}</a>", "<g>".repeat(levels), "</g>".repeat(levels))
|
||||
}
|
||||
|
||||
fn dtd<'a>() -> ParsingOptions<'a> {
|
||||
ParsingOptions { allow_dtd: true, ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nesting_past_the_cap_is_an_error_not_a_stack_overflow() {
|
||||
let deep = nested(20_000);
|
||||
std::thread::Builder::new()
|
||||
.stack_size(512 * 1024)
|
||||
.spawn(move || {
|
||||
for opts in [ParsingOptions::default(), dtd()] {
|
||||
let e = parse(&deep, opts).err().unwrap_or_else(|| panic!("parsed"));
|
||||
assert!(e.contains("nested") && e.contains(&MAX_DEPTH.to_string()), "{e}");
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap();
|
||||
// The root plus MAX_DEPTH - 1 levels is exactly MAX_DEPTH deep.
|
||||
assert!(parse(&nested(MAX_DEPTH - 1), ParsingOptions::default()).is_ok());
|
||||
assert!(parse(&nested(MAX_DEPTH), ParsingOptions::default()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markup_in_comments_cdata_pis_and_attributes_adds_no_depth() {
|
||||
let g = "<g>".repeat(2 * MAX_DEPTH);
|
||||
let xml = format!("<?xml version=\"1.0\"?><!-- {g} --><a t=\"<> /> >\"><![CDATA[ {g} ]]><?pi {g} ?><b/></a>");
|
||||
assert!(parse(&xml, ParsingOptions::default()).is_ok());
|
||||
}
|
||||
|
||||
/// The scan per `<!DOCTYPE` that [`internal_subset`] folds into one pass.
|
||||
fn internal_subset_per_doctype(xml: &[u8]) -> bool {
|
||||
const DOCTYPE: &[u8] = b"<!DOCTYPE";
|
||||
xml.windows(DOCTYPE.len()).enumerate().filter(|(_, w)| *w == DOCTYPE).any(|(at, _)| {
|
||||
let mut quote = None;
|
||||
for &b in &xml[at + DOCTYPE.len()..] {
|
||||
match quote {
|
||||
Some(q) if b == q => quote = None,
|
||||
Some(_) => {}
|
||||
None if b == b'"' || b == b'\'' => quote = Some(b),
|
||||
None if b == b'[' => return true,
|
||||
None if b == b'>' => return false,
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
false
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_one_pass_doctype_scan_agrees_with_a_scan_per_doctype() {
|
||||
let parts: [&[u8]; 7] = [b"<!DOCTYPE", b"\"", b"'", b"[", b">", b"a", b"<!-- "];
|
||||
// Every sequence of up to six parts, so the scans overlap in each quote state.
|
||||
let mut checked = 0;
|
||||
for len in 0..=6u32 {
|
||||
for mut code in 0..parts.len().pow(len) {
|
||||
let mut xml = Vec::new();
|
||||
for _ in 0..len {
|
||||
xml.extend_from_slice(parts[code % parts.len()]);
|
||||
code /= parts.len();
|
||||
}
|
||||
assert_eq!(internal_subset(&xml), internal_subset_per_doctype(&xml), "{}", String::from_utf8_lossy(&xml));
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert!(checked > 100_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_doctypes_in_a_comment_scan_in_linear_time() {
|
||||
// A scan per `<!DOCTYPE` reads on to the end from each of the ~1.9 million here, some
|
||||
// 10^13 steps; one pass reads the 16 MiB once.
|
||||
let xml = format!("<!-- {} --><a/>", "<!DOCTYPE".repeat((16 << 20) / 9));
|
||||
let started = std::time::Instant::now();
|
||||
assert!(parse(&xml, dtd()).is_ok());
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(20), "{:?}", started.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_internal_subset_is_refused_an_external_doctype_parses() {
|
||||
let krita = "<?xml version=\"1.0\"?>\n<!-- c --><!DOCTYPE DOC PUBLIC '-//KDE//DTD krita 2.0//EN' 'http://www.calligra.org/DTD/[krita].dtd'>\n<DOC/>";
|
||||
assert!(parse(krita, dtd()).is_ok());
|
||||
let g = ("<g>".repeat(20_000), "</g>".repeat(20_000));
|
||||
for xml in [
|
||||
"<!DOCTYPE a [<!ENTITY e \"x\">]><a>&e;</a>".to_string(),
|
||||
"\u{feff}<?xml version=\"1.0\"?><!-- ' --> <!DOCTYPE a SYSTEM \"a.dtd\" [<!-- ' -->]><a/>".to_string(),
|
||||
format!("<!DOCTYPE a [<!ENTITY e \"{}{}\">]><a>&e;</a>", g.0, g.1),
|
||||
// roxmltree reads the declaration's values as quoted attributes, so they may hold `?>`.
|
||||
format!("<?xml version=\"?>\"?><!DOCTYPE a [<!ENTITY e \"{}{}\">]><a>&e;</a>", g.0, g.1),
|
||||
format!("<?xml version=\"?>\"?><!DOCTYPE a [<!-- ' -->]><a>{}{}</a><!-- ' -->", g.0, g.1),
|
||||
] {
|
||||
let e = parse(&xml, dtd()).err().unwrap_or_else(|| panic!("parsed {xml:.60}"));
|
||||
assert!(e.contains("internal DTD"), "{e}");
|
||||
}
|
||||
// Without allow_dtd roxmltree refuses any DOCTYPE itself.
|
||||
assert!(parse(krita, ParsingOptions::default()).is_err());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user