forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

sheet.rs281 lines, 12.2 KiBHistoryRawDownload
1//! Spreadsheet previews: a workbook (`.xlsx`) or a CSV file read as values only, with the caps of
2//! `limits.rs`: at most 20 sheets, 1000 rows, 100 columns and 1000 characters a cell. Formulas, formats,
3//! charts and macros are not read; a cell is its displayed value. The caller turns the result into HTML,
4//! where every cell is escaped, so a cell that holds markup is shown as text.
5//!
6//! A workbook is a zip container, so it passes `archive::open_checked` before calamine parses it. An `.xlsx`
7//! is read cell by cell as a stream: a cell outside the caps is dropped as it is read, and the reading stops
8//! after a fixed number of visited cells, so a sheet whose used range is huge (a stray cell at `XFD1048576`)
9//! costs no more than the caps. An `.ods` is not previewed at all: calamine has no cell stream for it and reads
10//! its `content.xml` whole, and a tiny file can declare huge repeat counts that allocate gigabytes. The viewer
11//! shows such a file as refused, and it can still be downloaded. A CSV is read record by record and stops at
12//! the row cap, so a long file costs no more than the cap. An `.xlsb` is not previewed either: calamine reads its
13//! sheet as a whole range, sized by the cells it finds rather than by the sheet's declared dimensions, so no cap
14//! can be checked before the read.
15
16use std::collections::BTreeMap;
17use std::fs::File;
18use std::io::BufReader;
19use std::path::Path;
20
21use calamine::{Data, DataRef, Reader, Sheets, Xlsx, open_workbook_auto};
22
23use crate::archive;
24use crate::error::{Error, Result};
25use crate::limits::{
26 CELL_TEXT_MAX, SHEET_COLS_MAX, SHEET_INPUT_MAX_BYTES, SHEET_ROWS_MAX, SHEET_VISITS_MAX,
27 SHEETS_MAX,
28};
29
30/// One sheet of a book, as text cells. `rows_cut` is set when the sheet had more rows than the cap.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct Sheet {
33 /// The tab name (for a CSV, the file name).
34 pub name: String,
35 /// The rows, each a list of cell texts.
36 pub rows: Vec<Vec<String>>,
37 /// Whether rows past the cap were left out.
38 pub rows_cut: bool,
39}
40
41/// A book: the sheets shown, and how many it has in all.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct Book {
44 /// The first sheets, at most [`SHEETS_MAX`].
45 pub sheets: Vec<Sheet>,
46 /// The number of sheets in the file.
47 pub sheet_count: usize,
48}
49
50/// Cuts a cell's text to [`CELL_TEXT_MAX`] characters.
51fn cell_text(text: &str) -> String {
52 text.chars().take(CELL_TEXT_MAX).collect()
53}
54
55/// The shown text of a streamed `.xlsx` cell, cut to the cap as it is read.
56fn data_ref_text(value: &DataRef<'_>) -> String {
57 match value {
58 DataRef::SharedString(text) => cell_text(text),
59 DataRef::String(text) => cell_text(text),
60 other => cell_text(&Data::from(other.clone()).to_string()),
61 }
62}
63
64/// Reads an `.xlsx` workbook. It is a zip container, and it is refused (as `Invalid`) when the zip checks
65/// fail. An `.xls` never gets this far, because it is not a zip. An OpenDocument file is refused before calamine
66/// opens it, because calamine reads its `content.xml` whole. An `.xlsb` is refused too (see the module comment).
67pub fn read_workbook(path: &Path) -> Result<Book> {
68 let mut zip = archive::open_checked(path, SHEET_INPUT_MAX_BYTES)?;
69 if zip.by_name("content.xml").is_ok() {
70 // Only an OpenDocument file has a root `content.xml`. Such files are not previewed.
71 return Err(Error::Invalid("ods_not_previewed".into()));
72 }
73 let mut workbook =
74 open_workbook_auto(path).map_err(|_| Error::Invalid("bad_workbook".into()))?;
75 let Sheets::Xlsx(xlsx) = &mut workbook else {
76 // Only `.xlsx` is streamed. An `.xlsb` is read whole by calamine, so it is refused.
77 return Err(Error::Invalid("xlsb_not_previewed".into()));
78 };
79 let names = xlsx.sheet_names();
80 let sheet_count = names.len();
81 let mut sheets = Vec::new();
82 for name in names.into_iter().take(SHEETS_MAX) {
83 sheets.push(read_xlsx_sheet(xlsx, &name)?);
84 }
85 Ok(Book {
86 sheets,
87 sheet_count,
88 })
89}
90
91/// Streams one `.xlsx` sheet. Only cells inside the caps are kept, in a sparse map, and the table is built
92/// from them. `rows_cut` is set when a kept-out cell has text, or when the visit budget ended the read early.
93fn read_xlsx_sheet(xlsx: &mut Xlsx<BufReader<File>>, name: &str) -> Result<Sheet> {
94 let bad = || Error::Invalid("bad_workbook".into());
95 let mut reader = xlsx.worksheet_cells_reader(name).map_err(|_| bad())?;
96 let mut cells: BTreeMap<(usize, usize), String> = BTreeMap::new();
97 let mut rows_cut = false;
98 let mut visits = 0usize;
99 while let Some(cell) = reader.next_cell().map_err(|_| bad())? {
100 visits += 1;
101 if visits > SHEET_VISITS_MAX {
102 rows_cut = true;
103 break;
104 }
105 let (row, col) = cell.get_position();
106 let (row, col) = (row as usize, col as usize);
107 let text = data_ref_text(cell.get_value());
108 if text.is_empty() {
109 continue;
110 }
111 if row >= SHEET_ROWS_MAX {
112 rows_cut = true;
113 continue;
114 }
115 if col >= SHEET_COLS_MAX {
116 continue;
117 }
118 cells.insert((row, col), text);
119 }
120 let rows_used = cells.keys().map(|(row, _)| row + 1).max().unwrap_or(0);
121 let cols_used = cells.keys().map(|(_, col)| col + 1).max().unwrap_or(0);
122 let mut rows = vec![vec![String::new(); cols_used]; rows_used];
123 for ((row, col), text) in cells {
124 rows[row][col] = text;
125 }
126 Ok(Sheet {
127 name: name.to_owned(),
128 rows,
129 rows_cut,
130 })
131}
132
133/// Reads a CSV file as one sheet. Invalid UTF-8 is shown with replacement characters.
134pub fn read_csv(path: &Path, name: &str) -> Result<Book> {
135 let len = std::fs::metadata(path)?.len();
136 if len > SHEET_INPUT_MAX_BYTES {
137 return Err(Error::Invalid(archive::REFUSED_SIZE.into()));
138 }
139 let mut reader = csv::ReaderBuilder::new()
140 .has_headers(false)
141 .flexible(true)
142 .from_reader(File::open(path)?);
143 let mut rows = Vec::new();
144 let mut rows_cut = false;
145 let mut record = csv::ByteRecord::new();
146 loop {
147 let more = reader
148 .read_byte_record(&mut record)
149 .map_err(|_| Error::Invalid("bad_csv".into()))?;
150 if !more {
151 break;
152 }
153 if rows.len() == SHEET_ROWS_MAX {
154 rows_cut = true;
155 break;
156 }
157 rows.push(
158 record
159 .iter()
160 .take(SHEET_COLS_MAX)
161 .map(|field| cell_text(&String::from_utf8_lossy(field)))
162 .collect(),
163 );
164 }
165 Ok(Book {
166 sheets: vec![Sheet {
167 name: name.to_owned(),
168 rows,
169 rows_cut,
170 }],
171 sheet_count: 1,
172 })
173}
174
175#[cfg(test)]
176mod tests {
177 use super::*;
178
179 #[test]
180 fn a_csv_keeps_cells_as_plain_text() {
181 let dir = tempfile::tempdir().expect("dir");
182 let path = dir.path().join("t.csv");
183 std::fs::write(&path, "name,note\n<script>x</script>,\"a, b\"\n").expect("write");
184 let book = read_csv(&path, "t.csv").expect("csv");
185 assert_eq!(book.sheet_count, 1);
186 assert_eq!(book.sheets[0].rows[1][0], "<script>x</script>");
187 assert_eq!(book.sheets[0].rows[1][1], "a, b");
188 assert!(!book.sheets[0].rows_cut);
189 }
190
191 #[test]
192 fn a_workbook_zip_bomb_is_refused() {
193 let dir = tempfile::tempdir().expect("dir");
194 let path = dir.path().join("bomb.xlsx");
195 let file = std::fs::File::create(&path).expect("create");
196 let mut writer = zip::ZipWriter::new(file);
197 let options = zip::write::SimpleFileOptions::default()
198 .compression_method(zip::CompressionMethod::Deflated);
199 writer
200 .start_file("xl/worksheets/sheet1.xml", options)
201 .expect("start");
202 std::io::Write::write_all(&mut writer, &vec![0u8; 60 * 1024 * 1024]).expect("write");
203 writer.finish().expect("finish");
204 assert!(read_workbook(&path).is_err());
205 }
206
207 #[test]
208 fn an_opendocument_workbook_is_not_previewed() {
209 let dir = tempfile::tempdir().expect("dir");
210 let path = dir.path().join("sheet.ods");
211 let file = std::fs::File::create(&path).expect("create");
212 let mut writer = zip::ZipWriter::new(file);
213 let options = zip::write::SimpleFileOptions::default();
214 writer.start_file("content.xml", options).expect("start");
215 std::io::Write::write_all(&mut writer, b"<office:document-content/>").expect("write");
216 writer.finish().expect("finish");
217 assert!(read_workbook(&path).is_err());
218 }
219
220 #[test]
221 fn a_csv_stops_at_the_row_cap() {
222 let dir = tempfile::tempdir().expect("dir");
223 let path = dir.path().join("long.csv");
224 let text: String = (0..SHEET_ROWS_MAX + 5).map(|i| format!("{i}\n")).collect();
225 std::fs::write(&path, text).expect("write");
226 let book = read_csv(&path, "long.csv").expect("csv");
227 assert_eq!(book.sheets[0].rows.len(), SHEET_ROWS_MAX);
228 assert!(book.sheets[0].rows_cut);
229 }
230
231 /// A minimal `.xlsx`: A1 holds "hello" and XFD1048576 (the far corner) holds a number.
232 #[test]
233 fn a_far_cell_does_not_blow_up_the_preview() {
234 use std::io::Write;
235 let dir = tempfile::tempdir().expect("dir");
236 let path = dir.path().join("far.xlsx");
237 let file = std::fs::File::create(&path).expect("create");
238 let mut writer = zip::ZipWriter::new(file);
239 let options = zip::write::SimpleFileOptions::default()
240 .compression_method(zip::CompressionMethod::Deflated);
241 let parts = [
242 (
243 "[Content_Types].xml",
244 r#"<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>"#,
245 ),
246 (
247 "_rels/.rels",
248 r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>"#,
249 ),
250 (
251 "xl/workbook.xml",
252 r#"<?xml version="1.0" encoding="UTF-8"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Far" sheetId="1" r:id="rId1"/></sheets></workbook>"#,
253 ),
254 (
255 "xl/_rels/workbook.xml.rels",
256 r#"<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>"#,
257 ),
258 (
259 "xl/worksheets/sheet1.xml",
260 r#"<?xml version="1.0" encoding="UTF-8"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>hello</t></is></c></row><row r="1048576"><c r="XFD1048576"><v>7</v></c></row></sheetData></worksheet>"#,
261 ),
262 ];
263 for (name, body) in parts {
264 writer.start_file(name, options).expect("start");
265 writer.write_all(body.as_bytes()).expect("write");
266 }
267 writer.finish().expect("finish");
268 let book = read_workbook(&path).expect("workbook");
269 assert_eq!(book.sheet_count, 1);
270 assert_eq!(book.sheets[0].rows, vec![vec!["hello".to_owned()]]);
271 assert!(book.sheets[0].rows_cut);
272 }
273
274 #[test]
275 fn a_cell_is_cut_to_its_cap() {
276 assert_eq!(
277 cell_text(&"x".repeat(CELL_TEXT_MAX + 9)).len(),
278 CELL_TEXT_MAX
279 );
280 }
281}