1use std::ops::Range;
8
9use quick_xml::XmlVersion;
10use quick_xml::events::{BytesStart, Event};
11use quick_xml::name::ResolveResult;
12use quick_xml::reader::NsReader;
13
14use crate::{Error, Limits, UTF8_MARK, declared_encoding};
15
16#[derive(Clone, Debug)]
18pub struct StreamedBody {
19 pub in_scope: Vec<(String, String)>,
22 pub doc_in_scope: Vec<(String, String)>,
24 pub background: Option<Range<usize>>,
26 pub children: Vec<Range<usize>>,
28 pub has_revisions: bool,
30 pub has_cross_block_features: bool,
33}
34
35pub fn scan_body_children(
51 bytes: &[u8],
52 w_namespaces: &[&str],
53 body_wrappers: &[&str],
54 limits: &Limits,
55) -> Result<Option<StreamedBody>, Error> {
56 u32::try_from(bytes.len()).map_err(|_| Error::TooLarge)?;
57 if bytes.starts_with(&[0xFF, 0xFE]) || bytes.starts_with(&[0xFE, 0xFF]) {
58 return Ok(None);
59 }
60 let skipped = if bytes.starts_with(&UTF8_MARK) {
61 UTF8_MARK.len()
62 } else {
63 0
64 };
65 let mut reader = NsReader::from_reader(bytes);
66 reader.config_mut().check_end_names = true;
67 let mut state = ScanState::new(w_namespaces, body_wrappers, limits, skipped);
68 let mut buf = Vec::new();
69 loop {
70 buf.clear();
71 let start = state.position(&reader)?;
72 let (resolved, event) = reader
73 .read_resolved_event_into(&mut buf)
74 .map_err(|error| Error::Syntax(error.to_string()))?;
75 let is_w = state.is_w(&resolved);
76 let end = state.position(&reader)?;
77 match event {
78 Event::Eof => break,
79 Event::DocType(_) => return Err(Error::DocType),
80 Event::Decl(decl) => {
81 if declared_encoding(&decl).is_some() {
82 return Ok(None);
83 }
84 }
85 Event::Start(tag) => state.on_start(&tag, is_w, start, end, false)?,
86 Event::Empty(tag) => state.on_start(&tag, is_w, start, end, true)?,
87 Event::End(_) => state.on_end(end),
88 Event::Text(_)
89 | Event::CData(_)
90 | Event::GeneralRef(_)
91 | Event::Comment(_)
92 | Event::PI(_) => {}
93 }
94 }
95 if state.depth != 0 {
96 return Err(Error::Syntax("unclosed element".to_owned()));
97 }
98 Ok(state.finish())
99}
100
101#[derive(Clone, Copy, Debug, PartialEq, Eq)]
102enum ScanPhase {
103 BeforeDocument,
104 InDocument,
105 InBody,
106 AfterBody,
107}
108
109struct ScanState<'a> {
110 w_namespaces: &'a [&'a str],
111 body_wrappers: &'a [&'a str],
112 limits: &'a Limits,
113 skipped: usize,
114 depth: usize,
115 nodes: usize,
116 phase: ScanPhase,
117 doc_decls: Vec<(String, String)>,
118 body_decls: Vec<(String, String)>,
119 background_start: Option<usize>,
120 background: Option<Range<usize>>,
121 child_start: Option<usize>,
122 children: Vec<Range<usize>>,
123 has_revisions: bool,
124 has_cross_block_features: bool,
125}
126
127impl<'a> ScanState<'a> {
128 fn new(
129 w_namespaces: &'a [&'a str],
130 body_wrappers: &'a [&'a str],
131 limits: &'a Limits,
132 skipped: usize,
133 ) -> Self {
134 Self {
135 w_namespaces,
136 body_wrappers,
137 limits,
138 skipped,
139 depth: 0,
140 nodes: 0,
141 phase: ScanPhase::BeforeDocument,
142 doc_decls: Vec::new(),
143 body_decls: Vec::new(),
144 background_start: None,
145 background: None,
146 child_start: None,
147 children: Vec::new(),
148 has_revisions: false,
149 has_cross_block_features: false,
150 }
151 }
152
153 fn position(&self, reader: &NsReader<&[u8]>) -> Result<usize, Error> {
154 let pos = usize::try_from(reader.buffer_position())
155 .map_err(|_| Error::TooLarge)?
156 .saturating_add(self.skipped);
157 Ok(pos)
158 }
159
160 fn is_w(&self, resolved: &ResolveResult<'_>) -> bool {
161 matches!(resolved, ResolveResult::Bound(ns) if self.w_namespaces.contains(&ns.as_ref()))
162 }
163
164 fn on_start(
165 &mut self,
166 tag: &BytesStart<'_>,
167 is_w: bool,
168 start: usize,
169 end: usize,
170 empty: bool,
171 ) -> Result<(), Error> {
172 self.nodes += 1;
173 if self.nodes > self.limits.max_nodes {
174 return Err(Error::TooManyNodes);
175 }
176 let next_depth = self.depth + 1;
177 if !empty && next_depth > self.limits.max_depth {
178 return Err(Error::TooDeep);
179 }
180 let local = tag.local_name();
181 let local_str = local.as_ref();
182 match (next_depth, self.phase) {
183 (1, ScanPhase::BeforeDocument) if is_w && local_str == "document" => {
184 self.doc_decls = collect_xmlns(tag)?;
185 if !empty {
186 self.phase = ScanPhase::InDocument;
187 }
188 }
189 (2, ScanPhase::InDocument) if is_w => {
190 self.on_document_child(tag, local_str, start, end, empty)?;
191 }
192 (3, ScanPhase::InBody) => {
193 self.on_body_child(local_str, start, end, empty);
194 }
195 _ => {}
196 }
197 if is_w {
198 self.flag_features(local_str);
199 }
200 if !empty {
201 self.depth = next_depth;
202 }
203 Ok(())
204 }
205
206 fn on_document_child(
207 &mut self,
208 tag: &BytesStart<'_>,
209 local: &str,
210 start: usize,
211 end: usize,
212 empty: bool,
213 ) -> Result<(), Error> {
214 if local == "background" && self.background.is_none() {
215 if empty {
216 self.background = Some(start..end);
217 } else {
218 self.background_start = Some(start);
219 }
220 } else if local == "body" {
221 self.body_decls = collect_xmlns(tag)?;
222 self.phase = if empty {
223 ScanPhase::AfterBody
224 } else {
225 ScanPhase::InBody
226 };
227 }
228 Ok(())
229 }
230
231 fn on_body_child(&mut self, local: &str, start: usize, end: usize, empty: bool) {
232 if empty {
233 self.children.push(start..end);
234 } else {
235 self.child_start = Some(start);
236 }
237 if self.body_wrappers.contains(&local) {
238 self.has_cross_block_features = true;
239 }
240 }
241
242 fn flag_features(&mut self, local: &str) {
243 if matches!(
244 local,
245 "del"
246 | "ins"
247 | "moveFrom"
248 | "moveTo"
249 | "pPrChange"
250 | "rPrChange"
251 | "tblPrChange"
252 | "trPrChange"
253 | "tcPrChange"
254 | "sectPrChange"
255 | "customXmlDelRangeStart"
256 | "customXmlInsRangeStart"
257 | "customXmlMoveFromRangeStart"
258 | "customXmlMoveToRangeStart"
259 ) {
260 self.has_revisions = true;
261 } else if matches!(
262 local,
263 "commentRangeStart"
264 | "commentRangeEnd"
265 | "commentReference"
266 | "fldSimple"
267 | "instrText"
268 ) {
269 self.has_cross_block_features = true;
270 }
271 }
272
273 fn on_end(&mut self, end: usize) {
274 match (self.depth, self.phase) {
275 (3, ScanPhase::InBody) => {
276 if let Some(start) = self.child_start.take() {
277 self.children.push(start..end);
278 }
279 }
280 (2, ScanPhase::InBody) => {
281 self.phase = ScanPhase::AfterBody;
282 }
283 (2, ScanPhase::InDocument) => {
284 if let Some(start) = self.background_start.take() {
285 self.background = Some(start..end);
286 }
287 }
288 _ => {}
289 }
290 self.depth = self.depth.saturating_sub(1);
291 }
292
293 fn finish(self) -> Option<StreamedBody> {
294 if !matches!(self.phase, ScanPhase::InBody | ScanPhase::AfterBody) {
295 return None;
296 }
297 let mut in_scope = self.body_decls;
298 for (prefix, uri) in &self.doc_decls {
299 if in_scope.iter().all(|(known, _)| known != prefix) {
300 in_scope.push((prefix.clone(), uri.clone()));
301 }
302 }
303 Some(StreamedBody {
304 in_scope,
305 doc_in_scope: self.doc_decls,
306 background: self.background,
307 children: self.children,
308 has_revisions: self.has_revisions,
309 has_cross_block_features: self.has_cross_block_features,
310 })
311 }
312}
313
314fn collect_xmlns(tag: &BytesStart<'_>) -> Result<Vec<(String, String)>, Error> {
316 let mut decls = Vec::new();
317 for attr in tag.attributes() {
318 let attr = attr.map_err(|error| Error::Syntax(error.to_string()))?;
319 let key = attr.key;
320 let prefix = match key.prefix() {
321 Some(p) if p.as_ref() == "xmlns" => key.local_name().as_ref().to_owned(),
322 None if key.local_name().as_ref() == "xmlns" => String::new(),
323 _ => continue,
324 };
325 let value = attr
326 .normalized_value(XmlVersion::Implicit1_0)
327 .map_err(|error| Error::Syntax(error.to_string()))?
328 .into_owned();
329 if decls.iter().all(|(known, _)| known != &prefix) {
330 decls.push((prefix, value));
331 }
332 }
333 Ok(decls)
334}
335
336#[cfg(test)]
337mod tests {
338 use super::*;
339 use crate::Document;
340
341 const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
342
343 const WRAPPERS: [&str; 3] = ["customXml", "sdt", "AlternateContent"];
344
345 #[test]
346 fn scans_body_children_with_exact_byte_spans_and_background() {
347 let xml = format!(
348 r#"<?xml version="1.0" encoding="UTF-8"?><w:document xmlns:w="{W}"><w:background w:color="FFEEAA"/><w:body><w:p><w:r><w:t>One</w:t></w:r></w:p><w:tbl/><w:sectPr/></w:body></w:document>"#
349 );
350 let streamed = scan_body_children(xml.as_bytes(), &[W], &WRAPPERS, &Limits::default())
351 .unwrap()
352 .unwrap();
353 assert_eq!(
354 (
355 streamed.has_revisions,
356 streamed.has_cross_block_features,
357 streamed.children.len(),
358 &xml[streamed.background.unwrap()],
359 &xml[streamed.children[0].clone()],
360 &xml[streamed.children[1].clone()],
361 &xml[streamed.children[2].clone()],
362 ),
363 (
364 false,
365 false,
366 3,
367 r#"<w:background w:color="FFEEAA"/>"#,
368 "<w:p><w:r><w:t>One</w:t></w:r></w:p>",
369 "<w:tbl/>",
370 "<w:sectPr/>",
371 )
372 );
373
374 let full = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
376 let full_body = full.child(full.root().unwrap(), W, "body").unwrap();
377 let full_p = full.child(full_body, W, "p").unwrap();
378 let range = streamed.children[0].clone();
379 let frag = Document::parse_fragment_with_aliases_at(
380 &xml.as_bytes()[range.clone()],
381 &streamed.in_scope,
382 &[],
383 range.start as u64,
384 &Limits::default(),
385 )
386 .unwrap();
387 let frag_p = frag.nodes()[0];
388 assert_eq!(
389 frag.document().span(frag_p).unwrap(),
390 full.span(full_p).unwrap()
391 );
392 }
393
394 #[test]
395 fn flags_revisions_and_cross_block_features() {
396 let rev_xml = format!(
397 r#"<w:document xmlns:w="{W}"><w:body><w:p><w:ins><w:r><w:t>hi</w:t></w:r></w:ins></w:p></w:body></w:document>"#
398 );
399 let streamed = scan_body_children(rev_xml.as_bytes(), &[W], &WRAPPERS, &Limits::default())
400 .unwrap()
401 .unwrap();
402 assert!(streamed.has_revisions);
403
404 let toc_xml = format!(
405 r#"<w:document xmlns:w="{W}"><w:body><w:p><w:r><w:instrText>TOC</w:instrText></w:r></w:p></w:body></w:document>"#
406 );
407 let streamed = scan_body_children(toc_xml.as_bytes(), &[W], &WRAPPERS, &Limits::default())
408 .unwrap()
409 .unwrap();
410 assert!(streamed.has_cross_block_features);
411
412 let custom_xml = format!(
413 r#"<w:document xmlns:w="{W}"><w:body><w:customXml><w:p><w:r><w:t>inside</w:t></w:r></w:p></w:customXml></w:body></w:document>"#
414 );
415 let streamed =
416 scan_body_children(custom_xml.as_bytes(), &[W], &WRAPPERS, &Limits::default())
417 .unwrap()
418 .unwrap();
419 assert!(streamed.has_cross_block_features);
420 }
421}