//! A small, strict XML reader for the host's answers: one `` element with nested //! elements and text. No DTD, no entities beyond the five predefined ones and numeric character references, //! no processing instructions except a leading XML declaration, no comments, no CDATA, no namespaces. //! //! The reader is iterative (an explicit stack), so nesting cannot exhaust the call stack, and every cap is checked //! before the memory it guards is used. use crate::Result; use crate::util::{cap, malformed}; /// Maximum size of any XML body accepted, in bytes. pub const MAX_XML_BYTES: usize = 1024 * 1024; /// Maximum element nesting depth (the root is depth 1). pub const MAX_XML_DEPTH: usize = 8; /// Maximum number of elements in one document. pub const MAX_XML_ELEMENTS: usize = 16 * 1024; /// Maximum length of one element's text, in bytes after unescaping. pub const MAX_XML_TEXT_BYTES: usize = 64 * 1024; /// Maximum number of attributes on one element. pub const MAX_XML_ATTRIBUTES: usize = 8; /// Longest entity or character reference body accepted (`#x10FFFF` is 8). const MAX_ENTITY_LEN: usize = 10; /// One element: its name, attributes, text (concatenated, unescaped, not trimmed) and child elements. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Element { /// Tag name, case-sensitive. pub name: String, /// Attributes in document order, values unescaped. pub attributes: Vec<(String, String)>, /// Text content directly inside this element. pub text: String, /// Child elements in document order. pub children: Vec, } impl Element { /// The first child with this name. #[must_use] pub fn child(&self, name: &str) -> Option<&Element> { self.children.iter().find(|c| c.name == name) } /// The value of the first attribute with this name. #[must_use] pub fn attribute(&self, name: &str) -> Option<&str> { self.attributes.iter().find(|(n, _)| n == name).map(|(_, v)| v.as_str()) } } /// A parsed host answer. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Document { /// The root element's `status_code` attribute (the host's status; 200 = OK). pub status_code: u32, /// The root element's `status_message` attribute, if any (UNKNOWN U27). pub status_message: Option, /// The root element itself. pub root: Element, } /// Parses an XML answer. The root element must be `root` and carry a decimal `status_code`. /// /// # Errors /// [`crate::Error::TooLarge`] over [`MAX_XML_BYTES`] or any other cap, [`crate::Error::Malformed`] for anything that /// is not well-formed or uses a refused feature. pub fn parse(body: &[u8]) -> Result { cap("xml document", MAX_XML_BYTES, body.len())?; let text = core::str::from_utf8(body).map_err(|_| malformed("xml: not UTF-8"))?; let root = Reader { s: text, b: text.as_bytes(), pos: 0, elements: 0 }.document()?; if root.name != "root" { return Err(malformed("xml: root element is not `root`")); } let code = root.attribute("status_code").ok_or(malformed("xml: no status_code"))?; let status_code = crate::util::parse_u32("xml status_code", code)?; let status_message = root.attribute("status_message").map(str::to_owned); Ok(Document { status_code, status_message, root }) } struct Reader<'a> { s: &'a str, b: &'a [u8], pos: usize, elements: usize, } fn is_name_start(c: u8) -> bool { c.is_ascii_alphabetic() || c == b'_' } fn is_name_char(c: u8) -> bool { c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.') } fn is_space(c: u8) -> bool { matches!(c, b' ' | b'\t' | b'\r' | b'\n') } impl Reader<'_> { fn peek(&self) -> Option { self.b.get(self.pos).copied() } fn peek_at(&self, ahead: usize) -> Option { self.b.get(self.pos.saturating_add(ahead)).copied() } fn rest(&self) -> &[u8] { self.b.get(self.pos..).unwrap_or(&[]) } fn skip_ws(&mut self) -> bool { let start = self.pos; while self.peek().is_some_and(is_space) { self.pos += 1; } self.pos > start } fn expect(&mut self, c: u8, what: &'static str) -> Result<()> { if self.peek() == Some(c) { self.pos += 1; Ok(()) } else { Err(malformed(what)) } } fn name(&mut self) -> Result { let start = self.pos; if !self.peek().is_some_and(is_name_start) { return Err(malformed("xml: bad name")); } while self.peek().is_some_and(is_name_char) { self.pos += 1; } if self.peek() == Some(b':') { return Err(malformed("xml: namespaces are refused")); } self.s.get(start..self.pos).map(str::to_owned).ok_or(malformed("xml: bad name")) } /// The optional leading ``, only at byte 0. fn declaration(&mut self) -> Result<()> { if self.rest().starts_with(b"").ok_or(malformed("xml: unclosed declaration"))?; self.pos += end + 2; } Ok(()) } fn attach(stack: &mut [Element], root: &mut Option, element: Element) { match stack.last_mut() { Some(parent) => parent.children.push(element), None => *root = Some(element), } } fn document(mut self) -> Result { self.declaration()?; self.skip_ws(); let mut stack: Vec = Vec::new(); let mut root: Option = None; while let Some(c) = self.peek() { if c == b'<' { if root.is_some() { return Err(malformed("xml: content after the root element")); } match self.peek_at(1) { Some(b'/') => { self.pos += 2; let name = self.name()?; self.skip_ws(); self.expect(b'>', "xml: bad end tag")?; let done = stack.pop().ok_or(malformed("xml: end tag without start"))?; if done.name != name { return Err(malformed("xml: mismatched end tag")); } Self::attach(&mut stack, &mut root, done); } Some(b'!' | b'?') => return Err(malformed("xml: DTD, comment, CDATA or PI refused")), _ => { self.pos += 1; let (element, closed) = self.start_tag()?; self.elements += 1; cap("xml elements", MAX_XML_ELEMENTS, self.elements)?; cap("xml depth", MAX_XML_DEPTH, stack.len() + 1)?; if closed { Self::attach(&mut stack, &mut root, element); } else { stack.push(element); } } } } else { let already = stack.last().map_or(0, |t| t.text.len()); let text = self.text(already)?; match stack.last_mut() { Some(top) => top.text.push_str(&text), None => { if !text.bytes().all(is_space) { return Err(malformed("xml: text outside the root element")); } } } } } if !stack.is_empty() { return Err(malformed("xml: unclosed element")); } root.ok_or(malformed("xml: no root element")) } /// After `<`: name, attributes, `>` or `/>`. Returns the element and whether it was self-closing. fn start_tag(&mut self) -> Result<(Element, bool)> { let name = self.name()?; let mut attributes: Vec<(String, String)> = Vec::new(); loop { let had_ws = self.skip_ws(); match self.peek() { Some(b'>') => { self.pos += 1; return Ok((Element { name, attributes, ..Element::default() }, false)); } Some(b'/') => { self.pos += 1; self.expect(b'>', "xml: bad self-closing tag")?; return Ok((Element { name, attributes, ..Element::default() }, true)); } Some(_) if had_ws => { let key = self.name()?; if key == "xmlns" { return Err(malformed("xml: namespaces are refused")); } self.skip_ws(); self.expect(b'=', "xml: attribute without =")?; self.skip_ws(); let value = self.attribute_value()?; if attributes.iter().any(|(k, _)| *k == key) { return Err(malformed("xml: duplicate attribute")); } attributes.push((key, value)); cap("xml attributes", MAX_XML_ATTRIBUTES, attributes.len())?; } _ => return Err(malformed("xml: bad start tag")), } } } fn attribute_value(&mut self) -> Result { let quote = self.peek().filter(|q| *q == b'"' || *q == b'\'').ok_or(malformed("xml: unquoted attribute"))?; self.pos += 1; let mut out = String::new(); loop { let start = self.pos; while self.peek().is_some_and(|c| c != quote && c != b'&' && c != b'<') { self.pos += 1; } cap("xml text", MAX_XML_TEXT_BYTES, out.len().saturating_add(self.pos - start))?; out.push_str(self.s.get(start..self.pos).ok_or(malformed("xml: bad attribute"))?); match self.peek() { Some(c) if c == quote => { self.pos += 1; return Ok(out); } Some(b'&') => { out.push(self.entity()?); cap("xml text", MAX_XML_TEXT_BYTES, out.len())?; } _ => return Err(malformed("xml: bad attribute value")), } } } /// Text up to the next `<` (or the end), unescaped, capped together with the `already` bytes of the element. fn text(&mut self, already: usize) -> Result { let mut out = String::new(); loop { let start = self.pos; while self.peek().is_some_and(|c| c != b'<' && c != b'&') { self.pos += 1; } cap("xml text", MAX_XML_TEXT_BYTES, already.saturating_add(out.len()).saturating_add(self.pos - start))?; out.push_str(self.s.get(start..self.pos).ok_or(malformed("xml: bad text"))?); if self.peek() == Some(b'&') { out.push(self.entity()?); cap("xml text", MAX_XML_TEXT_BYTES, already.saturating_add(out.len()))?; } else { return Ok(out); } } } /// At `&`: one of the five entities or a character reference, ending in `;`. fn entity(&mut self) -> Result { self.pos += 1; let len = self .rest() .iter() .take(MAX_ENTITY_LEN + 1) .position(|&c| c == b';') .ok_or(malformed("xml: entity without ;"))?; let body = self.s.get(self.pos..self.pos + len).ok_or(malformed("xml: bad entity"))?; self.pos += len + 1; let c = match body { "lt" => '<', "gt" => '>', "amp" => '&', "quot" => '"', "apos" => '\'', _ => { let code = if let Some(hex) = body.strip_prefix("#x") { if hex.is_empty() || hex.len() > 8 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) { return Err(malformed("xml: bad character reference")); } u32::from_str_radix(hex, 16).map_err(|_| malformed("xml: bad character reference"))? } else if let Some(dec) = body.strip_prefix('#') { crate::util::parse_u32("xml character reference", dec)? } else { return Err(malformed("xml: unknown entity")); }; if code == 0 { return Err(malformed("xml: NUL character reference")); } char::from_u32(code).ok_or(malformed("xml: invalid character reference"))? } }; Ok(c) } }