diff --git a/Cargo.lock b/Cargo.lock index 03332b2e54..399529f05e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5603,6 +5603,7 @@ dependencies = [ "craft-svg", "craft-tiff", "craft-xcf", + "craft-xml", "crc32fast", "flate2", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index fcd2da3b02..347a3563fa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" } diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index d24f3b5b5e..10e9b068fc 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -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"] } diff --git a/crates/io/src/camera_raw_xmp.rs b/crates/io/src/camera_raw_xmp.rs index 76fd8bb0ca..f204870a87 100644 --- a/crates/io/src/camera_raw_xmp.rs +++ b/crates/io/src/camera_raw_xmp.rs @@ -270,11 +270,11 @@ fn number(s: &str) -> Option { } /// `"0, 0"` items of an `rdf:Seq` → curve points. -fn curve(node: roxmltree::Node<'_, '_>) -> Option> { - 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> { + 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 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 `` 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 } 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. diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 98c999c6f2..7c55580c40 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -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}; diff --git a/crates/io/src/pdf/tests.rs b/crates/io/src/pdf/tests.rs index 86d1472005..37575545e8 100644 --- a/crates/io/src/pdf/tests.rs +++ b/crates/io/src/pdf/tests.rs @@ -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("").unwrap() + 12], Default::default()).is_ok(), "{xmp}"); + assert!(craft_xml::parse(&xmp.as_bytes()[xmp.find("").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") diff --git a/crates/io/src/xml.rs b/crates/io/src/xml.rs deleted file mode 100644 index 423c8c8555..0000000000 --- a/crates/io/src/xml.rs +++ /dev/null @@ -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, 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 (``)? Every `` in the XML -/// declaration must not hide it. One inside a comment may be refused needlessly; that fails safe. -/// -/// Each `` 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 ` bool { - const DOCTYPE: &[u8] = 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!("{}{}", "".repeat(levels), "".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 = "".repeat(2 * MAX_DEPTH); - let xml = format!("\">"); - assert!(parse(&xml, ParsingOptions::default()).is_ok()); - } - - /// The scan per ` bool { - const DOCTYPE: &[u8] = b" 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"", b"a", b"", "\n\n"; - assert!(parse(krita, dtd()).is_ok()); - let g = ("".repeat(20_000), "".repeat(20_000)); - for xml in [ - "]>&e;".to_string(), - "\u{feff} ]>".to_string(), - format!("]>&e;", g.0, g.1), - // roxmltree reads the declaration's values as quoted attributes, so they may hold `?>`. - format!("\"?>]>&e;", g.0, g.1), - format!("\"?>]>{}{}", 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()); - } -}