//! Spreadsheet previews: a workbook (`.xlsx`) or a CSV file read as values only, with the caps of //! `limits.rs`: at most 20 sheets, 1000 rows, 100 columns and 1000 characters a cell. Formulas, formats, //! charts and macros are not read; a cell is its displayed value. The caller turns the result into HTML, //! where every cell is escaped, so a cell that holds markup is shown as text. //! //! A workbook is a zip container, so it passes `archive::open_checked` before calamine parses it. An `.xlsx` //! is read cell by cell as a stream: a cell outside the caps is dropped as it is read, and the reading stops //! after a fixed number of visited cells, so a sheet whose used range is huge (a stray cell at `XFD1048576`) //! costs no more than the caps. An `.ods` is not previewed at all: calamine has no cell stream for it and reads //! its `content.xml` whole, and a tiny file can declare huge repeat counts that allocate gigabytes. The viewer //! shows such a file as refused, and it can still be downloaded. A CSV is read record by record and stops at //! the row cap, so a long file costs no more than the cap. An `.xlsb` is not previewed either: calamine reads its //! sheet as a whole range, sized by the cells it finds rather than by the sheet's declared dimensions, so no cap //! can be checked before the read. use std::collections::BTreeMap; use std::fs::File; use std::io::BufReader; use std::path::Path; use calamine::{Data, DataRef, Reader, Sheets, Xlsx, open_workbook_auto}; use crate::archive; use crate::error::{Error, Result}; use crate::limits::{ CELL_TEXT_MAX, SHEET_COLS_MAX, SHEET_INPUT_MAX_BYTES, SHEET_ROWS_MAX, SHEET_VISITS_MAX, SHEETS_MAX, }; /// One sheet of a book, as text cells. `rows_cut` is set when the sheet had more rows than the cap. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Sheet { /// The tab name (for a CSV, the file name). pub name: String, /// The rows, each a list of cell texts. pub rows: Vec>, /// Whether rows past the cap were left out. pub rows_cut: bool, } /// A book: the sheets shown, and how many it has in all. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Book { /// The first sheets, at most [`SHEETS_MAX`]. pub sheets: Vec, /// The number of sheets in the file. pub sheet_count: usize, } /// Cuts a cell's text to [`CELL_TEXT_MAX`] characters. fn cell_text(text: &str) -> String { text.chars().take(CELL_TEXT_MAX).collect() } /// The shown text of a streamed `.xlsx` cell, cut to the cap as it is read. fn data_ref_text(value: &DataRef<'_>) -> String { match value { DataRef::SharedString(text) => cell_text(text), DataRef::String(text) => cell_text(text), other => cell_text(&Data::from(other.clone()).to_string()), } } /// Reads an `.xlsx` workbook. It is a zip container, and it is refused (as `Invalid`) when the zip checks /// fail. An `.xls` never gets this far, because it is not a zip. An OpenDocument file is refused before calamine /// opens it, because calamine reads its `content.xml` whole. An `.xlsb` is refused too (see the module comment). pub fn read_workbook(path: &Path) -> Result { let mut zip = archive::open_checked(path, SHEET_INPUT_MAX_BYTES)?; if zip.by_name("content.xml").is_ok() { // Only an OpenDocument file has a root `content.xml`. Such files are not previewed. return Err(Error::Invalid("ods_not_previewed".into())); } let mut workbook = open_workbook_auto(path).map_err(|_| Error::Invalid("bad_workbook".into()))?; let Sheets::Xlsx(xlsx) = &mut workbook else { // Only `.xlsx` is streamed. An `.xlsb` is read whole by calamine, so it is refused. return Err(Error::Invalid("xlsb_not_previewed".into())); }; let names = xlsx.sheet_names(); let sheet_count = names.len(); let mut sheets = Vec::new(); for name in names.into_iter().take(SHEETS_MAX) { sheets.push(read_xlsx_sheet(xlsx, &name)?); } Ok(Book { sheets, sheet_count, }) } /// Streams one `.xlsx` sheet. Only cells inside the caps are kept, in a sparse map, and the table is built /// from them. `rows_cut` is set when a kept-out cell has text, or when the visit budget ended the read early. fn read_xlsx_sheet(xlsx: &mut Xlsx>, name: &str) -> Result { let bad = || Error::Invalid("bad_workbook".into()); let mut reader = xlsx.worksheet_cells_reader(name).map_err(|_| bad())?; let mut cells: BTreeMap<(usize, usize), String> = BTreeMap::new(); let mut rows_cut = false; let mut visits = 0usize; while let Some(cell) = reader.next_cell().map_err(|_| bad())? { visits += 1; if visits > SHEET_VISITS_MAX { rows_cut = true; break; } let (row, col) = cell.get_position(); let (row, col) = (row as usize, col as usize); let text = data_ref_text(cell.get_value()); if text.is_empty() { continue; } if row >= SHEET_ROWS_MAX { rows_cut = true; continue; } if col >= SHEET_COLS_MAX { continue; } cells.insert((row, col), text); } let rows_used = cells.keys().map(|(row, _)| row + 1).max().unwrap_or(0); let cols_used = cells.keys().map(|(_, col)| col + 1).max().unwrap_or(0); let mut rows = vec![vec![String::new(); cols_used]; rows_used]; for ((row, col), text) in cells { rows[row][col] = text; } Ok(Sheet { name: name.to_owned(), rows, rows_cut, }) } /// Reads a CSV file as one sheet. Invalid UTF-8 is shown with replacement characters. pub fn read_csv(path: &Path, name: &str) -> Result { let len = std::fs::metadata(path)?.len(); if len > SHEET_INPUT_MAX_BYTES { return Err(Error::Invalid(archive::REFUSED_SIZE.into())); } let mut reader = csv::ReaderBuilder::new() .has_headers(false) .flexible(true) .from_reader(File::open(path)?); let mut rows = Vec::new(); let mut rows_cut = false; let mut record = csv::ByteRecord::new(); loop { let more = reader .read_byte_record(&mut record) .map_err(|_| Error::Invalid("bad_csv".into()))?; if !more { break; } if rows.len() == SHEET_ROWS_MAX { rows_cut = true; break; } rows.push( record .iter() .take(SHEET_COLS_MAX) .map(|field| cell_text(&String::from_utf8_lossy(field))) .collect(), ); } Ok(Book { sheets: vec![Sheet { name: name.to_owned(), rows, rows_cut, }], sheet_count: 1, }) } #[cfg(test)] mod tests { use super::*; #[test] fn a_csv_keeps_cells_as_plain_text() { let dir = tempfile::tempdir().expect("dir"); let path = dir.path().join("t.csv"); std::fs::write(&path, "name,note\n,\"a, b\"\n").expect("write"); let book = read_csv(&path, "t.csv").expect("csv"); assert_eq!(book.sheet_count, 1); assert_eq!(book.sheets[0].rows[1][0], ""); assert_eq!(book.sheets[0].rows[1][1], "a, b"); assert!(!book.sheets[0].rows_cut); } #[test] fn a_workbook_zip_bomb_is_refused() { let dir = tempfile::tempdir().expect("dir"); let path = dir.path().join("bomb.xlsx"); let file = std::fs::File::create(&path).expect("create"); let mut writer = zip::ZipWriter::new(file); let options = zip::write::SimpleFileOptions::default() .compression_method(zip::CompressionMethod::Deflated); writer .start_file("xl/worksheets/sheet1.xml", options) .expect("start"); std::io::Write::write_all(&mut writer, &vec![0u8; 60 * 1024 * 1024]).expect("write"); writer.finish().expect("finish"); assert!(read_workbook(&path).is_err()); } #[test] fn an_opendocument_workbook_is_not_previewed() { let dir = tempfile::tempdir().expect("dir"); let path = dir.path().join("sheet.ods"); let file = std::fs::File::create(&path).expect("create"); let mut writer = zip::ZipWriter::new(file); let options = zip::write::SimpleFileOptions::default(); writer.start_file("content.xml", options).expect("start"); std::io::Write::write_all(&mut writer, b"").expect("write"); writer.finish().expect("finish"); assert!(read_workbook(&path).is_err()); } #[test] fn a_csv_stops_at_the_row_cap() { let dir = tempfile::tempdir().expect("dir"); let path = dir.path().join("long.csv"); let text: String = (0..SHEET_ROWS_MAX + 5).map(|i| format!("{i}\n")).collect(); std::fs::write(&path, text).expect("write"); let book = read_csv(&path, "long.csv").expect("csv"); assert_eq!(book.sheets[0].rows.len(), SHEET_ROWS_MAX); assert!(book.sheets[0].rows_cut); } /// A minimal `.xlsx`: A1 holds "hello" and XFD1048576 (the far corner) holds a number. #[test] fn a_far_cell_does_not_blow_up_the_preview() { use std::io::Write; let dir = tempfile::tempdir().expect("dir"); let path = dir.path().join("far.xlsx"); let file = std::fs::File::create(&path).expect("create"); let mut writer = zip::ZipWriter::new(file); let options = zip::write::SimpleFileOptions::default() .compression_method(zip::CompressionMethod::Deflated); let parts = [ ( "[Content_Types].xml", r#""#, ), ( "_rels/.rels", r#""#, ), ( "xl/workbook.xml", r#""#, ), ( "xl/_rels/workbook.xml.rels", r#""#, ), ( "xl/worksheets/sheet1.xml", r#"hello7"#, ), ]; for (name, body) in parts { writer.start_file(name, options).expect("start"); writer.write_all(body.as_bytes()).expect("write"); } writer.finish().expect("finish"); let book = read_workbook(&path).expect("workbook"); assert_eq!(book.sheet_count, 1); assert_eq!(book.sheets[0].rows, vec![vec!["hello".to_owned()]]); assert!(book.sheets[0].rows_cut); } #[test] fn a_cell_is_cut_to_its_cap() { assert_eq!( cell_text(&"x".repeat(CELL_TEXT_MAX + 9)).len(), CELL_TEXT_MAX ); } }