diff --git a/crates/xlsx/src/xlsb.rs b/crates/xlsx/src/xlsb.rs index 5fe881322..c8fdba69f 100644 --- a/crates/xlsx/src/xlsb.rs +++ b/crates/xlsx/src/xlsb.rs @@ -30,6 +30,9 @@ pub(crate) const STRINGS: &str = "application/vnd.ms-excel.sharedStrings"; pub(crate) const STYLES: &str = "application/vnd.ms-excel.styles"; /// Most sheets in the workbook. const MAX_SHEETS: usize = 1024; +/// Supporting links (this workbook, add-ins, other workbooks) read at most; past it, formulas +/// keep their saved results. +const MAX_BOOKS: usize = 65_536; /// Most merged ranges in one worksheet. const MAX_MERGES: usize = 100_000; /// Defined names (Excel's hidden ones for newer functions included) read at most; past it, the @@ -287,6 +290,9 @@ pub(crate) fn workbook( let mut links = Some(Links::default()); let mut bundle = false; let mut bundle_seen = false; + // Every BrtBundleSh counts toward the cap, a skipped module sheet too: each keeps a place + // in the sheet links. + let mut bundle_count = 0usize; while let Some((id, payload)) = records.next(warnings)? { let mut b = Bytes::new(payload); match id { @@ -335,9 +341,10 @@ pub(crate) fn workbook( if !bundle { return Err(invalid("worksheet outside the worksheet list")); } - if wb.sheets.len() >= MAX_SHEETS { + if bundle_count >= MAX_SHEETS { return Err(Error::TooLarge(format!("XLSB exceeds {MAX_SHEETS} sheets"))); } + bundle_count += 1; let visibility = match b.u32()? { 0 => Visibility::Visible, 1 => Visibility::Hidden, @@ -387,6 +394,9 @@ pub(crate) fn workbook( /// (`BrtExternSheet`) or a defined name (`BrtName`), added to `links`. fn link_record(id: u16, payload: &[u8], links: &mut Links) -> Result<(), Error> { let mut b = Bytes::new(payload); + if matches!(id, 355 | 357 | 358 | 667) && links.books.len() >= MAX_BOOKS { + return Err(invalid("too many supporting links")); + } match id { 357 | 358 | 667 => { b.finish()?; diff --git a/crates/xlsx/src/xlsb/formula.rs b/crates/xlsx/src/xlsb/formula.rs index b62072ad2..a7293c0df 100644 --- a/crates/xlsx/src/xlsb/formula.rs +++ b/crates/xlsx/src/xlsb/formula.rs @@ -583,10 +583,13 @@ fn literal_text(e: &Expr) -> bool { } } -/// How many strings a [`literal_text`] chain joins, or `None` for anything else. +/// How many strings a [`literal_text`] chain joins, or `None` for anything else. It accepts +/// what [`literal_text`] does, typed spacing included, so a chain the Python check accepts is +/// one that is written flat. fn literal_texts(e: &Expr) -> Option { match e { Expr::Text(_) => Some(1), + Expr::Spaced(_, x, _) => literal_texts(x), Expr::Binary(BinOp::Concat, a, b) => literal_texts(a)?.checked_add(literal_texts(b)?), _ => None, } @@ -605,13 +608,24 @@ fn binding(e: &Expr) -> u8 { } } -/// The strings of a [`literal_text`] chain, left to right. +/// The strings of a [`literal_text`] chain, left to right. Spacing typed around a part of the +/// chain stays with that part's first and last strings, where it is written. fn flatten_texts(e: Expr, out: &mut Vec) { match e { Expr::Binary(BinOp::Concat, a, b) => { flatten_texts(*a, out); flatten_texts(*b, out); } + Expr::Spaced(before, x, after) if matches!(*x, Expr::Binary(BinOp::Concat, ..)) => { + let start = out.len(); + flatten_texts(*x, out); + if let Some(first) = out.get_mut(start) { + *first = spaced_before(std::mem::replace(first, Expr::Missing), before); + } + if let Some(last) = out.last_mut() { + *last = spaced_after(std::mem::replace(last, Expr::Missing), after); + } + } text => out.push(text), } } @@ -716,6 +730,18 @@ mod tests { } } + #[test] + fn a_spaced_part_of_a_string_chain_is_written_flat() { + // `"x"`, then `"="` typed with a space before it joined to `"1"`, then joined: the tokens + // nest to the right, and the space is on the inner chain. Written flat, as Python code + // must be, with the space where it was typed. + let s = |c: u8| [0x17, 1, 0, c, 0]; + let rgce = [&s(b'x')[..], &[0x19, 0x40, 0, 1], &s(b'=')[..], &s(b'1')[..], &[0x08, 0x08]].concat(); + let e = decode(&rgce, &[], &Links::default(), Mode::Cell).unwrap(); + assert_eq!(super::super::expr::print(&e), "\"x\"& \"=\"&\"1\""); + assert!(literal_text(&e) && literal_texts(&e) == Some(3)); + } + #[test] fn a_long_chain_of_strings_stays_within_the_depth_bound() { // 4,096 strings and 4,095 `&` fill 16,383 token bytes, 13 levels deep as written. Made diff --git a/crates/xlsx/tests/xlsb.rs b/crates/xlsx/tests/xlsb.rs index b72705b9f..18a833388 100644 --- a/crates/xlsx/tests/xlsb.rs +++ b/crates/xlsx/tests/xlsb.rs @@ -1349,3 +1349,21 @@ fn differential_format_strings_are_charged_to_the_text_allowance() { assert!(open(&dxf("Arial")).is_ok_and(|s| s.is_some_and(|s| s.dxfs.len() == 1))); assert!(matches!(open(&dxf(&"x".repeat(200))), Err(Error::TooLarge(_)))); } + +#[test] +fn module_sheets_and_supporting_links_are_bounded() { + // 1,025 very hidden module sheets (no relationship) before the worksheets: each keeps a place + // in the sheet links, so together they are past the 1,024-sheet cap. + let plain = book(false); + let at = plain.windows(3).position(|w| w == record(143, &[]).as_slice()).unwrap() + 3; + let module = record(156, &[&2u32.to_le_bytes()[..], &9u32.to_le_bytes(), &u32::MAX.to_le_bytes(), &wide("Module")].concat()); + let modules = [&plain[..at], &module.repeat(1025), &plain[at..]].concat(); + assert!(matches!(read(&package(&modules, &worksheet(&[], &[]), &sst(), ROOT, RELS, TYPES)), Err(Error::TooLarge(_)))); + // 65,537 supporting links: past the cap the links aren't read, and formulas keep their values. + let end = record(132, &[]); + let selves = [&plain[..plain.len() - end.len()], &record(353, &[]), &record(357, &[]).repeat(65_537), &record(354, &[]), &end].concat(); + let data = [row(0), formula_cell(0, &[0x1E, 1, 0], &[])].concat(); + let wb = read(&package(&selves, &worksheet(&data, &[]), &sst(), ROOT, RELS, TYPES)).unwrap(); + assert_eq!(wb.sheets[0].formula(CellRef::new(0, 0)), None); + assert!(wb.warnings.iter().any(|w| w.contains("sheet links or names could not be read")), "{:?}", wb.warnings); +}