Skip to content
Merged
4 changes: 4 additions & 0 deletions crates/xlsx/src/read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ pub struct Ctx<'a> {
pub cell_pictures: Vec<Option<Arc<CellPicture>>>,
/// x14 conditional-format ids of the current sheet's data bars, with the index of the rule in `cond_formats`.
pub cf_ext_ids: Vec<(String, usize)>,
/// Bytes charged so far for shared formulas expanded into dependent cells (see
/// [`crate::sheet_read::MAX_SHARED_FORMULA_BYTES`]).
pub shared_formula_bytes: u64,
}

impl Ctx<'_> {
Expand Down Expand Up @@ -82,6 +85,7 @@ pub fn read_xlsx(bytes: &[u8]) -> Result<(Workbook, ReadReport), IoError> {
num_fmts: Default::default(),
cell_pictures: vec![],
cf_ext_ids: vec![],
shared_formula_bytes: 0,
};
let root_rels = cx.pkg.rels("")?;
let wb_part = find_rel(&root_rels, "officeDocument").map(|r| r.target.clone()).unwrap_or_else(|| "xl/workbook.xml".into());
Expand Down
121 changes: 110 additions & 11 deletions crates/xlsx/src/sheet_read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ struct Shared {
anchor: CellRef,
expr: Option<Expr>,
text: String,
/// Approximate bytes one dependent cell costs (its printed text plus its expression tree),
/// charged against [`MAX_SHARED_FORMULA_BYTES`].
cost: u64,
}

#[derive(Default)]
Expand All @@ -37,7 +40,18 @@ struct RowState {
rows: u64,
}

/// Most cells one sheet's hyperlinks may cover (each cell gets its own copy of the link).
const MAX_HYPERLINK_CELLS: u64 = 10_000;
/// Longest hyperlink target kept, in bytes (Excel's own limit is about 2,079 characters).
const MAX_HYPERLINK_TARGET: usize = 8_192;
/// Longest hyperlink ScreenTip kept, in characters (Excel's limit).
const MAX_TOOLTIP_CHARS: usize = 255;
/// Most range references one sheet's conditional formats may copy: every rule after the first in
/// a `<conditionalFormatting>` block copies the block's `sqref`.
const MAX_CF_RANGE_COPIES: usize = 1_000_000;
/// Budget, per workbook, for shared formulas expanded into their dependent cells: each dependent
/// costs a copy of the master's text and expression tree.
pub const MAX_SHARED_FORMULA_BYTES: u64 = 2 << 30;

pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<Sheet, IoError> {
let bytes = cx.pkg.read(part)?.ok_or_else(|| IoError::Format(format!("missing part {part}")))?;
Expand All @@ -61,6 +75,8 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<Sheet, IoE
drop(bytes);

let mut fit_to_page = false;
let mut link_cells = 0u64;
let mut cf_copies = 0usize;
cx.cf_ext_ids.clear();
for e in &root.children {
match e.name.as_str() {
Expand Down Expand Up @@ -98,15 +114,15 @@ pub fn read_sheet(cx: &mut Ctx<'_>, part: &str, name: &str) -> Result<Sheet, IoE
}
}
}
"conditionalFormatting" => read_cf(cx, e, &mut sheet),
"conditionalFormatting" => read_cf(cx, e, &mut sheet, &mut cf_copies),
"dataValidations" => {
for v in e.kids("dataValidation") {
if let Some(v) = read_validation(v) {
sheet.validations.push(v);
}
}
}
"hyperlinks" => read_hyperlinks(cx, name, e, &rels, &mut sheet),
"hyperlinks" => read_hyperlinks(cx, name, e, &rels, &mut sheet, &mut link_cells),
"autoFilter" => sheet.autofilter = read_autofilter(cx, e),
"printOptions" => {
sheet.print.gridlines = e.flag("gridLines", false);
Expand Down Expand Up @@ -463,13 +479,25 @@ fn read_formula(cx: &mut Ctx<'_>, st: &mut RowState, f: &El, pos: CellRef, dynam
let si = f.attr_u32("si")?;
if !text.is_empty() {
let expr = gridcraft_formula::parse(text).ok();
st.shared.insert(si, Shared { anchor: pos, expr, text: text.to_string() });
let cost = shared_cost(text, expr.as_ref());
st.shared.insert(si, Shared { anchor: pos, expr, text: text.to_string(), cost });
Some(Formula::new(text))
} else {
let Some(sh) = st.shared.get(&si) else {
cx.warn("a shared formula refers to a missing master cell; kept the cached value");
return None;
};
if sh.expr.is_none() && sh.text.len() > gridcraft_formula::MAX_FORMULA_LEN {
cx.warn(format!(
"a shared formula is longer than {} characters; kept the cached values of the cells that share it",
gridcraft_formula::MAX_FORMULA_LEN
));
return None;
}
if !charge(&mut cx.shared_formula_bytes, sh.cost, MAX_SHARED_FORMULA_BYTES) {
cx.warn("shared formulas expand to too much data; kept the cached values of the remaining cells that share them");
return None;
}
Some(match &sh.expr {
Some(e) => {
let dr = pos.row as i64 - sh.anchor.row as i64;
Expand Down Expand Up @@ -542,6 +570,35 @@ pub fn parse_iso_datetime(s: &str, sys: DateSystem) -> Option<f64> {
Some(serial)
}

/// What one dependent of a shared formula costs: its printed text plus its expression tree.
fn shared_cost(text: &str, expr: Option<&Expr>) -> u64 {
let mut nodes = 0u64;
if let Some(e) = expr {
e.walk(&mut |_| nodes = nodes.saturating_add(1));
}
let node = std::mem::size_of::<Expr>() as u64;
(text.len() as u64).saturating_mul(2).saturating_add(nodes.saturating_mul(node)).saturating_add(64)
}

/// Adds `cost` to `used` when that stays within `cap`; `false` (and `used` unchanged) otherwise.
fn charge(used: &mut u64, cost: u64, cap: u64) -> bool {
match used.checked_add(cost) {
Some(total) if total <= cap => {
*used = total;
true
}
_ => false,
}
}

/// The first `max` characters of `s`.
fn truncate_chars(s: &str, max: usize) -> String {
match s.char_indices().nth(max) {
Some((at, _)) => s.get(..at).unwrap_or(s).to_string(),
None => s.to_string(),
}
}

pub fn parse_sqref(s: Option<&str>) -> Vec<RangeRef> {
s.unwrap_or("").split_whitespace().filter_map(RangeRef::parse).collect()
}
Expand Down Expand Up @@ -588,12 +645,26 @@ fn cfvos(e: &El) -> Vec<CfValueKind> {
.collect()
}

fn read_cf(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) {
/// `copies` counts the range references this sheet's conditional formats have copied so far.
fn read_cf(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet, copies: &mut usize) {
let ranges = parse_sqref(e.attr("sqref"));
if ranges.is_empty() {
return;
}
let mut first = true;
for r in e.kids("cfRule") {
// The first rule takes the parsed ranges as read; each further rule copies them.
if !first {
match copies.checked_add(ranges.len()) {
Some(total) if total <= MAX_CF_RANGE_COPIES => *copies = total,
Comment thread
Higgs32584 marked this conversation as resolved.
Resolved
_ => {
cx.warn(format!(
"conditional formats cover too many ranges; rules past the first {MAX_CF_RANGE_COPIES} range copies were dropped"
));
return;
}
}
}
let style = Box::new(r.attr_u32("dxfId").and_then(|i| cx.dxfs.get(i as usize)).cloned().unwrap_or_default());
let formulas: Vec<String> = r.kids("formula").map(|f| from_file(f.text.trim())).collect();
let f0 = formulas.first().cloned().unwrap_or_default();
Expand Down Expand Up @@ -657,6 +728,7 @@ fn read_cf(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) {
if let Some(id) = ext_id {
cx.cf_ext_ids.push((id, sheet.cond_formats.len()));
}
first = false;
sheet.cond_formats.push(CondFormat {
ranges: ranges.clone(),
rule,
Expand Down Expand Up @@ -717,14 +789,21 @@ fn read_validation(v: &El) -> Option<Validation> {
})
}

fn read_hyperlinks(cx: &mut Ctx<'_>, name: &str, e: &El, rels: &[Rel], sheet: &mut Sheet) {
let mut cells = 0u64;
/// `cells` counts the cells this sheet's hyperlinks cover so far, across `<hyperlinks>` blocks.
fn read_hyperlinks(cx: &mut Ctx<'_>, name: &str, e: &El, rels: &[Rel], sheet: &mut Sheet, cells: &mut u64) {
for h in e.kids("hyperlink") {
let Some(range) = h.attr("ref").and_then(RangeRef::parse) else { continue };
let mut target = h.attr("id").and_then(|id| rels.iter().find(|r| r.id == id)).map(|r| r.target.clone()).unwrap_or_default();
let rel_target = h.attr("id").and_then(|id| rels.iter().find(|r| r.id == id)).map(|r| r.target.as_str()).unwrap_or("");
let location = h.attr("location").filter(|l| !l.is_empty());
// Each covered cell gets its own copy of the link: refuse oversized targets before copying.
if rel_target.len().saturating_add(location.map_or(0, str::len)) > MAX_HYPERLINK_TARGET {
cx.warn(format!("sheet \"{name}\": hyperlinks longer than {MAX_HYPERLINK_TARGET} characters were dropped"));
continue;
}
let mut target = rel_target.to_string();
// A relationship is a file or web page; a bare `location` is a place in this workbook.
let external = !target.is_empty();
if let Some(loc) = h.attr("location").filter(|l| !l.is_empty()) {
if let Some(loc) = location {
if target.is_empty() {
target = loc.trim_start_matches('#').to_string();
} else {
Expand All @@ -734,13 +813,14 @@ fn read_hyperlinks(cx: &mut Ctx<'_>, name: &str, e: &El, rels: &[Rel], sheet: &m
if target.is_empty() {
continue;
}
let link = Hyperlink { target, tooltip: h.attr("tooltip").map(str::to_string), external };
let tooltip = h.attr("tooltip").map(|t| truncate_chars(t, MAX_TOOLTIP_CHARS));
let link = Hyperlink { target, tooltip, external };
for c in range.iter() {
if cells >= MAX_HYPERLINK_CELLS {
if *cells >= MAX_HYPERLINK_CELLS {
cx.warn(format!("sheet \"{name}\": hyperlinks past the first {MAX_HYPERLINK_CELLS} cells were dropped"));
return;
}
cells += 1;
*cells += 1;
sheet.hyperlinks.insert(c, link.clone());
}
}
Expand Down Expand Up @@ -1005,6 +1085,25 @@ fn read_ext(cx: &mut Ctx<'_>, e: &El, sheet: &mut Sheet) {
mod tests {
use super::*;

#[test]
fn shared_formula_budget_stops_expansion() {
let expr = gridcraft_formula::parse("SUM(1,2,3)").ok();
let cost = shared_cost("SUM(1,2,3)", expr.as_ref());
assert!(cost > 64 + 4 * std::mem::size_of::<Expr>() as u64);
let cap = cost * 3;
let mut used = 0;
assert!((0..3).all(|_| charge(&mut used, cost, cap)));
assert!(!charge(&mut used, cost, cap));
assert_eq!(used, cap);
assert!(!charge(&mut used, u64::MAX, u64::MAX));
}

#[test]
fn truncate_keeps_whole_characters() {
assert_eq!(truncate_chars("ab\u{e9}d", 3), "ab\u{e9}");
assert_eq!(truncate_chars("ab", 3), "ab");
}

#[test]
fn iso_dates() {
assert_eq!(parse_iso_datetime("1900-01-01", DateSystem::D1900), Some(1.0));
Expand Down
32 changes: 23 additions & 9 deletions crates/xlsx/src/styles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ use crate::xml::{El, esc_attr, num};

// ---------------------------------------------------------------- reading

/// Longest font name kept, in characters (Excel's own limit is 31).
pub const MAX_FONT_NAME_CHARS: usize = 255;

/// Styles read from a file.
#[derive(Debug, Default)]
pub struct StylesIn {
Expand Down Expand Up @@ -60,7 +63,11 @@ fn bool_prop(e: &El, name: &str) -> bool {
pub fn read_font(e: &El, palette: &[u32]) -> Font {
let mut f = Font::default();
if let Some(n) = e.child("name").or_else(|| e.child("rFont")).and_then(|n| n.attr("val")) {
f.name = n.to_string();
// Every cell format that uses the font copies its name: keep it short.
f.name = match n.char_indices().nth(MAX_FONT_NAME_CHARS) {
Some((at, _)) => n.get(..at).unwrap_or_default().to_string(),
None => n.to_string(),
};
}
if let Some(sz) = e.child("sz").and_then(|s| s.attr_f64("val")) {
f.size = sz.clamp(1.0, 409.0) as f32;
Expand Down Expand Up @@ -267,14 +274,16 @@ fn read_protection(p: &El) -> Protection {
Protection { locked: p.flag("locked", true), hidden: p.flag("hidden", false) }
}

fn num_fmt_code(id: u32, custom: &HashMap<u32, String>) -> NumFmt {
/// A number format by id. Custom formats are built once and shared (`NumFmt` is an `Arc`), so
/// many cell formats naming one long code don't each copy it.
fn num_fmt_code(id: u32, custom: &HashMap<u32, NumFmt>) -> NumFmt {
if let Some(c) = custom.get(&id) {
return NumFmt::new(c);
return c.clone();
}
NumFmt::new(builtin_format(id).unwrap_or("General"))
}

fn read_xf(xf: &El, fonts: &[Font], fills: &[Fill], borders: &[Borders], fmts: &HashMap<u32, String>, checkboxes: &[bool]) -> Style {
fn read_xf(xf: &El, fonts: &[Font], fills: &[Fill], borders: &[Borders], fmts: &HashMap<u32, NumFmt>, checkboxes: &[bool]) -> Style {
let mut s = Style::default();
if let Some(f) = xf.attr_u32("fontId").and_then(|i| fonts.get(i as usize)) {
s.font = f.clone();
Expand Down Expand Up @@ -325,13 +334,18 @@ pub fn read_styles(root: &El, checkboxes: &[bool]) -> StylesIn {
}
}
}
let shared_fmts: HashMap<u32, NumFmt> = fmts.iter().map(|(&id, code)| (id, NumFmt::new(code))).collect();
Comment thread
Higgs32584 marked this conversation as resolved.
Resolved
let fonts: Vec<Font> = root.child("fonts").map(|f| f.kids("font").map(|e| read_font(e, &palette)).collect()).unwrap_or_default();
let fills: Vec<Fill> = root.child("fills").map(|f| f.kids("fill").map(|e| read_fill(e, &palette, false)).collect()).unwrap_or_default();
let borders: Vec<Borders> = root.child("borders").map(|f| f.kids("border").map(|e| read_border(e, &palette)).collect()).unwrap_or_default();
let xfs =
root.child("cellXfs").map(|x| x.kids("xf").map(|xf| read_xf(xf, &fonts, &fills, &borders, &fmts, checkboxes)).collect()).unwrap_or_default();
let style_xfs: Vec<Style> =
root.child("cellStyleXfs").map(|x| x.kids("xf").map(|xf| read_xf(xf, &fonts, &fills, &borders, &fmts, &[])).collect()).unwrap_or_default();
let xfs = root
.child("cellXfs")
.map(|x| x.kids("xf").map(|xf| read_xf(xf, &fonts, &fills, &borders, &shared_fmts, checkboxes)).collect())
.unwrap_or_default();
let style_xfs: Vec<Style> = root
.child("cellStyleXfs")
.map(|x| x.kids("xf").map(|xf| read_xf(xf, &fonts, &fills, &borders, &shared_fmts, &[])).collect())
.unwrap_or_default();
let mut named = Vec::new();
if let Some(cs) = root.child("cellStyles") {
for c in cs.kids("cellStyle") {
Expand All @@ -357,7 +371,7 @@ pub fn read_styles(root: &El, checkboxes: &[bool]) -> StylesIn {
if let Some(code) = n.attr("formatCode") {
s.num_fmt = NumFmt::new(code);
} else if let Some(id) = n.attr_u32("numFmtId") {
s.num_fmt = num_fmt_code(id, &fmts);
s.num_fmt = num_fmt_code(id, &shared_fmts);
}
}
if let Some(f) = x.child("fill") {
Expand Down
Loading
Loading