Skip to content

Commit 163a259

Browse files
committed
Merge PR #480 from NikitkaRa: Pptx: budget chart points, chart XML size, inflate work and VML lookups (#401)
2 parents 215fed0 + d2066a1 commit 163a259

5 files changed

Lines changed: 190 additions & 26 deletions

File tree

‎crates/pptx/src/opc.rs‎

Lines changed: 60 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ pub const MAX_PART: u64 = 512 * 1024 * 1024;
1212
pub const MAX_XML_PART: usize = 96 * 1024 * 1024;
1313
/// Total decompressed bytes accepted for one package.
1414
pub const MAX_TOTAL: u64 = 2 * 1024 * 1024 * 1024;
15+
/// Total bytes we are willing to decompress for one package, counting parts we then discard
16+
/// (too large, or failing part-way): bounds inflate work, not just what is kept.
17+
pub const MAX_INFLATE_WORK: u64 = 2 * MAX_TOTAL;
1518
/// Maximum number of zip entries.
1619
pub const MAX_ENTRIES: usize = 50_000;
1720

@@ -38,13 +41,22 @@ pub struct Package {
3841

3942
impl Package {
4043
pub fn open(bytes: &[u8]) -> Result<Self, PptxError> {
44+
Self::open_within(bytes, MAX_PART, MAX_TOTAL, MAX_INFLATE_WORK)
45+
}
46+
/// [`Package::open`] with explicit limits: per part, kept in total, and inflated in total.
47+
fn open_within(bytes: &[u8], max_part: u64, max_total: u64, max_work: u64) -> Result<Self, PptxError> {
4148
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| PptxError::NotPptx(format!("{e}")))?;
4249
if zip.len() > MAX_ENTRIES {
4350
return Err(PptxError::NotPptx(format!("too many entries ({})", zip.len())));
4451
}
4552
let mut parts = HashMap::new();
4653
let mut total: u64 = 0;
54+
let mut work: u64 = 0;
4755
for i in 0..zip.len() {
56+
if work >= max_work {
57+
log::warn!("pptx: decompression budget spent; skipping the remaining {} entries", zip.len() - i);
58+
break;
59+
}
4860
let mut f = match zip.by_index(i) {
4961
Ok(f) => f,
5062
Err(e) => {
@@ -57,13 +69,16 @@ impl Package {
5769
}
5870
let name = f.name().trim_start_matches('/').to_string();
5971
let declared = f.size();
60-
if declared > MAX_PART {
72+
if declared > max_part {
6173
log::warn!("pptx: skipping oversized part {name} ({declared} bytes)");
6274
continue;
6375
}
6476
let mut data = Vec::with_capacity(declared.min(16 * 1024 * 1024) as usize);
65-
let cap = MAX_PART.min(MAX_TOTAL.saturating_sub(total));
66-
match (&mut f).take(cap.saturating_add(1)).read_to_end(&mut data) {
77+
let cap = max_part.min(max_total.saturating_sub(total)).min(max_work.saturating_sub(work));
78+
let read = (&mut f).take(cap.saturating_add(1)).read_to_end(&mut data);
79+
// Charge what was inflated whether or not the part is kept.
80+
work = work.saturating_add(data.len() as u64);
81+
match read {
6782
Ok(_) if data.len() as u64 > cap => {
6883
log::warn!("pptx: part {name} exceeds size limits; skipped");
6984
continue;
@@ -82,6 +97,15 @@ impl Package {
8297
pub fn get(&self, name: &str) -> Option<&[u8]> {
8398
self.parts.get(&norm(name)).map(|(_, d)| d.as_slice())
8499
}
100+
/// An XML part's bytes, when it is within the XML size limit.
101+
pub fn xml_bytes(&self, name: &str) -> Option<&[u8]> {
102+
let b = self.get(name)?;
103+
if b.len() > MAX_XML_PART {
104+
log::warn!("pptx: XML part {name} too large");
105+
return None;
106+
}
107+
Some(b)
108+
}
85109
/// Parse an XML part.
86110
pub fn xml(&self, name: &str) -> Option<xml::Doc> {
87111
let b = self.get(name)?;
@@ -354,6 +378,39 @@ impl PackageOut {
354378
mod tests {
355379
use super::*;
356380

381+
fn zip_of(entries: &[(&str, usize)]) -> Vec<u8> {
382+
let mut zw = zip::ZipWriter::new(Cursor::new(Vec::new()));
383+
let o = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
384+
for (name, len) in entries {
385+
zw.start_file(*name, o).unwrap();
386+
zw.write_all(&vec![b'x'; *len]).unwrap();
387+
}
388+
zw.finish().unwrap().into_inner()
389+
}
390+
391+
#[test]
392+
fn discarded_parts_count_against_the_inflate_budget() {
393+
// Kept bytes cap at 100: b, c and d are inflated past what's left and discarded. That
394+
// work is charged, so after d the budget (130) is spent and e is not read, although it
395+
// would have fit.
396+
let z = zip_of(&[("a", 80), ("b", 80), ("c", 80), ("d", 80), ("e", 5)]);
397+
let p = Package::open_within(&z, 1000, 100, 130).unwrap();
398+
assert!(p.get("a").is_some());
399+
assert!(p.get("b").is_none() && p.get("d").is_none());
400+
assert!(p.get("e").is_none(), "the inflate budget stops reading");
401+
// With room to spare the same small part is kept.
402+
let p = Package::open_within(&z, 1000, 100, 10_000).unwrap();
403+
assert!(p.get("e").is_some());
404+
}
405+
406+
#[test]
407+
fn xml_bytes_applies_the_xml_limit() {
408+
let z = zip_of(&[("small.xml", 10)]);
409+
let p = Package::open(&z).unwrap();
410+
assert_eq!(p.xml_bytes("small.xml").map(<[u8]>::len), Some(10));
411+
assert!(p.xml_bytes("missing.xml").is_none());
412+
}
413+
357414
#[test]
358415
fn path_resolution() {
359416
assert_eq!(resolve("ppt/slides", "../media/image1.png"), "ppt/media/image1.png");

‎crates/pptx/src/read/chart.rs‎

Lines changed: 63 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -35,19 +35,34 @@ fn rich_text(t: &El) -> Option<String> {
3535
tx.find("v").map(|v| v.text())
3636
}
3737

38-
/// String values from `c:cat`/`c:tx` (str or num refs, caches or literals).
39-
fn strings(e: &El) -> Vec<String> {
38+
/// Most category/value/size slots one chart may decode across all its series and caches, so
39+
/// sparse `ptCount`/`idx` declarations can't expand far beyond the XML they came from.
40+
pub(crate) const MAX_CHART_POINTS: usize = 1_000_000;
41+
42+
/// Most slots one cache may hold.
43+
const MAX_CACHE_POINTS: usize = 100_000;
44+
45+
/// String values from `c:cat`/`c:tx` (str or num refs, caches or literals). Every slot returned
46+
/// is taken from `budget`; once it runs out the values are cut short.
47+
fn strings(e: &El, budget: &mut usize) -> Vec<String> {
48+
let cap = MAX_CACHE_POINTS.min(*budget);
49+
let out = strings_capped(e, cap);
50+
*budget = budget.saturating_sub(out.len());
51+
out
52+
}
53+
54+
fn strings_capped(e: &El, cap: usize) -> Vec<String> {
4055
let cache = e.find("strCache").or_else(|| e.find("numCache")).or_else(|| e.find("strLit")).or_else(|| e.find("numLit"));
4156
if let Some(c) = cache {
42-
let n = c.child("ptCount").and_then(|p| p.u32("val")).unwrap_or(0).min(100_000) as usize;
57+
let n = (c.child("ptCount").and_then(|p| p.u32("val")).unwrap_or(0) as usize).min(cap);
4358
let mut out = vec![String::new(); n];
44-
for pt in c.children_named("pt").take(100_000) {
59+
for pt in c.children_named("pt").take(MAX_CACHE_POINTS) {
4560
let i = pt.u32("idx").unwrap_or(0) as usize;
61+
if i >= cap {
62+
continue;
63+
}
4664
let v = pt.child("v").map(|v| v.text()).unwrap_or_default();
4765
if i >= out.len() {
48-
if i >= 100_000 {
49-
continue;
50-
}
5166
out.resize(i + 1, String::new());
5267
}
5368
if let Some(s) = out.get_mut(i) {
@@ -59,17 +74,19 @@ fn strings(e: &El) -> Vec<String> {
5974
if let Some(ml) = e.find("multiLvlStrCache") {
6075
// Use the innermost level.
6176
if let Some(l) = ml.child("lvl") {
62-
return l.children_named("pt").map(|p| p.child("v").map(|v| v.text()).unwrap_or_default()).collect();
77+
return l.children_named("pt").take(cap).map(|p| p.child("v").map(|v| v.text()).unwrap_or_default()).collect();
6378
}
6479
}
65-
if let Some(v) = e.child("v") {
80+
if cap > 0
81+
&& let Some(v) = e.child("v")
82+
{
6683
return vec![v.text()];
6784
}
6885
vec![]
6986
}
7087

71-
fn numbers(e: &El) -> Vec<Option<f64>> {
72-
strings(e).into_iter().map(|s| s.trim().parse::<f64>().ok().filter(|v| v.is_finite())).collect()
88+
fn numbers(e: &El, budget: &mut usize) -> Vec<Option<f64>> {
89+
strings(e, budget).into_iter().map(|s| s.trim().parse::<f64>().ok().filter(|v| v.is_finite())).collect()
7390
}
7491

7592
/// Parse a chart part. Returns `None` for something that isn't a chart we can read.
@@ -86,6 +103,11 @@ pub fn read_chart_xml(bytes: &[u8]) -> Option<Chart> {
86103
}
87104

88105
pub(crate) fn chart_from(root: &El) -> Option<Chart> {
106+
chart_within(root, MAX_CHART_POINTS)
107+
}
108+
109+
/// [`chart_from`] decoding at most `budget` data slots in all.
110+
fn chart_within(root: &El, mut budget: usize) -> Option<Chart> {
89111
let ch = root.child("chart")?;
90112
let pa = ch.child("plotArea")?;
91113
let mut c = Chart { categories: vec![], series: vec![], title: None, legend: None, gridlines: false, ..Default::default() };
@@ -190,7 +212,7 @@ pub(crate) fn chart_from(root: &El) -> Option<Chart> {
190212
let secondary = val_axis.is_some() && val_axis != primary_val;
191213
for s in g.children_named("ser").take(1000) {
192214
let mut ser = Series {
193-
name: s.child("tx").map(strings).and_then(|v| v.into_iter().next()).unwrap_or_default(),
215+
name: s.child("tx").map(|t| strings(t, &mut budget)).and_then(|v| v.into_iter().next()).unwrap_or_default(),
194216
fill: simple_fill(s.child("spPr")),
195217
line: simple_line(s.child("spPr")),
196218
smooth: s.child("smooth").and_then(|v| v.bool("val")).unwrap_or(false),
@@ -218,7 +240,7 @@ pub(crate) fn chart_from(root: &El) -> Option<Chart> {
218240
}
219241
}
220242
if let Some(cat) = s.child("cat").or_else(|| s.child("xVal")) {
221-
let cats = strings(cat);
243+
let cats = strings(cat, &mut budget);
222244
if matches!(kind, ChartType::Scatter | ChartType::Bubble) {
223245
ser.x_values = cats.iter().map(|v| v.trim().parse::<f64>().ok()).collect();
224246
}
@@ -227,10 +249,10 @@ pub(crate) fn chart_from(root: &El) -> Option<Chart> {
227249
}
228250
}
229251
if let Some(v) = s.child("val").or_else(|| s.child("yVal")) {
230-
ser.values = numbers(v);
252+
ser.values = numbers(v, &mut budget);
231253
}
232254
if let Some(b) = s.child("bubbleSize") {
233-
ser.sizes = numbers(b);
255+
ser.sizes = numbers(b, &mut budget);
234256
}
235257
c.series.push(ser);
236258
}
@@ -310,6 +332,32 @@ fn text_size(e: Option<&El>) -> Option<f64> {
310332
mod tests {
311333
use super::*;
312334

335+
#[test]
336+
fn sparse_caches_share_one_chart_wide_budget() {
337+
// Every series declares 100000 points but writes one: without a chart-wide budget each
338+
// would expand to the full count.
339+
let ser = |n: usize| {
340+
format!(
341+
r#"<c:ser><c:idx val="{n}"/><c:val><c:numRef><c:numCache><c:ptCount val="100000"/><c:pt idx="0"><c:v>{n}</c:v></c:pt></c:numCache></c:numRef></c:val></c:ser>"#
342+
)
343+
};
344+
let sers: String = (0..5).map(ser).collect();
345+
let xml = format!(
346+
r#"<c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart"><c:chart><c:plotArea><c:barChart><c:barDir val="col"/>{sers}</c:barChart></c:plotArea></c:chart></c:chartSpace>"#
347+
);
348+
let doc = crate::xml::parse(xml.as_bytes()).unwrap();
349+
let c = chart_within(&doc.root, 250_000).unwrap();
350+
let total: usize = c.series.iter().map(|s| s.values.len()).sum();
351+
assert!(total <= 250_000, "{total}");
352+
assert_eq!(c.series.len(), 5);
353+
assert_eq!(c.series[0].values.len(), 100_000);
354+
assert_eq!(c.series[0].values[0], Some(0.0));
355+
assert!(c.series[4].values.is_empty(), "the budget ran out before the last series");
356+
// A small chart is untouched by the default budget.
357+
let c = chart_from(&doc.root).unwrap();
358+
assert!(c.series.iter().all(|s| s.values.len() == 100_000));
359+
}
360+
313361
#[test]
314362
fn legend_position_and_overlay_are_read() {
315363
let legend = r#"<c:legend><c:legendPos val="r"/><c:overlay val="1"/></c:legend>"#;

‎crates/pptx/src/read/mod.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ pub struct Imp<'a> {
3232
pub custom_show_names: HashMap<String, String>,
3333
/// GUIDs (upper case) of the table styles the file defines.
3434
pub table_style_ids: Vec<String>,
35+
/// Per legacy VML drawing part: shape id → preview picture part (see `shapes::vml_preview`).
36+
pub vml_previews: HashMap<String, HashMap<String, String>>,
3537
}
3638

3739
impl Imp<'_> {
@@ -269,6 +271,7 @@ pub fn import(bytes: &[u8]) -> Result<Presentation, PptxError> {
269271
slide_by_part: HashMap::new(),
270272
custom_show_names: HashMap::new(),
271273
table_style_ids: Vec::new(),
274+
vml_previews: HashMap::new(),
272275
};
273276
// Slide ids first so hyperlinks anywhere can point at slides.
274277
let mut slide_ids: Vec<(u32, String, SlideId)> = vec![];

‎crates/pptx/src/read/shapes.rs‎

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,7 @@ fn frame(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El, depth: usize) -> S
367367
}
368368
if let Some(c) = gd.child("chart")
369369
&& let Some(rel) = part.rels.get(c.attr("r:id").unwrap_or(""))
370-
&& let Some(bytes) = imp.pkg.get(&rel.target)
370+
&& let Some(bytes) = imp.pkg.xml_bytes(&rel.target)
371371
&& let Some(chart) = super::read_chart_xml(bytes)
372372
{
373373
s.kind = ShapeKind::Chart(Box::new(chart));
@@ -403,17 +403,39 @@ fn frame(imp: &mut Imp, part: &Part, ctx: &mut IdCtx, e: &El, depth: usize) -> S
403403
/// `v:imagedata` of the legacy VML drawing shape with that id, as PowerPoint 2007 wrote them.
404404
fn vml_preview(imp: &mut Imp, part: &Part, spid: &str) -> Option<deckcraft_model::MediaId> {
405405
for rel in part.rels.items.iter().filter(|r| r.kind == "vmlDrawing" && !r.external) {
406-
let Some(doc) = imp.pkg.xml(&rel.target) else { continue };
407-
let mut shapes = vec![];
408-
doc.root.find_all("shape", &mut shapes);
409-
let Some(img) = shapes.into_iter().find(|s| s.attr("id") == Some(spid)).and_then(|s| s.find("imagedata")) else { continue };
410-
let Some(id) = img.attr("o:relid").or(img.attr("r:id")) else { continue };
411-
let target = imp.pkg.rels(&rel.target).get(id).filter(|r| !r.external).map(|r| r.target.clone())?;
406+
let key = crate::opc::norm(&rel.target);
407+
if !imp.vml_previews.contains_key(&key) {
408+
let index = vml_index(imp.pkg, &rel.target);
409+
imp.vml_previews.insert(key.clone(), index);
410+
}
411+
let Some(target) = imp.vml_previews.get(&key).and_then(|m| m.get(spid)).cloned() else { continue };
412412
return imp.media_for(&target);
413413
}
414414
None
415415
}
416416

417+
/// Every shape id in a VML drawing with a picture, mapped to that picture's part: parsed once per
418+
/// drawing however many objects look it up.
419+
fn vml_index(pkg: &crate::opc::Package, vml: &str) -> std::collections::HashMap<String, String> {
420+
let mut out = std::collections::HashMap::new();
421+
let Some(doc) = pkg.xml(vml) else { return out };
422+
let rels = pkg.rels(vml);
423+
let mut shapes = vec![];
424+
doc.root.find_all("shape", &mut shapes);
425+
for s in shapes {
426+
let Some(id) = s.attr("id") else { continue };
427+
if out.contains_key(id) {
428+
continue; // the first shape with an id wins, as the old lookup did
429+
}
430+
let Some(img) = s.find("imagedata") else { continue };
431+
let Some(rid) = img.attr("o:relid").or(img.attr("r:id")) else { continue };
432+
if let Some(r) = rels.get(rid).filter(|r| !r.external) {
433+
out.insert(id.to_string(), r.target.clone());
434+
}
435+
}
436+
out
437+
}
438+
417439
/// SmartArt: read the pre-drawn shapes of its drawing part as a group.
418440
fn smartart(imp: &mut Imp, part: &Part, gd: &El, frame: &Shape, depth: usize) -> Option<Shape> {
419441
let rel_ids = gd.child("relIds")?;

‎crates/pptx/tests/ole_vml.rs‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,11 @@ fn png(v: u8) -> Vec<u8> {
2727

2828
/// A new deck whose first slide holds [`FRAME`], with the VML drawing, its rels and two pictures.
2929
fn deck() -> Vec<u8> {
30+
deck_with(FRAME)
31+
}
32+
33+
/// [`deck`] with `frames` in place of [`FRAME`].
34+
fn deck_with(frames: &str) -> Vec<u8> {
3035
let bytes = deckcraft_pptx::export(&defaults::new_presentation(None)).expect("export");
3136
let mut z = zip::ZipArchive::new(Cursor::new(bytes)).expect("zip");
3237
let mut out = zip::ZipWriter::new(Cursor::new(Vec::new()));
@@ -39,7 +44,7 @@ fn deck() -> Vec<u8> {
3944
if name == "ppt/slides/slide1.xml" {
4045
let s = String::from_utf8(d).expect("utf8");
4146
let at = s.rfind("</p:spTree>").expect("spTree");
42-
let s = format!("{}{FRAME}{}", &s[..at], &s[at..]);
47+
let s = format!("{}{frames}{}", &s[..at], &s[at..]);
4348
let at = s.rfind("</p:cSld>").expect("cSld");
4449
d = format!("{}{CONTROLS}{}", &s[..at], &s[at..]).into_bytes();
4550
} else if name == "ppt/slides/_rels/slide1.xml.rels" {
@@ -82,3 +87,32 @@ fn activex_controls_show_their_pictures() {
8287
assert_eq!((x.x, x.y, x.w, x.h), (1.0, 2.0, 10.0, 5.0));
8388
assert!(!p.slides[0].shapes.iter().any(|s| s.name == "NoPicture"), "a control without a picture draws nothing");
8489
}
90+
91+
#[test]
92+
fn many_objects_sharing_one_vml_drawing_each_get_their_preview() {
93+
// 200 frames look up the same drawing (it is parsed once); every other one names a shape id
94+
// the drawing doesn't have.
95+
let frames: String = (0..200)
96+
.map(|i| {
97+
let spid = match i % 4 {
98+
0 => "_x0000_s2050",
99+
1 => "_x0000_s9999",
100+
2 => "_x0000_s2049",
101+
_ => "missing",
102+
};
103+
FRAME.replace("id=\"90\" name=\"Object 3\"", &format!("id=\"{}\" name=\"Obj {i}\"", 1000 + i)).replace("_x0000_s2050", spid)
104+
})
105+
.collect();
106+
let p = deckcraft_pptx::import(&deck_with(&frames)).expect("import");
107+
for i in 0..200 {
108+
let s = p.slides[0].shapes.iter().find(|s| s.name == format!("Obj {i}")).expect("frame");
109+
let ShapeKind::Opaque { preview, .. } = &s.kind else { panic!("{:?}", s.kind) };
110+
let name = preview.and_then(|m| p.media.iter().find(|x| x.id == m)).map(|m| m.name.as_str());
111+
let want = match i % 4 {
112+
0 => Some("preview.png"),
113+
2 => Some("other.png"),
114+
_ => None,
115+
};
116+
assert_eq!(name, want, "frame {i}");
117+
}
118+
}

0 commit comments

Comments
 (0)