From b616d590e862d9a2c63d67aaadb59dcae2e6d054 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Sun, 15 Nov 2026 11:15:32 -0500 Subject: [PATCH] Port XML property-list reader from Craft Anything Source: storytold/craft-anything at 8f3b775157d331dd31cfa4da911e26d8856b8c77, crates/formats/src/plist.rs and bytes.rs. Preserve original contributor fixes for document boundaries, UTF-16, numeric references, quoted attributes and line endings. Co-authored-by: Afloat Co-authored-by: BFlat Co-authored-by: Rahul Co-authored-by: RRFZ <247457381+Plastic-time@users.noreply.github.com> Co-authored-by: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> --- crates/plist/src/xml.rs | 432 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 432 insertions(+) create mode 100644 crates/plist/src/xml.rs diff --git a/crates/plist/src/xml.rs b/crates/plist/src/xml.rs new file mode 100644 index 000000000..7b41ecc91 --- /dev/null +++ b/crates/plist/src/xml.rs @@ -0,0 +1,432 @@ +//! XML property-list reader ported from Craft Anything at 8f3b7751. +use crate::{DateValue, FormatError, Value}; +const MAX_NODES: usize = 100_000; +const MAX_DEPTH: usize = 64; +fn decode_base64(text: &str, url_safe: bool) -> Option> { + let mut out = Vec::with_capacity(text.len() / 4 * 3); + let mut acc = 0u32; + let mut bits = 0u32; + let mut digits = 0usize; + let mut padding = 0usize; + for c in text.bytes() { + match c { + b' ' | b'\t' | b'\r' | b'\n' => continue, + b'=' => { + padding += 1; + if padding > 2 { + return None; + } + continue; + } + _ if padding != 0 => return None, + _ => {} + } + let value = match c { + b'A'..=b'Z' => c - b'A', + b'a'..=b'z' => c - b'a' + 26, + b'0'..=b'9' => c - b'0' + 52, + b'+' => 62, + b'/' => 63, + b'-' if url_safe => 62, + b'_' if url_safe => 63, + _ => return None, + }; + acc = (acc << 6) | u32::from(value); + bits += 6; + digits += 1; + if bits >= 8 { + bits -= 8; + out.push((acc >> bits) as u8); + acc &= (1 << bits) - 1; + } + } + let remainder = digits % 4; + if remainder == 1 || (padding != 0 && !matches!((remainder, padding), (2, 2) | (3, 1))) { + return None; + } + Some(out) +} + +fn base64_decode(s: &str) -> Option> { decode_base64(s, false) } +#[derive(Debug, Clone, PartialEq)] +enum Tok { + Open(String), + Close(String), + Empty(String), + Text(String), +} + +fn decode_entities(s: &str) -> String { + if !s.contains('&') { + return s.to_string(); + } + let mut out = String::with_capacity(s.len()); + let mut rest = s; + while let Some(p) = rest.find('&') { + out.push_str(rest.get(..p).unwrap_or("")); + let after = rest.get(p..).unwrap_or(""); + let Some(end) = after.find(';').filter(|&e| e <= 12) else { + out.push('&'); + rest = after.get(1..).unwrap_or(""); + continue; + }; + let ent = after.get(1..end).unwrap_or(""); + let rep = match ent { + "lt" => Some('<'), + "gt" => Some('>'), + "amp" => Some('&'), + "quot" => Some('"'), + "apos" => Some('\''), + e if e.starts_with("#x") || e.starts_with("#X") => { + let d = e.get(2..).unwrap_or(""); + if d.bytes().all(|b| b.is_ascii_hexdigit()) { u32::from_str_radix(d, 16).ok().and_then(char::from_u32) } else { None } + } + e if e.starts_with('#') => { + let d = e.get(1..).unwrap_or(""); + if d.bytes().all(|b| b.is_ascii_digit()) { d.parse::().ok().and_then(char::from_u32) } else { None } + } + _ => None, + }; + match rep { + Some(c) => { + out.push(c); + rest = after.get(end + 1..).unwrap_or(""); + } + None => { + out.push('&'); + rest = after.get(1..).unwrap_or(""); + } + } + } + out.push_str(rest); + out +} + +/// Skip a declaration without interpreting or fetching any entity. A DOCTYPE's +/// internal subset can itself contain declarations, quoted delimiters, comments and PIs. +fn after_declaration(mut rest: &str) -> Result<&str, FormatError> { + let mut quote = None; + let mut brackets = 0usize; + while let Some(ch) = rest.chars().next() { + if quote.is_none() { + if let Some(comment) = rest.strip_prefix("").ok_or_else(|| FormatError::Truncated("comment in declaration".into()))?.1; + continue; + } + if let Some(pi) = rest.strip_prefix("").ok_or_else(|| FormatError::Truncated("processing instruction in declaration".into()))?.1; + continue; + } + } + rest = rest.get(ch.len_utf8()..).unwrap_or(""); + match (quote, ch) { + (Some(q), c) if q == c => quote = None, + (None, '\'' | '"') => quote = Some(ch), + (None, '[') => brackets += 1, + (None, ']') => brackets = brackets.saturating_sub(1), + (None, '>') if brackets == 0 => return Ok(rest), + _ => {} + } + } + Err(FormatError::Truncated("declaration".into())) +} + +fn tokenize(text: &str) -> Result, FormatError> { + let mut toks = Vec::new(); + let mut rest = text; + while !rest.is_empty() { + if toks.len() > MAX_NODES { + return Err(FormatError::TooLarge("too many XML tokens".into())); + } + match rest.find('<') { + None => { + if !rest.is_empty() { + toks.push(Tok::Text(decode_entities(rest))); + } + break; + } + Some(p) => { + let t = rest.get(..p).unwrap_or(""); + if !t.is_empty() { + toks.push(Tok::Text(decode_entities(t))); + } + rest = rest.get(p..).unwrap_or(""); + } + } + if let Some(r) = rest.strip_prefix("").ok_or_else(|| FormatError::Truncated("comment".into()))?; + rest = r.get(e + 3..).unwrap_or(""); + continue; + } + if let Some(r) = rest.strip_prefix("").ok_or_else(|| FormatError::Truncated("CDATA".into()))?; + toks.push(Tok::Text(r.get(..e).unwrap_or("").to_string())); + rest = r.get(e + 3..).unwrap_or(""); + continue; + } + if let Some(r) = rest.strip_prefix("").ok_or_else(|| FormatError::Truncated("processing instruction".into()))?; + rest = r.get(end + 2..).unwrap_or(""); + continue; + } + if let Some(declaration) = rest.strip_prefix(" { + quote = None; + false + } + (None, '\'' | '"') => { + quote = Some(ch); + false + } + (None, '>') => true, + _ => false, + }) + .ok_or_else(|| FormatError::Truncated("tag".into()))?; + let inner = rest.get(1..e).unwrap_or("").trim(); + rest = rest.get(e + 1..).unwrap_or(""); + if let Some(name) = inner.strip_prefix('/') { + toks.push(Tok::Close(name.trim().to_string())); + } else if let Some(body) = inner.strip_suffix('/') { + toks.push(Tok::Empty(body.split_whitespace().next().unwrap_or("").to_string())); + } else { + toks.push(Tok::Open(inner.split_whitespace().next().unwrap_or("").to_string())); + } + } + Ok(toks) +} + +struct Xml { + toks: Vec, + pos: usize, + nodes: usize, +} + +impl Xml { + fn next(&mut self) -> Option { + let t = self.toks.get(self.pos).cloned(); + self.pos += 1; + t + } + + fn peek(&self) -> Option<&Tok> { + self.toks.get(self.pos) + } + + /// Text up to the closing tag `name`. + fn text_until(&mut self, name: &str) -> Result { + let mut s = String::new(); + loop { + match self.next() { + Some(Tok::Text(t)) => s.push_str(&t), + Some(Tok::Close(n)) if n == name => return Ok(s), + Some(other) => return Err(FormatError::Malformed(format!("unexpected {other:?} inside <{name}>"))), + None => return Err(FormatError::Truncated(format!("<{name}> is not closed"))), + } + } + } + + fn skip_space(&mut self) { + while matches!(self.peek(), Some(Tok::Text(t)) if t.bytes().all(|b| matches!(b, b' ' | b'\t' | b'\r' | b'\n'))) { + self.pos += 1; + } + } + + fn value(&mut self, depth: usize) -> Result { + self.nodes += 1; + if depth > MAX_DEPTH || self.nodes > MAX_NODES { + return Err(FormatError::TooLarge("plist nesting or size limit".into())); + } + self.skip_space(); + match self.next() { + Some(Tok::Empty(n)) => Ok(match n.as_str() { + "true" => Value::Bool(true), + "false" => Value::Bool(false), + "dict" => Value::Dict(Vec::new()), + "array" => Value::Array(Vec::new()), + "string" => Value::String(String::new()), + "data" => Value::Data(Vec::new()), + other => return Err(FormatError::Malformed(format!("unexpected <{other}/>"))), + }), + Some(Tok::Open(n)) => match n.as_str() { + "string" => Ok(Value::String(self.text_until("string")?)), + "integer" => { + let t = self.text_until("integer")?; + let t = t.trim(); + let v = if let Some(h) = t.strip_prefix("0x").or_else(|| t.strip_prefix("0X")) { + i128::from_str_radix(h, 16).ok() + } else { + t.parse::().ok() + }; + v.map(Value::Integer).ok_or_else(|| FormatError::Malformed(format!("bad integer {t:?}"))) + } + "real" => { + let t = self.text_until("real")?; + t.trim().parse::().map(Value::Real).map_err(|_| FormatError::Malformed(format!("bad real {t:?}"))) + } + "date" => Ok(Value::Date(DateValue::Text(self.text_until("date")?.trim().to_string()))), + "data" => { + let t = self.text_until("data")?; + base64_decode(&t).map(Value::Data).ok_or_else(|| FormatError::Malformed("bad base64 in ".into())) + } + "true" | "false" => { + if !self.text_until(&n)?.is_empty() { + return Err(FormatError::Malformed(format!("<{n}> must be empty"))); + } + Ok(Value::Bool(n == "true")) + } + "array" => { + let mut out = Vec::new(); + loop { + self.skip_space(); + if matches!(self.peek(), Some(Tok::Close(c)) if c == "array") { + self.pos += 1; + return Ok(Value::Array(out)); + } + if self.peek().is_none() { + return Err(FormatError::Truncated(" is not closed".into())); + } + out.push(self.value(depth + 1)?); + } + } + "dict" => { + let mut out = Vec::new(); + loop { + self.skip_space(); + match self.next() { + Some(Tok::Close(c)) if c == "dict" => return Ok(Value::Dict(out)), + Some(Tok::Open(k)) if k == "key" => { + let key = self.text_until("key")?; + let v = self.value(depth + 1)?; + out.push((key, v)); + } + Some(Tok::Empty(k)) if k == "key" => { + let v = self.value(depth + 1)?; + out.push((String::new(), v)); + } + Some(other) => return Err(FormatError::Malformed(format!("expected in , found {other:?}"))), + None => return Err(FormatError::Truncated(" is not closed".into())), + } + } + } + other => Err(FormatError::Malformed(format!("unknown plist element <{other}>"))), + }, + Some(other) => Err(FormatError::Malformed(format!("expected a value, found {other:?}"))), + None => Err(FormatError::Truncated("expected a value".into())), + } + } +} + +/// Decode a UTF-16 XML property list after its byte-order mark into UTF-8 text. +/// Surrogate pairs join normally; a lone surrogate fails as malformed rather +/// than turning into replacement characters that tokenize into garbage element +/// names. +fn decode_utf16_xml(data: &[u8], big_endian: bool) -> Result { + if !data.len().is_multiple_of(2) { + return Err(FormatError::Truncated("UTF-16 code unit".into())); + } + let units: Vec = data.chunks_exact(2).map(|b| if big_endian { u16::from_be_bytes([b[0], b[1]]) } else { u16::from_le_bytes([b[0], b[1]]) }).collect(); + String::from_utf16(&units).map_err(|_| FormatError::Malformed("invalid UTF-16 in XML plist".into())) +} + +/// Parse an XML property list. +pub fn parse_xml(data: &[u8]) -> Result { + // Apple's Core Foundation reader accepts XML plists in UTF-16 as well as + // UTF-8: it recognises both byte-order marks. `from_utf8_lossy` turns a + // UTF-16 byte stream into NUL-separated text, so the encoding is settled + // here, before tokenizing. + let text = match data { + [0xFF, 0xFE, rest @ ..] => decode_utf16_xml(rest, false)?, + [0xFE, 0xFF, rest @ ..] => decode_utf16_xml(rest, true)?, + _ => std::str::from_utf8(data.strip_prefix(b"\xef\xbb\xbf").unwrap_or(data)) + .map_err(|_| FormatError::Malformed("invalid UTF-8 in XML plist".into()))? + .to_owned(), + }; + // XML normalizes literal line endings before parsing; character references such as + // must still decode to a carriage return afterwards. + let text = if text.contains('\r') { text.replace("\r\n", "\n").replace('\r', "\n") } else { text }; + let toks = tokenize(&text)?; + let mut x = Xml { toks, pos: 0, nodes: 0 }; + x.skip_space(); + let wrapped = matches!(x.peek(), Some(Tok::Open(n)) if n == "plist"); + if wrapped { + x.pos += 1; + } + let value = x.value(0)?; + x.skip_space(); + if wrapped { + if !matches!(x.next(), Some(Tok::Close(n)) if n == "plist") { + return Err(FormatError::Malformed("expected after its value".into())); + } + x.skip_space(); + } + if x.peek().is_some() { + return Err(FormatError::Malformed("unexpected content after the plist value".into())); + } + Ok(value) +} + + +#[cfg(test)] +mod tests { +use super::*; + #[test] + fn xml_has_one_complete_root_with_only_markup_space_around_values() { + for invalid in [ + "", + "", + "", + "", + "junk", + "text", + "junk", + "xgarbage", + "no", + "yes", + "", + ] { + assert!(parse_xml(invalid.as_bytes()).is_err(), "{invalid}"); + } + let xml = b" ?>\n "; + assert_eq!(parse_xml(xml).unwrap().get("").and_then(Value::as_str), Some(" ")); + assert_eq!(parse_xml(b" ").unwrap(), Value::Bool(true)); + } + + #[test] + fn xml_rejects_partial_code_units_and_preserves_the_utf8_bom() { + assert_eq!(parse_xml(b"\xef\xbb\xbfok").unwrap().as_str(), Some("ok")); + assert!(parse_xml(b"\xff").is_err()); + for be in [false, true] { + let mut bytes = if be { vec![0xfe, 0xff] } else { vec![0xff, 0xfe] }; + for unit in "".encode_utf16() { + bytes.extend(if be { unit.to_be_bytes() } else { unit.to_le_bytes() }); + } + bytes.push(0); + assert!(parse_xml(&bytes).is_err()); + } + } + + #[test] + fn a_doctype_internal_subset_is_skipped_as_one_declaration() { + let doc = br#"y"> ?>]>ok"#; + assert_eq!(parse_xml(doc).unwrap().as_str(), Some("ok")); + assert!(parse_xml(b"").is_err()); + } + + #[test] + fn xml_char_refs_require_plain_digits() { + let text = |s: &str| { + let doc = format!("{s}"); + parse_xml(doc.as_bytes()).unwrap().as_str().map(str::to_string) + }; + assert_eq!(text("a&#+65;b&#x+41;").as_deref(), Some("a&#+65;b&#x+41;")); + assert_eq!(text("AA").as_deref(), Some("AA")); + assert_eq!(text("&#;&#x;").as_deref(), Some("&#;&#x;")); + } + +}