| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | use std::collections::BTreeMap; |
| 17 | use std::fs::File; |
| 18 | use std::io::BufReader; |
| 19 | use std::path::Path; |
| 20 | |
| 21 | use calamine::{Data, DataRef, Reader, Sheets, Xlsx, open_workbook_auto}; |
| 22 | |
| 23 | use crate::archive; |
| 24 | use crate::error::{Error, Result}; |
| 25 | use 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 | |
| 31 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 32 | pub struct Sheet { |
| 33 | |
| 34 | pub name: String, |
| 35 | |
| 36 | pub rows: Vec<Vec<String>>, |
| 37 | |
| 38 | pub rows_cut: bool, |
| 39 | } |
| 40 | |
| 41 | |
| 42 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 43 | pub struct Book { |
| 44 | |
| 45 | pub sheets: Vec<Sheet>, |
| 46 | |
| 47 | pub sheet_count: usize, |
| 48 | } |
| 49 | |
| 50 | |
| 51 | fn cell_text(text: &str) -> String { |
| 52 | text.chars().take(CELL_TEXT_MAX).collect() |
| 53 | } |
| 54 | |
| 55 | |
| 56 | fn 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 | |
| 65 | |
| 66 | |
| 67 | pub 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 | |
| 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 | |
| 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 | |
| 92 | |
| 93 | fn 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 | |
| 134 | pub 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)] |
| 176 | mod 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 | |
| 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 | } |