diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index 15d3961ba4..29bf592147 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -767,6 +767,11 @@ async fn fetch_reached( let max = limit.map(|n| n as u64).unwrap_or(64 << 20); let (url, tail) = cache::split_tail(url); let (url, range) = cache::split_range(url); + if let Some((a, b)) = range + && cache::range_len(a, b).is_none() + { + return Err("byte range is inverted or its length overflows".into()); + } // Share native GET routing: explicit service logins outrank implicit S3 endpoint signing. let bound = url; let prepared = cache::prepare_get(url)?; diff --git a/crates/data/src/filegdb.rs b/crates/data/src/filegdb.rs index 592f5e51f0..38d5841277 100644 --- a/crates/data/src/filegdb.rs +++ b/crates/data/src/filegdb.rs @@ -394,6 +394,7 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option) -> Result) -> Result {} - Err(()) => report.skipped += 1, + Err(()) => { + bad_geometries += 1; + report.skipped += 1; + } } } // Kept as the file holds it, in its own system; counted when it has no place in @@ -502,6 +506,14 @@ fn read_table(name: &str, t: &[u8], x: &[u8], wkid: Option) -> Result 0 { + let what = if bad_geometries == 1 { + "1 feature had an unreadable or non-finite geometry and is kept without geometry".to_string() + } else { + format!("{bad_geometries} features had unreadable or non-finite geometries and are kept without geometry") + }; + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedGeometry, what)); + } Ok(Some((ds, report))) } @@ -988,6 +1000,12 @@ fn row_offsets(x: &[u8]) -> Result> { } } } + // Check for duplicate offsets in place without allocating an auxiliary hash set. + out.sort_unstable_by_key(|&(_, offset)| offset); + if out.windows(2).any(|w| matches!(w, [(_, a), (_, b)] if a == b)) { + return Err(bad("duplicate row offset")); + } + out.sort_unstable_by_key(|&(row, _)| row); Ok(out) } @@ -1029,7 +1047,11 @@ fn decode_geometry(b: &[u8], def: &GeomDef, budget: &mut usize) -> std::result:: if vx == 0 || vy == 0 { return Ok(Decoded::Empty); } - Ok(Decoded::Geometry(Geometry::Point(Coord::new(x((vx - 1) as f64), y((vy - 1) as f64))), 0)) + let (px, py) = (x((vx - 1) as f64), y((vy - 1) as f64)); + if !px.is_finite() || !py.is_finite() { + return Err(()); + } + Ok(Decoded::Geometry(Geometry::Point(Coord::new(px, py)), 0)) } // Multipoints. 8 | 18 | 20 | 28 | 53 => { @@ -1136,7 +1158,11 @@ fn deltas(c: &mut Cur, n: usize, def: &GeomDef) -> std::result::Result f64 { } /// A multipatch's faces, each its outer ring and then its holes: triangles from strips, fans and -/// triangle lists, and rings. At most [`MAX_FACES`]; the flag says some were left out. +/// triangle lists, and rings. At most [`MAX_FACES`] rings in total; the flag says some were left +/// out. fn faces(parts: &[Vec], kinds: &[u64]) -> (Vec>>, bool) { + faces_limited(parts, kinds, MAX_FACES) +} + +fn faces_limited(parts: &[Vec], kinds: &[u64], limit: usize) -> (Vec>>, bool) { let mut faces: Vec>> = Vec::new(); + let mut rings = 0usize; let mut truncated = false; for (part, &kind) in parts.iter().zip(kinds) { - // Faces past the cap are left out, within a part too (one strip can hold millions). - let room = MAX_FACES.saturating_sub(faces.len()); + // Faces and inner rings past the cap are left out, within a part too (one strip can hold millions). + let room = limit.saturating_sub(rings); let has = match kind { 0 | 1 => part.len().saturating_sub(2), 6 => part.len() / 3, - 3 => 0, _ => 1, }; if has > room { truncated = true; } if room == 0 { - break; + if truncated { + break; + } + continue; } match kind { // Triangle strip, fan, triangles. - 0 => faces.extend(part.windows(3).take(room).map(|w| vec![w.to_vec()])), + 0 => { + let take = part.len().saturating_sub(2).min(room); + faces.extend(part.windows(3).take(take).map(|w| vec![w.to_vec()])); + rings += take; + } 1 => { if let Some((first, rest)) = part.split_first() { + let take = rest.len().saturating_sub(1).min(room); faces.extend( rest.windows(2) .filter_map(|w| match w { [a, b] => Some(vec![vec![*first, *a, *b]]), _ => None, }) - .take(room), + .take(take), ); + rings += take; } } - 6 => faces.extend(part.as_chunks::<3>().0.iter().take(room).map(|w| vec![w.to_vec()])), + 6 => { + let take = (part.len() / 3).min(room); + faces.extend(part.as_chunks::<3>().0.iter().take(take).map(|w| vec![w.to_vec()])); + rings += take; + } // An inner ring is a hole in the face before. - 3 => match faces.last_mut() { - Some(face) => face.push(part.clone()), - None => faces.push(vec![part.clone()]), - }, + 3 => { + match faces.last_mut() { + Some(face) => face.push(part.clone()), + None => faces.push(vec![part.clone()]), + } + rings += 1; + } // Outer, first and plain rings. - _ => faces.push(vec![part.clone()]), + _ => { + faces.push(vec![part.clone()]); + rings += 1; + } } } (faces, truncated) diff --git a/crates/data/src/filegdb/tests.rs b/crates/data/src/filegdb/tests.rs index 677538056f..77ebc8323a 100644 --- a/crates/data/src/filegdb/tests.rs +++ b/crates/data/src/filegdb/tests.rs @@ -970,6 +970,76 @@ fn filegdb_temporal_fields_keep_days_offsets_and_null_notices() { } } +#[test] +fn duplicate_row_offsets_are_refused() { + let (t, mut x) = table(0, &[F::Oid, F::Text("name")], &[vec![V::Text(Some("a"))], vec![V::Text(Some("b"))]]); + // Row index entries start at byte 16 with width 4; copy row 0's offset into row 1's slot. + let first_offset: [u8; 4] = x[16..20].try_into().unwrap(); + x[20..24].copy_from_slice(&first_offset); + let err = row_offsets(&x).unwrap_err().to_string(); + assert!(err.contains("duplicate row offset"), "{err}"); + assert!(read_table("dup", &t, &x, None).is_err()); +} + +#[test] +fn non_finite_coordinates_are_rejected() { + let tiny_scale = GeomDef { wkt: String::new(), x0: 0.0, y0: 0.0, xy_scale: 1e-308, z0: 0.0, z_scale: 1.0 }; + // Point (code 1): vx = 2, vy = 2 -> (1.0 / 1e-308) is finite; vx = 1000 -> 999 / 1e-308 = inf. + let mut pt = varuint(1); + pt.extend(varuint(1000)); + pt.extend(varuint(2)); + assert!(decode_geometry(&pt, &tiny_scale, &mut 100).is_err()); + + // Polyline (code 3): 2 points, 1 part, bbox(4 varuints), delta (1000, 0) overflows to inf. + let mut line = varuint(3); + line.extend(varuint(2)); + line.extend(varuint(1)); + for _ in 0..4 { + line.extend(varuint(0)); + } + line.extend(varint(1000)); + line.extend(varint(0)); + line.extend(varint(0)); + line.extend(varint(0)); + assert!(decode_geometry(&line, &tiny_scale, &mut 100).is_err()); + + // End-to-end through `read_table`: lossy input emits a DroppedGeometry notice; clean input emits none. + let (mut t, x) = table(1, &[F::Oid, F::Shape { z: false, wkt: "" }], &[vec![V::Blob(pt.clone())]]); + let scale_bytes = 1000.0f64.to_le_bytes(); + let pos = t.windows(8).position(|w| w == scale_bytes).expect("xy_scale in shape field header"); + t[pos..pos + 8].copy_from_slice(&1e-308f64.to_le_bytes()); + let (lossy_ds, lossy_report) = read_table("nonfinite", &t, &x, None).unwrap().unwrap(); + assert_eq!(lossy_ds.features.len(), 1); + assert!(lossy_ds.features[0].geometry.is_none()); + assert_eq!(lossy_report.skipped, 1); + assert!( + lossy_report.messages.iter().any(|m| { + m.loss == Some(crate::loss::LossCode::DroppedGeometry) + && m.as_str() == "1 feature had an unreadable or non-finite geometry and is kept without geometry" + }), + "{lossy_report:?}" + ); + + let (clean_t, clean_x) = table(1, &[F::Oid, F::Shape { z: false, wkt: "" }], &[vec![V::Blob(pt)]]); + let (clean_ds, clean_report) = read_table("clean", &clean_t, &clean_x, None).unwrap().unwrap(); + assert_eq!(clean_ds.features.len(), 1); + assert!(clean_ds.features[0].geometry.is_some()); + assert_eq!(clean_report.skipped, 0); + assert!(!clean_report.messages.iter().any(|m| m.loss == Some(crate::loss::LossCode::DroppedGeometry)), "{clean_report:?}"); +} + +#[test] +fn multipatch_inner_rings_respect_ring_budget() { + let ring = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]]; + let parts = vec![ring; 6]; + // 1 outer ring (kind 2) followed by 5 inner rings (kind 3). + let kinds = [2, 3, 3, 3, 3, 3]; + let (got, truncated) = faces_limited(&parts, &kinds, 3); + assert!(truncated, "inner rings past the ring budget must set truncated"); + let total_rings: usize = got.iter().map(Vec::len).sum(); + assert_eq!(total_rings, 3); +} + /// A binary field and a geometry field after the first are left out of the layer, and said, once /// for the table and by its name; a table without them says nothing (#2916). #[test] diff --git a/crates/data/src/interop.rs b/crates/data/src/interop.rs index 7ddece5782..b0a8d31068 100644 --- a/crates/data/src/interop.rs +++ b/crates/data/src/interop.rs @@ -672,10 +672,10 @@ impl WktParser { } } -/// What goes before a [`to_wkt_csv`] cell's text: `'` before text starting like a formula, so -/// spreadsheets show it rather than run it, else nothing. +/// What goes before a [`to_wkt_csv`] field name: `'` before a name starting like a formula, so +/// spreadsheets show it rather than run it, else nothing. The same guard as plain CSV's. pub(crate) fn wkt_csv_guard(s: &str) -> &'static str { - if s.starts_with(['=', '+', '-', '@']) && s.parse::().is_err() { "'" } else { "" } + if crate::io::csv_needs_guard(s) { "'" } else { "" } } /// One CSV cell of `text`, `guard` before it: quoted when the text holds a comma, a quote or a @@ -704,16 +704,17 @@ pub fn to_wkt_csv(ds: &Dataset) -> crate::Result { text(out) } -/// [`to_wkt_csv`]'s text, written to `out` as it is made. +/// [`to_wkt_csv`]'s text, written to `out` as it is made. Field names and text cells that start +/// like a spreadsheet formula take an apostrophe, as in plain CSV. pub(crate) fn write_wkt_csv(ds: &Dataset, out: &mut impl Write) -> crate::Result<()> { - /// A comma, then `text` as a CSV cell with its formula guard. - fn cell(out: &mut impl Write, text: &str) -> std::io::Result<()> { + /// A comma, then `text` as a CSV cell with `guard` before it. + fn cell(out: &mut impl Write, guard: &str, text: &str) -> std::io::Result<()> { out.write_all(b",")?; - write_csv_cell(out, wkt_csv_guard(text), text) + write_csv_cell(out, guard, text) } out.write_all(b"wkt")?; for f in &ds.fields { - cell(out, &f.name)?; + cell(out, wkt_csv_guard(&f.name), &f.name)?; } out.write_all(b"\n")?; for f in &ds.features { @@ -727,7 +728,8 @@ pub(crate) fn write_wkt_csv(ds: &Dataset, out: &mut impl Write) -> crate::Result out.write_all(quote)?; } for v in &f.attrs { - cell(out, &v.file_text())?; + let (guard, text) = crate::io::csv_cell(v); + cell(out, guard, &text)?; } out.write_all(b"\n")?; } @@ -794,6 +796,121 @@ mod tests { assert!(c.contains("POINT (1 2),,0.1234567891\n") && c.contains(",B,0.000000001\n"), "{c}"); } + #[test] + fn wkt_csv_formula_guard_matches_csv() { + for guarded in ["=SUM(A1)", "@cmd", "\t=1", "\r+1", "+Inf", "-NaN", "+0123", "-007", "+1234567890123456", "-1234567890123456"] { + let value = Value::Text(guarded.into()); + let (guard, text) = crate::io::csv_cell(&value); + assert_eq!(format!("{guard}{text}"), format!("'{guarded}"), "{guarded:?}"); + } + for plain in ["-12.5", "+42", "-0.5", "Paris"] { + let value = Value::Text(plain.into()); + let (guard, text) = crate::io::csv_cell(&value); + assert_eq!(format!("{guard}{text}"), plain, "{plain:?}"); + } + // Formula-like headers (`=1+1`, `=HYPERLINK(...)`, `+0123`) are apostrophe-guarded on + // export in both WKT CSV and plain CSV, reported via `export_losses_notes`, and read back + // with the guard intact; 16-digit negative integers stay unguarded and round-trip as + // Integer; formula-like text cells are guarded on export and unguarded on read. + let mut ds = Dataset::new( + "rt", + GeometryType::Point, + vec![ + Field::new("=1+1", FieldType::Text), + Field::new("=HYPERLINK(\"https://example.com\",\"x\")", FieldType::Text), + Field::new("+0123", FieldType::Text), + Field::new("big_id", FieldType::Integer), + ], + ); + ds.push( + Some(Geometry::Point(Coord::new(1.0, 2.0))), + vec![Value::Text("\t=1".into()), Value::Text("ok".into()), Value::Text("+0123".into()), Value::Int(-1_234_567_890_123_456)], + ); + let csv = to_wkt_csv(&ds).unwrap(); + let header_line = csv.lines().next().unwrap_or(""); + assert_eq!(header_line, "wkt,'=1+1,\"'=HYPERLINK(\"\"https://example.com\"\",\"\"x\"\")\",'+0123,big_id"); + assert!(csv.contains("'\t=1,ok,'+0123,-1234567890123456\n"), "text guarded, integer unguarded: {csv}"); + // Plain CSV writer has header-guard parity too. + let plain_csv = crate::io::to_csv(&ds).unwrap(); + assert_eq!( + plain_csv.lines().next().unwrap_or(""), + "longitude,latitude,'=1+1,\"'=HYPERLINK(\"\"https://example.com\"\",\"\"x\"\")\",'+0123,big_id" + ); + // Both WKT CSV and plain CSV report the guarded field names (including that they read back + // with the apostrophe prefix) and guarded text values. + for ext in ["wkt", "csv"] { + let notes = crate::io::export_losses_notes(&ds, ext, None, "rt.csv").unwrap(); + assert!( + notes.iter().any(|n| { + n.contains("CSV prefixed 3 field names with an apostrophe for spreadsheet protection") + && n.ends_with("; they read back with that prefix") + }), + "{ext}: {notes:?}" + ); + assert!( + notes.iter().any(|n| n.contains("CSV prefixed 2 text values with an apostrophe for spreadsheet protection")), + "{ext}: {notes:?}" + ); + } + // Clean dataset produces zero guard notices. + let mut clean = Dataset::new("clean", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + clean.push(Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![Value::Text("Paris".into())]); + assert!(!to_wkt_csv(&clean).unwrap().contains('\'')); + assert!(crate::io::export_losses_notes(&clean, "wkt", None, "clean.csv").unwrap().is_empty()); + assert!(crate::io::export_losses_notes(&clean, "csv", None, "clean.csv").unwrap().is_empty()); + + // Round-trip: guarded field names come back with their reported apostrophe prefix; + // integer column stays Integer; text cells unguard back to their original values. + let (back, _) = crate::io::read_csv(&csv, "rt").unwrap(); + let names: Vec<&str> = back.fields.iter().map(|f| f.name.as_str()).collect(); + assert_eq!(names, ["'=1+1", "'=HYPERLINK(\"https://example.com\",\"x\")", "'+0123", "big_id"]); + assert_eq!(back.fields[3].ty, FieldType::Integer); + assert_eq!(back.features[0].attrs[0], Value::Text("\t=1".into())); + assert_eq!(back.features[0].attrs[2], Value::Text("+0123".into())); + assert_eq!(back.features[0].attrs[3], Value::Int(-1_234_567_890_123_456)); + + // External CSVs whose headers literally start with an apostrophe keep their exact names + // and still match explicit `CsvOptions.wkt`. + let external = "'=geom,'-foo\nPOINT (1 2),bar\n"; + let opts = crate::io::CsvOptions { wkt: Some("'=geom".into()), ..Default::default() }; + let (ext, _) = crate::io::read_csv_with(external, "ext", &opts).unwrap(); + assert_eq!(ext.fields.iter().map(|f| f.name.as_str()).collect::>(), ["'-foo"]); + assert_eq!(ext.features[0].geometry, Some(Geometry::Point(Coord::new(1.0, 2.0)))); + } + + /// A guarded field name that comes out the same as another field's name (`=1+1` next to + /// `'=1+1`) is said in the export notice; names that don't clash say nothing more. + #[test] + fn guarded_header_that_clashes_with_another_field_is_said() { + let mut ds = Dataset::new( + "clash", + GeometryType::Point, + vec![Field::new("=1+1", FieldType::Text), Field::new("'=1+1", FieldType::Text), Field::new("@x", FieldType::Text)], + ); + ds.push( + Some(Geometry::Point(Coord::new(1.0, 2.0))), + vec![Value::Text("a".into()), Value::Text("b".into()), Value::Text("c".into())], + ); + let csv = to_wkt_csv(&ds).unwrap(); + assert_eq!(csv.lines().next(), Some("wkt,'=1+1,'=1+1,'@x")); + for ext in ["wkt", "csv"] { + let notes = crate::io::export_losses_notes(&ds, ext, None, "clash.csv").unwrap(); + let texts: Vec<&str> = notes.texts().collect(); + assert!( + texts + .iter() + .any(|n| n.ends_with("they read back with that prefix; 1 of them now has the same header as another field: '=1+1'")), + "{ext}: {texts:?}" + ); + } + let mut plain = Dataset::new("plain", GeometryType::Point, vec![Field::new("=1+1", FieldType::Text)]); + plain.push(Some(Geometry::Point(Coord::new(1.0, 2.0))), vec![Value::Text("a".into())]); + let notes = crate::io::export_losses_notes(&plain, "wkt", None, "plain.csv").unwrap(); + let texts: Vec<&str> = notes.texts().collect(); + assert!(texts.iter().any(|n| n.ends_with("it reads back with that prefix")), "{texts:?}"); + assert!(!texts.iter().any(|n| n.contains("same header")), "{texts:?}"); + } + /// Values longer than a piece, with every character that is escaped, a quote or the formula /// guard, are written whole in KML, GPX and a WKT cell. #[test] diff --git a/crates/data/src/io.rs b/crates/data/src/io.rs index c37e234dcd..cf4cbf6f99 100644 --- a/crates/data/src/io.rs +++ b/crates/data/src/io.rs @@ -3708,7 +3708,7 @@ const FORMULA_START: [char; 6] = ['=', '+', '-', '@', '\t', '\r']; /// Text needs an apostrophe if it starts like a spreadsheet formula. The numeric exception /// keeps finite numbers that fit Double precision and have at most 15 significant digits. /// A leading-zero code stays guarded unless its mantissa has digits after a decimal point. -fn csv_needs_guard(text: &str) -> bool { +pub(crate) fn csv_needs_guard(text: &str) -> bool { if !text.starts_with(FORMULA_START) { return false; } @@ -3722,7 +3722,7 @@ fn csv_needs_guard(text: &str) -> bool { /// What goes before a cell's file text, an apostrophe when the spreadsheet guard applies, and /// that text. -fn csv_cell(v: &Value) -> (&'static str, Cow<'_, str>) { +pub(crate) fn csv_cell(v: &Value) -> (&'static str, Cow<'_, str>) { let guard = match v { Value::Text(t) if csv_needs_guard(t) => "'", _ => "", @@ -3730,6 +3730,11 @@ fn csv_cell(v: &Value) -> (&'static str, Cow<'_, str>) { (guard, v.file_text()) } +/// A CSV header name, prefixed with an apostrophe when it starts like a spreadsheet formula. +pub(crate) fn csv_header(name: &str) -> String { + if csv_needs_guard(name) { format!("'{name}") } else { name.to_string() } +} + /// The names of a point layer's longitude and latitude columns in CSV: the first of the names /// reading takes for each that no field has, ignoring case and the spaces around a name (reading /// trims them). @@ -3805,7 +3810,7 @@ impl CsvWriter { // The coordinate columns come first, before any attributes using recognised names. head.extend(csv_names_in(fields, crs)); } - head.extend(fields.iter().map(|f| f.name.clone())); + head.extend(fields.iter().map(|f| csv_header(&f.name))); w.write_record(&head).map_err(|e| DataError::Format(e.to_string()))?; Ok(CsvWriter { w: Some(w), point, columns: head.len() }) } @@ -5582,21 +5587,8 @@ impl CsvLosses { format!("{target}: CSV holds a point a row, so the geometry of {what} wasn't written, only the attributes"), )); } - let total: usize = self.guarded.iter().sum(); - if total > 0 { - let target: String = target.chars().map(dbf_notice_char).collect(); - let values = if total == 1 { "value" } else { "values" }; - let affected = fields - .iter() - .zip(&self.guarded) - .filter(|(_, n)| **n > 0) - .map(|(f, n)| format!("'{}' ({n})", dbf_notice_name(&f.name))) - .collect::>() - .join(", "); - notes.push(crate::loss::Note::plain(format!( - "{target}: CSV prefixed {total} text {values} with an apostrophe for spreadsheet protection in {affected}" - ))); - } + notes.extend(csv_guarded_headers_note(fields, target)); + notes.extend(csv_guarded_cells_note(fields, &self.guarded, target)); notes } @@ -5842,12 +5834,7 @@ impl TextLosses { if let Some(column) = &mut loss.column && !column.is_text() { - let (guard, cell) = if ext == "csv" { - csv_cell(v) - } else { - let cell = v.file_text(); - (if ext == "wkt" { crate::interop::wkt_csv_guard(&cell) } else { "" }, cell) - }; + let (guard, cell) = if ext == "csv" || ext == "wkt" { csv_cell(v) } else { ("", v.file_text()) }; // Guarded text types its column as text, as its apostrophe alone does. let text = if guard.is_empty() { cell.as_ref() } else { guard }; // CSV's `` reads as null, so it types a column no more than an empty cell. @@ -6009,6 +5996,58 @@ pub fn export_losses_notes(ds: &Dataset, ext: &str, name_field: Option, t export_losses_notes_in(ds, ext, name_field, target, Crs::LonLat) } +/// Notice for CSV/WKT CSV field names prefixed with an apostrophe for spreadsheet protection. +fn csv_guarded_headers_note(fields: &[Field], target: &str) -> Option { + let guarded: Vec = + fields.iter().filter(|f| csv_needs_guard(&f.name)).map(|f| format!("'{}'", dbf_notice_name(&f.name))).collect(); + if guarded.is_empty() { + return None; + } + let target: String = target.chars().map(dbf_notice_char).collect(); + let count = guarded.len(); + let (names, pronoun) = if count == 1 { ("field name", "it reads") } else { ("field names", "they read") }; + // A guarded name can come out the same as another field's name that already starts with an + // apostrophe (`=1+1` and `'=1+1`): the file then holds two columns under one header. + let clashes: Vec = fields + .iter() + .filter(|f| csv_needs_guard(&f.name)) + .filter(|f| { + let written = format!("'{}", f.name); + fields.iter().any(|other| other.name == written) + }) + .map(|f| format!("'{}'", dbf_notice_name(&f.name))) + .collect(); + let clash = match clashes.len() { + 0 => String::new(), + 1 => format!("; 1 of them now has the same header as another field: {}", clashes.join(", ")), + n => format!("; {n} of them now have the same header as another field: {}", clashes.join(", ")), + }; + Some(crate::loss::Note::plain(format!( + "{target}: CSV prefixed {count} {names} with an apostrophe for spreadsheet protection ({}); {pronoun} back with that prefix{clash}", + guarded.join(", ") + ))) +} + +/// Notice for CSV/WKT CSV text cells prefixed with an apostrophe for spreadsheet protection. +fn csv_guarded_cells_note(fields: &[Field], guarded: &[usize], target: &str) -> Option { + let total: usize = guarded.iter().sum(); + if total == 0 { + return None; + } + let target: String = target.chars().map(dbf_notice_char).collect(); + let values = if total == 1 { "value" } else { "values" }; + let affected = fields + .iter() + .zip(guarded) + .filter(|(_, n)| **n > 0) + .map(|(f, n)| format!("'{}' ({n})", dbf_notice_name(&f.name))) + .collect::>() + .join(", "); + Some(crate::loss::Note::plain(format!( + "{target}: CSV prefixed {total} text {values} with an apostrophe for spreadsheet protection in {affected}" + ))) +} + /// As [`export_losses_notes`], for an export written in `crs`. pub fn export_losses_notes_in(ds: &Dataset, ext: &str, name_field: Option, target: &str, crs: Crs) -> Result { let mut notes = match ext { @@ -6037,6 +6076,13 @@ pub fn export_losses_notes_in(ds: &Dataset, ext: &str, name_field: Option notes.extend(losses.coordinates_note_in(&ds.fields, target, crs).map(crate::loss::Note::plain)); notes } + "wkt" => { + let mut notes = Vec::new(); + notes.extend(csv_guarded_headers_note(&ds.fields, target)); + let guarded_cells = CsvLosses::of(&ds.features, GeometryType::None, &ds.fields)?; + notes.extend(csv_guarded_cells_note(&ds.fields, &guarded_cells.guarded, target)); + notes + } "kml" | "kmz" => { let placed = written_with_geometry(ds)?; kml_empty_fields_note(ds, &placed, target)?.into_iter().chain(kml_blank_names_note(ds, &placed, target)?).collect() diff --git a/crates/data/src/landxml.rs b/crates/data/src/landxml.rs index 347911e41e..9f695caa6a 100644 --- a/crates/data/src/landxml.rs +++ b/crates/data/src/landxml.rs @@ -20,7 +20,7 @@ use crate::{DataError, Dataset, Field, FieldType, Geometry, GeometryType, ReadRe /// LandXML file types (often plain `.xml`, read when its contents say so). pub const EXTENSIONS: &[&str] = &["landxml"]; -/// The most TIN faces read from one surface. +/// The most TIN faces read from a LandXML file. const MAX_FACES: usize = 2_000_000; pub fn is_landxml_name(name: &str) -> bool { @@ -41,6 +41,31 @@ fn elements<'a, 'i>(n: &Node<'a, 'i>, name: &'static str) -> impl Iterator` and `` descendants of `s`, stopping at any nested `` so each surface +/// keeps its own point-ID namespace and every node is visited once even under deep nesting. +fn surface_nodes<'a, 'i>(s: &Node<'a, 'i>) -> Result<(Vec>, Vec>)> { + let (mut pts, mut fcs) = (Vec::new(), Vec::new()); + let mut stack: Vec> = s.children().rev().collect(); + let mut visited = 0usize; + while let Some(node) = stack.pop() { + if visited.is_multiple_of(1024) { + crate::progress::check()?; + } + visited += 1; + if !node.is_element() { + continue; + } + match local(&node) { + "Surface" => continue, + "P" => pts.push(node), + "F" => fcs.push(node), + _ => {} + } + stack.extend(node.children().rev()); + } + Ok((pts, fcs)) +} + fn text_of(n: &Node) -> String { n.children().filter(|t| t.is_text()).filter_map(|t| t.text()).collect::() } @@ -58,6 +83,10 @@ fn nez(s: &str) -> Option<(Coord, Option)> { /// Reads a LandXML file into its layers (those with features). `crs` is the coordinate system of /// a file that doesn't say. pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result> { + read_with_max_faces(file_name, bytes, crs, MAX_FACES) +} + +fn read_with_max_faces(file_name: &str, bytes: &[u8], crs: Option, max_faces: usize) -> Result> { let name = std::path::Path::new(file_name).file_stem().and_then(|s| s.to_str()).unwrap_or("landxml").to_string(); let text = std::str::from_utf8(bytes).map_err(|_| DataError::Format(format!("{file_name} is not UTF-8 text")))?; let opts = ParsingOptions { allow_dtd: false, nodes_limit: crate::io::XML_NODES, ..ParsingOptions::default() }; @@ -199,10 +228,16 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result = Vec::new(); let mut faces_left_out = 0usize; + let mut total_faces = 0usize; for s in elements(&root, "Surface") { + crate::progress::check()?; let sname = s.attribute("name").unwrap_or("").to_string(); + let (surf_pts, surf_faces) = surface_nodes(&s)?; let mut pnts: HashMap<&str, (Coord, Option)> = HashMap::new(); - for p in elements(&s, "P") { + for (pi, p) in surf_pts.into_iter().enumerate() { + if pi.is_multiple_of(1024) { + crate::progress::check()?; + } // A point that can't be read isn't kept. The faces that name it are left out, and // counted as features, so the point is said on its own without a code. match (p.attribute("id"), nez(&text_of(&p))) { @@ -214,15 +249,21 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result= MAX_FACES { - if i == MAX_FACES { + let mut s_over_limit = false; + for (fi, f) in surf_faces.into_iter().filter(|f| f.attribute("i") != Some("1")).enumerate() { + if fi.is_multiple_of(1024) { + crate::progress::check()?; + } + // Past the file-wide limit, a face is only counted, so the notice says how many are left out. + if total_faces >= max_faces { + if !s_over_limit { over_limit.push(sname.clone()); + s_over_limit = true; } faces_left_out += 1; continue; } + total_faces += 1; let tri: Option)>> = text_of(&f).split_whitespace().map(|id| pnts.get(id).copied()).collect(); match tri.as_deref() { Some([a, b, c]) => { @@ -246,7 +287,7 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result {} [one] => report.messages.push(crate::loss::Note::loss( crate::loss::LossCode::DroppedOverLimit, - format!("surface '{one}' has more than {MAX_FACES} faces: the {faces_left_out} past the limit are left out"), + format!("the file has more than {max_faces} faces: the {faces_left_out} past the limit are left out, from surface '{one}' on"), )), many => { let shown: Vec = many.iter().take(10).map(|n| format!("'{n}'")).collect(); @@ -254,7 +295,7 @@ pub fn read(file_name: &str, bytes: &[u8], crs: Option) -> Result + + + +

0 0 1

0 1 1

1 0 1

+ 1 2 3 +
+
+ + +

10 10 5

10 11 5

11 10 5

+ 1 2 3 +
+
+
+
"#; + let layers = read("nested.xml", nested.as_bytes(), None).unwrap(); + assert_eq!(layers.len(), 1); + assert_eq!(layers[0].0.features.len(), 2, "nested elements must not duplicate faces"); + assert_eq!(layers[0].0.value(0, 0), &Value::Text("inner_a".into())); + assert_eq!(layers[0].0.value(0, 1), &Value::Float(1.0)); + assert_eq!(layers[0].0.value(1, 0), &Value::Text("inner_b".into())); + assert_eq!(layers[0].0.value(1, 1), &Value::Float(5.0)); + assert_eq!( + layers[0].0.features[0].geometry, + Some(Geometry::Polygon(vec![vec![vec![ + Coord::new(0.0, 0.0), + Coord::new(1.0, 0.0), + Coord::new(0.0, 1.0), + Coord::new(0.0, 0.0), + ]]])) + ); + assert_eq!( + layers[0].0.features[1].geometry, + Some(Geometry::Polygon(vec![vec![vec![ + Coord::new(10.0, 10.0), + Coord::new(11.0, 10.0), + Coord::new(10.0, 11.0), + Coord::new(10.0, 10.0), + ]]])) + ); + + let two_surfaces = r#" + +

0 0 1

0 1 1

1 0 1

+ 1 2 31 2 31 2 3 +
+ +

0 0 2

0 1 2

1 0 2

+ 1 2 31 2 31 2 3 +
+
"#; + let layers = read_with_max_faces("two.xml", two_surfaces.as_bytes(), None, 4).unwrap(); + assert_eq!(layers[0].0.features.len(), 4, "file-wide face cap must bound sibling surfaces"); + assert!(layers[0].1.messages.iter().any(|m| { + m.loss == Some(crate::loss::LossCode::DroppedOverLimit) + && m.as_str() == "the file has more than 4 faces: the 2 past the limit are left out, from surface 'b' on" + })); + + let three_surfaces = r#" + +

0 0 1

0 1 1

1 0 1

+ 1 2 31 2 31 2 3 +
+ +

0 0 2

0 1 2

1 0 2

+ 1 2 31 2 3 +
+ +

0 0 3

0 1 3

1 0 3

+ 1 2 31 2 3 +
+
"#; + let layers = read_with_max_faces("three.xml", three_surfaces.as_bytes(), None, 4).unwrap(); + assert_eq!(layers[0].0.features.len(), 4); + assert!(layers[0].1.messages.iter().any(|m| { + m.loss == Some(crate::loss::LossCode::DroppedOverLimit) + && m.as_str() == "the file has more than 4 faces: the 3 past the limit are left out, across 2 surfaces ('b', 'c')" + })); + } + + #[test] + fn a_cancelled_landxml_surface_read_stops() { + let probe = std::sync::Arc::new(crate::progress::tests::Counted::default()); + probe.cancel.store(true, std::sync::atomic::Ordering::Relaxed); + let _g = crate::progress::install(Some(probe)); + assert!(matches!(read("site.xml", LANDXML.as_bytes(), None), Err(DataError::Cancelled))); + } } diff --git a/crates/data/src/osm.rs b/crates/data/src/osm.rs index 0c98e1f060..7a68ca1354 100644 --- a/crates/data/src/osm.rs +++ b/crates/data/src/osm.rs @@ -24,6 +24,40 @@ const MAX_MEMBERS: usize = 100_000; const MAX_WAYS: usize = MAX_NODES / 4; const MAX_REFS: usize = MAX_NODES * 2; const MAX_RELATIONS: usize = MAX_NODES / 40; +/// The decoded tag and role text bytes kept across an OSM PBF file, as a multiple of the file's +/// size: a small compressed block can repeat one string-table entry across thousands of entities. +/// Real extracts hold about 3.5 to 7.5 times their size (Geofabrik's Luxembourg, 48 MB: 167 MiB, +/// 116 MiB of it on ways; Berlin, 100 MB: 721 MiB, 393 MiB on ways, per-entry overhead included), +/// so 24 times leaves the busiest kind, ways, about twice what Berlin needs of its third. +/// Split across nodes, ways and relations so heavy tags on one kind cannot starve the others. +const TEXT_BYTES_PER_FILE_BYTE: usize = 24; +/// The text budget's floor (a small file still reads whole) and its most: 4 GiB on a 64-bit +/// build, 1 GiB where `usize` is 32 bits (the browser, a 32-bit phone). +const MIN_TEXT_BYTES: usize = if cfg!(target_arch = "wasm32") { 64 << 20 } else { 256 << 20 }; +#[cfg(not(target_pointer_width = "64"))] +const MAX_TEXT_BYTES: usize = 1 << 30; +#[cfg(target_pointer_width = "64")] +const MAX_TEXT_BYTES: usize = 4 << 30; + +/// The tag and role text budget of a file of `len` bytes: [`TEXT_BYTES_PER_FILE_BYTE`] times its +/// size, from [`MIN_TEXT_BYTES`] up to what this computer plans for one job +/// ([`crate::memory::planned`], at most [`MAX_TEXT_BYTES`]). The browser doesn't say its memory, +/// so there the ceiling is [`MAX_TEXT_BYTES`] itself, with [`MAX_NODES`] already smaller there. +/// What is past the budget is left out and said, with a smaller extract as the way out. +fn text_limit_for(len: usize) -> usize { + let ceiling = if cfg!(target_arch = "wasm32") { MAX_TEXT_BYTES } else { crate::memory::planned(MIN_TEXT_BYTES, MAX_TEXT_BYTES, 1) }; + text_limit_within(len, ceiling) +} + +/// [`text_limit_for`] with a given `ceiling`. +fn text_limit_within(len: usize, ceiling: usize) -> usize { + len.saturating_mul(TEXT_BYTES_PER_FILE_BYTE).clamp(MIN_TEXT_BYTES, ceiling.max(MIN_TEXT_BYTES)) +} +/// Per-tag overhead (one `(String, String)` entry) charged beside key/value text bytes so +/// zero-length `("", "")` tag pairs from string-table index 0 cannot allocate unbounded entries. +const TAG_OVERHEAD: usize = 48; +/// Per-member role overhead (one `String`) charged beside role text bytes. +const ROLE_OVERHEAD: usize = 24; /// Keys with a field of their own (as GDAL's OSM driver gives them). const KEYS: &[&str] = &[ @@ -256,6 +290,26 @@ fn ignored(key: &str) -> bool { || key.starts_with("openGeoDB:") } +/// Whether `keys`/`vals` hold any non-ignored tags and their combined retained byte cost +/// (UTF-8 key/value lengths plus [`TAG_OVERHEAD`] per entry). +fn tags_info(strings: &[String], keys: &[u64], vals: &[u64]) -> (bool, usize) { + let mut any = false; + let mut bytes = 0usize; + for (k, v) in keys.iter().zip(vals) { + let (Some(k), Some(v)) = + (usize::try_from(*k).ok().and_then(|i| strings.get(i)), usize::try_from(*v).ok().and_then(|i| strings.get(i))) + else { + continue; + }; + if ignored(k) { + continue; + } + any = true; + bytes = bytes.saturating_add(TAG_OVERHEAD).saturating_add(k.len()).saturating_add(v.len()); + } + (any, bytes) +} + fn tags(strings: &[String], keys: &[u64], vals: &[u64]) -> Tags { keys.iter() .zip(vals) @@ -269,7 +323,6 @@ fn tag<'t>(t: &'t [(String, String)], k: &str) -> Option<&'t str> { } /// What was read: nodes (sorted by id), tagged nodes, ways, and relations. -#[derive(Default)] struct Osm { nodes: Vec<(i64, i32, i32)>, points: Vec<(i64, Coord, Tags)>, @@ -281,6 +334,67 @@ struct Osm { capped: bool, /// Members omitted at the per-relation limit; wide enough for all bounded relations. omitted_members: u64, + /// Cumulative retained tag/role bytes (including per-entry overhead), tracked separately per + /// entity kind so heavy node tags early in a file cannot starve ways or relations. + node_text_bytes: usize, + way_text_bytes: usize, + relation_text_bytes: usize, + node_text_limit: usize, + way_text_limit: usize, + relation_text_limit: usize, + text_limit: usize, + /// Entities and decoded tag/role text bytes omitted after reaching a text budget. + text_capped_nodes: u64, + text_capped_ways: u64, + text_capped_relations: u64, + text_capped_bytes: u64, +} + +impl Osm { + fn with_text_limit(text_limit: usize) -> Self { + let share = text_limit / 3; + Osm { + nodes: Vec::new(), + points: Vec::new(), + ways: Vec::new(), + refs: 0, + relations: Vec::new(), + capped: false, + omitted_members: 0, + node_text_bytes: 0, + way_text_bytes: 0, + relation_text_bytes: 0, + node_text_limit: share, + way_text_limit: share, + relation_text_limit: text_limit.saturating_sub(share.saturating_mul(2)), + text_limit, + text_capped_nodes: 0, + text_capped_ways: 0, + text_capped_relations: 0, + text_capped_bytes: 0, + } + } + + fn try_charge(used: &mut usize, limit: usize, bytes: usize) -> bool { + let next = used.saturating_add(bytes); + if next > limit { + return false; + } + *used = next; + true + } + + fn try_charge_node_text(&mut self, bytes: usize) -> bool { + Self::try_charge(&mut self.node_text_bytes, self.node_text_limit, bytes) + } + + fn try_charge_way_text(&mut self, bytes: usize) -> bool { + Self::try_charge(&mut self.way_text_bytes, self.way_text_limit, bytes) + } + + fn try_charge_relation_text(&mut self, bytes: usize) -> bool { + Self::try_charge(&mut self.relation_text_bytes, self.relation_text_limit, bytes) + } } /// Degrees from OSM's fixed point (1e-7°), and back. @@ -346,7 +460,20 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { _ => {} } } - keep(osm, id, lat, lon, tags(&strings, &k, &vv)); + let (has_tags, cost) = tags_info(&strings, &k, &vv); + let t = if !has_tags { + Vec::new() + } else if osm.points.len() >= MAX_NODES { + osm.capped = true; + Vec::new() + } else if !osm.try_charge_node_text(cost) { + osm.text_capped_nodes = osm.text_capped_nodes.saturating_add(1); + osm.text_capped_bytes = osm.text_capped_bytes.saturating_add(cost as u64); + Vec::new() + } else { + tags(&strings, &k, &vv) + }; + keep(osm, id, lat, lon, t); } // Dense nodes. 2 => { @@ -361,22 +488,55 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { _ => {} } } - let mut kvi = kv.into_iter(); + let mut pos = 0usize; + let at = |i: u64| usize::try_from(i).ok().and_then(|i| strings.get(i)); for ((id, lat), lon) in ids.into_iter().zip(lats).zip(lons) { - let mut t = Vec::new(); - // Key, value pairs up to a 0. - while let Some(k) = kvi.next() { + let start = pos; + let mut has_tags = false; + let mut cost = 0usize; + // Key, value pairs up to a 0; measure cost before cloning any strings. + while let Some(&k) = kv.get(pos) { + pos += 1; if k == 0 { break; } - let Some(v) = kvi.next() else { break }; - let at = |i: u64| usize::try_from(i).ok().and_then(|i| strings.get(i)); + let Some(&v) = kv.get(pos) else { break }; + pos += 1; if let (Some(k), Some(v)) = (at(k), at(v)) && !ignored(k) { - t.push((k.clone(), v.clone())); + has_tags = true; + cost = cost.saturating_add(TAG_OVERHEAD).saturating_add(k.len()).saturating_add(v.len()); } } + let t = if !has_tags { + Vec::new() + } else if osm.points.len() >= MAX_NODES { + osm.capped = true; + Vec::new() + } else if !osm.try_charge_node_text(cost) { + osm.text_capped_nodes = osm.text_capped_nodes.saturating_add(1); + osm.text_capped_bytes = osm.text_capped_bytes.saturating_add(cost as u64); + Vec::new() + } else { + let mut t = Vec::new(); + let mut p = start; + while p < pos { + let Some(&k) = kv.get(p) else { break }; + p += 1; + if k == 0 { + break; + } + let Some(&v) = kv.get(p) else { break }; + p += 1; + if let (Some(k), Some(v)) = (at(k), at(v)) + && !ignored(k) + { + t.push((k.clone(), v.clone())); + } + } + t + }; keep(osm, id, lat, lon, t); } } @@ -401,14 +561,21 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { osm.capped = true; continue; } + let (has_tags, cost) = tags_info(&strings, &k, &vv); + if has_tags && !osm.try_charge_way_text(cost) { + osm.text_capped_ways = osm.text_capped_ways.saturating_add(1); + osm.text_capped_bytes = osm.text_capped_bytes.saturating_add(cost as u64); + continue; + } let places = (!lats.is_empty() && lats.len() == refs.len() && lons.len() == refs.len()).then(|| { lats.iter() .zip(&lons) .map(|(la, lo)| Coord::new(nano(lon_off, *lo) as f64 * 1e-9, nano(lat_off, *la) as f64 * 1e-9)) .collect() }); + let t = if has_tags { tags(&strings, &k, &vv) } else { Vec::new() }; osm.refs += refs.len(); - osm.ways.push((id, refs, tags(&strings, &k, &vv), places)); + osm.ways.push((id, refs, t, places)); } // A relation. 4 => { @@ -435,10 +602,17 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { previous }) .collect(); - let t = tags(&strings, &k, &vv); - // Only the relations drawn are kept, so only they meet the cap: one of - // another type is left out either way. - let drawn = matches!(tag(&t, "type"), Some("multipolygon" | "boundary")); + // Only the relations drawn are kept, so check before cloning or charging tags. + let drawn = k + .iter() + .zip(&vv) + .filter_map(|(ki, vi)| { + let k = usize::try_from(*ki).ok().and_then(|i| strings.get(i))?; + let v = usize::try_from(*vi).ok().and_then(|i| strings.get(i))?; + (!ignored(k)).then_some((k.as_str(), v.as_str())) + }) + .find(|(k, _)| *k == "type") + .is_some_and(|(_, v)| matches!(v, "multipolygon" | "boundary")); if drawn && osm.relations.len() >= MAX_RELATIONS { osm.capped = true; } else if drawn { @@ -450,6 +624,21 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { types.len() ))); } + let (_, tag_bytes) = tags_info(&strings, &k, &vv); + let role_bytes = roles + .iter() + .take(MAX_MEMBERS) + .map(|r| { + let len = usize::try_from(*r).ok().and_then(|i| strings.get(i)).map_or(0, String::len); + ROLE_OVERHEAD.saturating_add(len) + }) + .fold(0usize, usize::saturating_add); + let cost = tag_bytes.saturating_add(role_bytes); + if !osm.try_charge_relation_text(cost) { + osm.text_capped_relations = osm.text_capped_relations.saturating_add(1); + osm.text_capped_bytes = osm.text_capped_bytes.saturating_add(cost as u64); + continue; + } // Node members are never read, so only the others past the limit are // left out by it. let omitted = types.iter().skip(MAX_MEMBERS).filter(|ty| **ty != 0).count() as u64; @@ -463,7 +652,7 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { (ty, m, usize::try_from(role).ok().and_then(|r| strings.get(r)).cloned().unwrap_or_default()) }) .collect(); - osm.relations.push((id, members, t)); + osm.relations.push((id, members, tags(&strings, &k, &vv))); } } _ => {} @@ -473,9 +662,9 @@ fn block(osm: &mut Osm, data: &[u8]) -> Result<()> { Ok(()) } -/// Reads the file's blocks. -fn blocks(bytes: &[u8]) -> Result { - let mut osm = Osm::default(); +/// Reads the file's blocks within a `text_limit`-byte retained tag/role budget. +fn blocks_with_text_limit(bytes: &[u8], text_limit: usize) -> Result { + let mut osm = Osm::with_text_limit(text_limit); let mut i = 0usize; let mut saw_header = false; while i < bytes.len() { @@ -614,9 +803,13 @@ fn inside(p: Coord, ring: &[Coord]) -> bool { /// between blocks and between the ways and relations built from them; decoding one block is one /// step without a look. pub fn read(file_name: &str, bytes: &[u8]) -> Result> { + read_with_text_limit(file_name, bytes, text_limit_for(bytes.len())) +} + +fn read_with_text_limit(file_name: &str, bytes: &[u8], text_limit: usize) -> Result> { let stem = std::path::Path::new(file_name).file_name().and_then(|s| s.to_str()).unwrap_or("osm"); let stem = stem.trim_end_matches(".pbf").trim_end_matches(".osm").to_string(); - let mut osm = blocks(bytes)?; + let mut osm = blocks_with_text_limit(bytes, text_limit)?; osm.nodes.sort_unstable_by_key(|n| n.0); let node = |id: i64| -> Option { let i = osm.nodes.binary_search_by_key(&id, |n| n.0).ok()?; @@ -795,6 +988,30 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> .messages .push(crate::loss::Note::loss(crate::loss::LossCode::DroppedOverLimit, "the extract is larger than RustGIS reads at once: the rest is left out (use a smaller extract; on the desktop, files over 256 MB open through GDAL when it is installed)")); } + let text_capped_note = (osm.text_capped_nodes > 0 || osm.text_capped_ways > 0 || osm.text_capped_relations > 0).then(|| { + let mut parts = Vec::new(); + if osm.text_capped_nodes > 0 { + let n = osm.text_capped_nodes; + parts.push(format!("{n} {} (left out of points)", if n == 1 { "tagged node" } else { "tagged nodes" })); + } + if osm.text_capped_ways > 0 { + let n = osm.text_capped_ways; + parts.push(format!("{n} {} (omitted from lines/multipolygons)", if n == 1 { "tagged way" } else { "tagged ways" })); + } + if osm.text_capped_relations > 0 { + let n = osm.text_capped_relations; + parts.push(format!("{n} {} (omitted from multipolygons)", if n == 1 { "relation" } else { "relations" })); + } + format!( + "OSM tag/role text reached the {}-byte limit: {} ({} bytes of text and per-entry overhead left out)", + osm.text_limit, + parts.join(", "), + osm.text_capped_bytes, + ) + }); + if let Some(note) = &text_capped_note { + report.messages.push(crate::loss::Note::loss(crate::loss::LossCode::DroppedOverLimit, note.clone())); + } if missing > 0 { report.messages.push(crate::loss::Note::loss( crate::loss::LossCode::DroppedFeature, @@ -847,6 +1064,9 @@ pub fn read(file_name: &str, bytes: &[u8]) -> Result> *first = report; } if out.is_empty() { + if let Some(note) = text_capped_note { + return Err(DataError::Format(format!("{file_name}: {note}"))); + } return Err(DataError::Format(format!("{file_name}: nothing tagged to draw"))); } Ok(out) @@ -1474,4 +1694,257 @@ pub(crate) mod tests { let _g = crate::progress::install(Some(probe)); assert!(matches!(read("a.osm.pbf", &sample()), Err(DataError::Cancelled))); } + + #[test] + fn string_table_amplification_is_capped() { + let mut out = Vec::new(); + let mut header = Vec::new(); + field_bytes(4, b"OsmSchema-V0.6", &mut header); + field_bytes(4, b"DenseNodes", &mut header); + blob("OSMHeader", &header, false, &mut out); + + let big = "x".repeat(512); + let mut st = Vec::new(); + for s in ["", "name", big.as_str(), "type", "multipolygon", "route", "highway", "road"] { + field_bytes(1, s.as_bytes(), &mut st); + } + // Ten dense nodes all referencing the same 512-byte string entry (516 bytes each), plus + // one tagged way (527 bytes) and one drawn multipolygon relation (5136 bytes of roles/tags). + let ids: Vec = (1..=10).collect(); + let coords: Vec = ids.iter().map(|i| i * 1_000_000).collect(); + let mut kv = Vec::new(); + for _ in 0..10 { + kv.extend([1u64, 2, 0]); + } + let mut dense = Vec::new(); + field_bytes(1, &delta(&ids), &mut dense); + field_bytes(8, &delta(&coords), &mut dense); + field_bytes(9, &delta(&coords), &mut dense); + field_bytes(10, &packed_of(&kv), &mut dense); + + let mut way = Vec::new(); + field_varint(1, 100, &mut way); + field_bytes(2, &packed_of(&[6, 1]), &mut way); + field_bytes(3, &packed_of(&[7, 2]), &mut way); + field_bytes(8, &delta(&[1, 2]), &mut way); + + let mut rel = Vec::new(); + field_varint(1, 500, &mut rel); + field_bytes(2, &packed_of(&[3]), &mut rel); + field_bytes(3, &packed_of(&[4]), &mut rel); + field_bytes(8, &packed_of(&[2; 10]), &mut rel); + field_bytes(9, &delta(&ids), &mut rel); + field_bytes(10, &packed_of(&[1; 10]), &mut rel); + + let mut pg = Vec::new(); + field_bytes(2, &dense, &mut pg); + field_bytes(3, &way, &mut pg); + field_bytes(4, &rel, &mut pg); + let mut prim = Vec::new(); + field_bytes(1, &st, &mut prim); + field_bytes(2, &pg, &mut prim); + blob("OSMData", &prim, true, &mut out); + + // Under a 1800-byte total budget (600 bytes per entity kind): + // - node 1 (48 + 516 = 564 bytes) fits; nodes 2..=10 (9 * 564 = 5076 bytes) exceed the + // node share; + // - the tagged way (2 * 48 + 527 = 623 bytes) exceeds the 600-byte way share; + // - the drawn relation (48 + 16 + 10 * (24 + 512) = 5424 bytes) exceeds the 600-byte + // relation share. + let layers = read_with_text_limit("cap.osm.pbf", &out, 1800).unwrap(); + assert_eq!(layers.len(), 1, "only points remain after way and relation are omitted"); + assert_eq!(layers[0].0.features.len(), 1); + let expected_bytes = 9 * (TAG_OVERHEAD + 516) + (2 * TAG_OVERHEAD + 527) + (TAG_OVERHEAD + 16 + 10 * (ROLE_OVERHEAD + 512)); + let note = layers[0] + .1 + .messages + .iter() + .find(|m| m.loss == Some(crate::loss::LossCode::DroppedOverLimit)) + .expect("must emit a DroppedOverLimit notice"); + assert_eq!( + note.as_str(), + format!( + "OSM tag/role text reached the 1800-byte limit: 9 tagged nodes (left out of points), 1 tagged way (omitted from lines/multipolygons), 1 relation (omitted from multipolygons) ({expected_bytes} bytes of text and per-entry overhead left out)" + ) + ); + + // Within a generous budget, no text-budget notice is emitted. + let full = read_with_text_limit("cap.osm.pbf", &out, 64 * 1024).unwrap(); + assert_eq!(full[0].0.features.len(), 10); + assert_eq!(full[1].0.features.len(), 1); + assert!(!full[0].1.messages.iter().any(|m| m.loss == Some(crate::loss::LossCode::DroppedOverLimit))); + + // Discarded relations (type=route) must not charge the text budget or emit a notice. + let mut route_out = Vec::new(); + blob("OSMHeader", &header, false, &mut route_out); + let mut route_pg = Vec::new(); + for rid in 1..=10u64 { + let mut r = Vec::new(); + field_varint(1, rid, &mut r); + field_bytes(2, &packed_of(&[3, 1]), &mut r); + field_bytes(3, &packed_of(&[5, 2]), &mut r); + field_bytes(8, &packed_of(&[2; 10]), &mut r); + field_bytes(9, &delta(&ids), &mut r); + field_bytes(10, &packed_of(&[1; 10]), &mut r); + field_bytes(4, &r, &mut route_pg); + } + let mut route_prim = Vec::new(); + field_bytes(1, &st, &mut route_prim); + field_bytes(2, &route_pg, &mut route_prim); + blob("OSMData", &route_prim, true, &mut route_out); + let route_osm = blocks_with_text_limit(&route_out, 1800).unwrap(); + assert_eq!(route_osm.relation_text_bytes, 0); + assert_eq!(route_osm.text_capped_relations, 0); + } + + /// Zero-length `("", "")` tag pairs from string-table index 0 still charge per-tag overhead, + /// so they cannot allocate unbounded `(String, String)` entries at zero budget cost. + #[test] + fn zero_length_tags_still_hit_text_budget() { + let mut out = Vec::new(); + let mut header = Vec::new(); + field_bytes(4, b"OsmSchema-V0.6", &mut header); + field_bytes(4, b"DenseNodes", &mut header); + blob("OSMHeader", &header, false, &mut out); + + let mut st = Vec::new(); + for s in ["", "name", "ok"] { + field_bytes(1, s.as_bytes(), &mut st); + } + // Two dense nodes (first tagged so a points layer exists). + let mut dense = Vec::new(); + field_bytes(1, &delta(&[1, 2]), &mut dense); + field_bytes(8, &delta(&[0, 1_000_000]), &mut dense); + field_bytes(9, &delta(&[0, 1_000_000]), &mut dense); + field_bytes(10, &packed_of(&[1, 2, 0, 0]), &mut dense); + + // One way carrying 30 zero-length ("", "") tag pairs (30 * TAG_OVERHEAD = 1440 bytes). + let mut way = Vec::new(); + field_varint(1, 200, &mut way); + field_bytes(2, &packed_of(&[0; 30]), &mut way); + field_bytes(3, &packed_of(&[0; 30]), &mut way); + field_bytes(8, &delta(&[1, 2]), &mut way); + + let mut pg = Vec::new(); + field_bytes(2, &dense, &mut pg); + field_bytes(3, &way, &mut pg); + let mut prim = Vec::new(); + field_bytes(1, &st, &mut prim); + field_bytes(2, &pg, &mut prim); + blob("OSMData", &prim, true, &mut out); + + // Total budget 3000 -> 1000-byte way share < 1440-byte zero-length tag overhead. + let layers = read_with_text_limit("empty-tags.osm.pbf", &out, 3000).unwrap(); + assert_eq!(layers.len(), 1, "way with excess zero-length tags must be omitted"); + let expected = 30 * TAG_OVERHEAD; + let note = layers[0] + .1 + .messages + .iter() + .find(|m| m.loss == Some(crate::loss::LossCode::DroppedOverLimit)) + .expect("must emit DroppedOverLimit notice for zero-length tags"); + assert_eq!( + note.as_str(), + format!( + "OSM tag/role text reached the 3000-byte limit: 1 tagged way (omitted from lines/multipolygons) ({expected} bytes of text and per-entry overhead left out)" + ) + ); + } + + /// Exhausting the node text budget early in a file must not starve tagged ways or drawn + /// relations that appear later. + #[test] + fn node_text_budget_does_not_starve_ways_or_relations() { + let mut out = Vec::new(); + let mut header = Vec::new(); + field_bytes(4, b"OsmSchema-V0.6", &mut header); + field_bytes(4, b"DenseNodes", &mut header); + blob("OSMHeader", &header, false, &mut out); + + let big = "x".repeat(512); + let mut st = Vec::new(); + for s in ["", "name", big.as_str(), "highway", "road", "type", "multipolygon", "outer"] { + field_bytes(1, s.as_bytes(), &mut st); + } + // Ten dense nodes (first 4 form a square for the relation), all with 512-byte names. + let ids: Vec = (1..=10).collect(); + let lons = vec![0, 1_000_000, 1_000_000, 0, 2_000_000, 3_000_000, 4_000_000, 5_000_000, 6_000_000, 7_000_000]; + let lats = vec![0, 0, 1_000_000, 1_000_000, 0, 0, 0, 0, 0, 0]; + let mut kv = Vec::new(); + for _ in 0..10 { + kv.extend([1u64, 2, 0]); + } + let mut dense = Vec::new(); + field_bytes(1, &delta(&ids), &mut dense); + field_bytes(8, &delta(&lats), &mut dense); + field_bytes(9, &delta(&lons), &mut dense); + field_bytes(10, &packed_of(&kv), &mut dense); + + // Way 100: small tagged road (fits easily in way share). + let mut road = Vec::new(); + field_varint(1, 100, &mut road); + field_bytes(2, &packed_of(&[3]), &mut road); + field_bytes(3, &packed_of(&[4]), &mut road); + field_bytes(8, &delta(&[5, 6]), &mut road); + + // Way 101: untagged closed outer ring for relation 200. + let mut ring = Vec::new(); + field_varint(1, 101, &mut ring); + field_bytes(8, &delta(&[1, 2, 3, 4, 1]), &mut ring); + + // Relation 200: small multipolygon (fits easily in relation share). + let mut rel = Vec::new(); + field_varint(1, 200, &mut rel); + field_bytes(2, &packed_of(&[5]), &mut rel); + field_bytes(3, &packed_of(&[6]), &mut rel); + field_bytes(8, &packed_of(&[7]), &mut rel); + field_bytes(9, &delta(&[101]), &mut rel); + field_bytes(10, &packed_of(&[1]), &mut rel); + + let mut pg = Vec::new(); + field_bytes(2, &dense, &mut pg); + field_bytes(3, &road, &mut pg); + field_bytes(3, &ring, &mut pg); + field_bytes(4, &rel, &mut pg); + let mut prim = Vec::new(); + field_bytes(1, &st, &mut prim); + field_bytes(2, &pg, &mut prim); + blob("OSMData", &prim, true, &mut out); + + // Budget 1800 -> 600 per kind: only 1 of 10 tagged nodes fits, but both road and + // multipolygon relation remain intact. + let layers = read_with_text_limit("isolated.osm.pbf", &out, 1800).unwrap(); + assert_eq!(layers.len(), 3, "points, lines, and multipolygons must all be present"); + assert_eq!(layers[0].0.features.len(), 1, "only 1 tagged node fits in node budget"); + assert_eq!(layers[1].0.features.len(), 1, "tagged way must not be starved by nodes"); + assert_eq!(layers[2].0.features.len(), 1, "multipolygon relation must not be starved by nodes"); + let note = layers[0] + .1 + .messages + .iter() + .find(|m| m.loss == Some(crate::loss::LossCode::DroppedOverLimit)) + .expect("node cap notice must be emitted"); + assert!(note.contains("9 tagged nodes (left out of points)"), "{note:?}"); + assert!(!note.contains("tagged way") && !note.contains("relation"), "{note:?}"); + } + + /// The text budget follows the file's size between its floor and ceiling, so an ordinary + /// extract (Berlin's 100 MB holds 721 MiB of tag text) keeps its tags. + #[test] + fn text_budget_follows_the_file_size() { + assert_eq!(text_limit_within(0, MAX_TEXT_BYTES), MIN_TEXT_BYTES); + assert_eq!(text_limit_within(1 << 20, MAX_TEXT_BYTES), MIN_TEXT_BYTES); + assert_eq!(text_limit_within(usize::MAX, MAX_TEXT_BYTES), MAX_TEXT_BYTES); + // The computer's share caps it, never below the floor. + assert_eq!(text_limit_within(100_000_000, 1 << 30), 1 << 30); + assert_eq!(text_limit_within(100_000_000, 0), MIN_TEXT_BYTES); + let planned = text_limit_for(usize::MAX); + assert!((MIN_TEXT_BYTES..=MAX_TEXT_BYTES).contains(&planned), "{planned}"); + if cfg!(target_pointer_width = "64") { + let berlin = text_limit_within(100_000_000, MAX_TEXT_BYTES); + assert_eq!(berlin, 2_400_000_000); + // Each kind's third is above the 393 MiB Berlin's ways need. + assert!(berlin / 3 > 393 << 20); + } + } } diff --git a/crates/data/src/query.rs b/crates/data/src/query.rs index c59c51dc76..ba0044c64c 100644 --- a/crates/data/src/query.rs +++ b/crates/data/src/query.rs @@ -2382,10 +2382,26 @@ impl<'a> Eval<'a> { let mut best: Option<(f64, Cow<'a, Value>)> = None; for a in args { let v = read(a); - let Some(x) = v.as_f64() else { continue }; + let Some(x) = number(&v) else { continue }; let better = match &best { None => true, - Some((b, _)) => (f == Func::Min && x < *b) || (f == Func::Max && x > *b), + Some((b, bv)) => { + // Whole numbers, as integers or as text, compare exactly: through + // f64, neighbours above 2^53 would be equal. + let whole = |v: &Value| match v { + Value::Int(i) => Some(*i), + Value::Text(t) => t.trim().parse::().ok(), + _ => None, + }; + let ord = match (&*v, &**bv) { + _ if whole(&v).is_some() && whole(bv).is_some() => whole(&v).cmp(&whole(bv)), + (Value::Int(_), _) | (_, Value::Int(_)) => { + v.partial_cmp(bv).unwrap_or_else(|| x.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)) + } + _ => x.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal), + }; + (f == Func::Min && ord.is_lt()) || (f == Func::Max && ord.is_gt()) + } }; if better { best = Some((x, v)); diff --git a/crates/data/src/query/tests.rs b/crates/data/src/query/tests.rs index bd108bcabe..90863ecd27 100644 --- a/crates/data/src/query/tests.rs +++ b/crates/data/src/query/tests.rs @@ -944,6 +944,44 @@ fn errors_say_why_they_are_null() { assert_eq!(why("sqrt(0)", 0), (Value::Float(0.0), None)); } +#[test] +fn min_and_max_report_non_number_faults_and_keep_i64_precision() { + let mut odd = Dataset::new( + "odd", + GeometryType::None, + vec![ + Field::new("x", FieldType::Double), + Field::new("label", FieldType::Text), + Field::new("n", FieldType::Integer), + Field::new("a", FieldType::Integer), + Field::new("b", FieldType::Integer), + ], + ); + odd.push( + None, + vec![ + Value::Float(f64::NAN), + Value::Text("abc".into()), + Value::Null, + Value::Int(9_007_199_254_740_992), + Value::Int(9_007_199_254_740_993), + ], + ); + let run = |text: &str| { + let e = parse(text, &odd).unwrap_or_else(|e| panic!("{text}: {e}")); + value_or_fault(&e, &odd, 0, &Env::default()) + }; + assert_eq!(run("min(label, n)"), (Value::Null, Some(Fault::Text))); + assert_eq!(run("max(x, n)"), (Value::Null, Some(Fault::NotANumber))); + assert_eq!(run("min(n, 5)"), (Value::Int(5), None)); + assert_eq!(run("max(a, b)"), (Value::Int(9_007_199_254_740_993), None)); + assert_eq!(run("min(b, a)"), (Value::Int(9_007_199_254_740_992), None)); + assert_eq!(run("min('2', '10')"), (Value::Text("2".into()), None)); + // Whole-number text above 2^53 compares exactly too. + assert_eq!(run("min('9007199254740993', '9007199254740992')"), (Value::Text("9007199254740992".into()), None)); + assert_eq!(run("max('9007199254740992', '9007199254740993')"), (Value::Text("9007199254740993".into()), None)); +} + #[test] fn text_equality_and_like_preserve_unicode_and_numeric_semantics() { let mut d = Dataset::new( diff --git a/crates/data/src/raster/grib/complex.rs b/crates/data/src/raster/grib/complex.rs index 318e8a0cb7..8a063384ff 100644 --- a/crates/data/src/raster/grib/complex.rs +++ b/crates/data/src/raster/grib/complex.rs @@ -195,12 +195,15 @@ impl Values<'_> { let packed = bits(self.data, self.at, self.width); self.at += u64::from(self.width); // Missing: every bit set (one less, the secondary missing value) in the value, or in the - // reference of a group of no bits. + // reference of a group of no bits. When both widths are 0 there are no bits to carry a + // missing sentinel, so the group is a constant value. if p.missing > 0 { let (v, width) = if self.width == 0 { (self.reference, p.ref_bits) } else { (packed, self.width) }; - let ones = (1u64 << width) - 1; - if v == ones || (p.missing == 2 && v + 1 == ones) { - return None; + if width > 0 { + let ones = (1u64 << width) - 1; + if v == ones || (p.missing == 2 && v + 1 == ones) { + return None; + } } } // At most 33 bits, so the sums below are far from `i64`'s range. diff --git a/crates/data/src/raster/grib_tests.rs b/crates/data/src/raster/grib_tests.rs index 43ae13ca00..f446d25001 100644 --- a/crates/data/src/raster/grib_tests.rs +++ b/crates/data/src/raster/grib_tests.rs @@ -1425,6 +1425,17 @@ fn complex_packing_marks_missing_values() { assert!(r.rounded.is_empty() && r.lost.len() == 1, "{:?}", r.lost); } +#[test] +fn complex_packing_zero_bit_constant_group_with_missing_management() { + for missing in [1, 2] { + let mut c = Cx::new(&[(0, 0, &[0, 0, 0])]); + c.ref_bits = 0; + c.r = 12.5; + c.missing = missing; + assert_eq!(c.values(), vec![12.5, 12.5, 12.5], "missing={missing}"); + } +} + #[test] fn spatial_differencing_is_undone() { // 100, 103, 101, 101, 90: differences 3, −2, 0, −11, the least −11. diff --git a/crates/data/src/sheets.rs b/crates/data/src/sheets.rs index 7967084a71..4ed4563b6b 100644 --- a/crates/data/src/sheets.rs +++ b/crates/data/src/sheets.rs @@ -541,6 +541,24 @@ fn damaged(what: &str) -> Result { Err(DataError::Format(format!("spreadsheet: the .xls file is damaged ({what})"))) } +/// Grows `bounds` (`r0, r1, c0, c1`) to include `(r, c)` and refuses spans past [`MAX_CELLS`]. +fn grow_sheet_bounds(bounds: &mut Option<(u32, u32, u32, u32)>, (r, c): (u32, u32), sheet: &str) -> Result<()> { + let (r0, r1, c0, c1) = bounds.map_or((r, r, c, c), |(r0, r1, c0, c1)| (r0.min(r), r1.max(r), c0.min(c), c1.max(c))); + *bounds = Some((r0, r1, c0, c1)); + let rows = u64::from(r1 - r0) + 1; + let cols = u64::from(c1 - c0) + 1; + if rows.saturating_mul(cols) > MAX_CELLS as u64 { + return Err(DataError::Format(format!( + "sheet '{sheet}' is too large (cells from row {} to {}, column {} to {})", + u64::from(r0) + 1, + u64::from(r1) + 1, + column_letter(c0 as usize), + column_letter(c1 as usize) + ))); + } + Ok(()) +} + /// Refuses a sheet whose cells span more than [`MAX_CELLS`] before calamine lays it out as a dense /// grid (one cell at `XFD1048576` would ask for 17 billion): an `.xlsx` or `.xlsb` sheet's cells /// are read one at a time for their extent first. Every `.xls` sheet's BIFF records and cell @@ -548,33 +566,18 @@ fn damaged(what: &str) -> Result { /// extents are checked by [`check_expansion`] before its eagerly loaded sheets are allocated. fn check_size(wb: &mut Sheets>, sheet: &str) -> Result<()> { let mut b: Option<(u32, u32, u32, u32)> = None; - let mut grow = |(r, c): (u32, u32)| -> Result<()> { - let (r0, r1, c0, c1) = b.map_or((r, r, c, c), |(r0, r1, c0, c1)| (r0.min(r), r1.max(r), c0.min(c), c1.max(c))); - b = Some((r0, r1, c0, c1)); - let cells = ((r1 - r0) as usize + 1).saturating_mul((c1 - c0) as usize + 1); - if cells > MAX_CELLS { - return Err(DataError::Format(format!( - "sheet '{sheet}' is too large (cells from row {} to {}, column {} to {})", - r0 + 1, - r1 + 1, - column_letter(c0 as usize), - column_letter(c1 as usize) - ))); - } - Ok(()) - }; let bad = |e: String| DataError::Format(format!("sheet '{sheet}': {e}")); match wb { Sheets::Xlsx(x) => { let mut cells = x.worksheet_cells_reader(sheet).map_err(|e| bad(e.to_string()))?; while let Some(c) = cells.next_cell().map_err(|e| bad(e.to_string()))? { - grow(c.get_position())?; + grow_sheet_bounds(&mut b, c.get_position(), sheet)?; } } Sheets::Xlsb(x) => { let mut cells = x.worksheet_cells_reader(sheet).map_err(|e| bad(e.to_string()))?; while let Some(c) = cells.next_cell().map_err(|e| bad(e.to_string()))? { - grow(c.get_position())?; + grow_sheet_bounds(&mut b, c.get_position(), sheet)?; } } Sheets::Xls(_) | Sheets::Ods(_) => {} @@ -1669,4 +1672,16 @@ mod tests { let names: Vec<&str> = ds.fields.iter().map(|f| f.name.as_str()).collect(); assert_eq!(names, ["name", "D"]); } + + #[test] + fn sheet_bounds_never_overflow_u32_max() { + let mut bounds = None; + grow_sheet_bounds(&mut bounds, (0, 0), "S").unwrap(); + let err = grow_sheet_bounds(&mut bounds, (u32::MAX, 0), "S").unwrap_err().to_string(); + assert!(err.contains("row 1 to 4294967296"), "{err}"); + + let mut col_bounds = None; + grow_sheet_bounds(&mut col_bounds, (0, 0), "S").unwrap(); + assert!(grow_sheet_bounds(&mut col_bounds, (0, u32::MAX), "S").is_err()); + } } diff --git a/crates/data/src/sqlite.rs b/crates/data/src/sqlite.rs index f22cf32aa2..6e2d4d33b7 100644 --- a/crates/data/src/sqlite.rs +++ b/crates/data/src/sqlite.rs @@ -609,36 +609,71 @@ fn column_list(sql: &str) -> Option<(usize, usize)> { None } -/// Splits on commas outside parentheses and quotes. +/// Splits on commas outside parentheses, quotes and SQL comments. fn split_top(s: &str) -> Vec { + let cs: Vec = s.chars().collect(); let mut out = Vec::new(); let mut cur = String::new(); let mut depth = 0usize; let mut quote: Option = None; - for c in s.chars() { + let mut i = 0; + while let Some(&c) = cs.get(i) { match quote { Some(q) => { cur.push(c); - if c == q || (q == '[' && c == ']') { + let close = if q == '[' { ']' } else { q }; + if c == close { + if close != ']' && cs.get(i + 1) == Some(&close) { + cur.push(close); + i += 2; + continue; + } quote = None; } + i += 1; } - None => match c { - '"' | '\'' | '`' | '[' => { - quote = Some(c); - cur.push(c); - } - '(' => { - depth += 1; - cur.push(c); - } - ')' => { - depth = depth.saturating_sub(1); + None => { + if c == '-' && cs.get(i + 1) == Some(&'-') { + while let Some(&d) = cs.get(i) { + cur.push(d); + i += 1; + if d == '\n' { + break; + } + } + } else if c == '/' && cs.get(i + 1) == Some(&'*') { cur.push(c); + cur.push('*'); + i += 2; + while let Some(&d) = cs.get(i) { + cur.push(d); + i += 1; + if d == '*' && cs.get(i) == Some(&'/') { + cur.push('/'); + i += 1; + break; + } + } + } else { + match c { + '"' | '\'' | '`' | '[' => { + quote = Some(c); + cur.push(c); + } + '(' => { + depth += 1; + cur.push(c); + } + ')' => { + depth = depth.saturating_sub(1); + cur.push(c); + } + ',' if depth == 0 => out.push(std::mem::take(&mut cur)), + c => cur.push(c), + } + i += 1; } - ',' if depth == 0 => out.push(std::mem::take(&mut cur)), - c => cur.push(c), - }, + } } } if !cur.trim().is_empty() { @@ -752,6 +787,21 @@ mod tests { assert_eq!(p.stored_order.as_deref(), Some(&[1, 2, 3, 0][..])); } + #[test] + fn create_table_with_comments_containing_commas_parens_and_quotes() { + let sql = "CREATE TABLE t ( + a INTEGER, -- don't, split (here) + /* block, comment with 'apostrophe and (paren */ + b TEXT DEFAULT 'don''t, split', + c REAL /* trailing, (comment) */ + )"; + let (cols, _) = parse_create_table(sql).unwrap(); + let names: Vec<&str> = cols.iter().map(|c| c.name.as_str()).collect(); + let decls: Vec<&str> = cols.iter().map(|c| c.decl.as_str()).collect(); + assert_eq!(names, ["a", "b", "c"]); + assert_eq!(decls, ["INTEGER", "TEXT", "REAL"]); + } + #[test] fn varints_and_records() { assert_eq!(varint(&[0x7f], 0), Some((127, 1))); diff --git a/crates/tiles/src/cache.rs b/crates/tiles/src/cache.rs index 70f47305c2..fc7d01e933 100644 --- a/crates/tiles/src/cache.rs +++ b/crates/tiles/src/cache.rs @@ -1567,6 +1567,11 @@ fn decode_with( /// a fragment, so it never reaches the server, which gets a `Range` header instead. pub const RANGE: &str = "#rustgis-range="; +/// Length of an inclusive byte range `a..=b`, or `None` when `a > b` or `b - a + 1` overflows `u64`. +pub fn range_len(a: u64, b: u64) -> Option { + b.checked_sub(a)?.checked_add(1) +} + /// Splits an address into the address to fetch and the byte range it asks for, if any. pub fn split_range(url: &str) -> (&str, Option<(u64, u64)>) { match url.rsplit_once(RANGE) { @@ -3713,7 +3718,8 @@ mod native { if let Some(local) = url.strip_prefix(LOCAL) { let (path, range) = super::split_range(local); let (a, b) = range.ok_or("a local read without a range")?; - return crate::pmtiles::read_file(path, a, b - a + 1) + let len = super::range_len(a, b).ok_or("a local read with an overflowing range")?; + return crate::pmtiles::read_file(path, a, len) .map(|bytes| Fetched { bytes, origin: Origin::named(url) }) .map_err(Failure::from); } @@ -3721,6 +3727,11 @@ mod native { let max = limit.unwrap_or(MAX_BYTES); let (url, mut tail) = super::split_tail(url); let (url, mut range) = super::split_range(url); + if let Some((a, b)) = range + && super::range_len(a, b).is_none() + { + return Err("byte range is inverted or its length overflows".into()); + } // The last bytes asked for, while the file's length is asked for instead (see below). let mut measuring: Option = None; // Explicit service logins outrank implicit S3 endpoint signing. @@ -3924,10 +3935,11 @@ mod native { return Err(format!("larger than {max} bytes").into()); } if let Some((a, b)) = range.filter(|_| whole) { - if buf.len() as u64 > b - a + 1 { + let len = super::range_len(a, b).ok_or("byte range is inverted or its length overflows")?; + if buf.len() as u64 > len { return Err(rustgis_data::diagnostics::message_with_address(url, super::NO_RANGES).into()); } - buf.truncate(usize::try_from(b - a + 1).unwrap_or(usize::MAX)); + buf.truncate(usize::try_from(len).unwrap_or(usize::MAX)); } Ok(Fetched { bytes: buf, origin }) }; @@ -8212,4 +8224,20 @@ Connection: close assert_eq!(ceiling_for(&tile), crate::address::Reach::Public); assert!(matches!(get_tile(&tile, Want::Image), State::Failed(_))); } + + #[test] + fn byte_range_overflow_is_rejected() { + assert_eq!(range_len(5, 5), Some(1)); + assert_eq!(range_len(10, 5), None); + assert_eq!(range_len(0, u64::MAX), None); + #[cfg(not(target_arch = "wasm32"))] + { + let _turn = turn(); + let (tx, rx) = std::sync::mpsc::channel(); + let url = format!("https://example.invalid/data.bin{RANGE}0-{}", u64::MAX); + native::fetch_reached(url, crate::address::Reach::Public, Box::new(move |r| tx.send(r).unwrap()), &[]); + let err = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap().unwrap_err(); + assert!(err.contains("overflows"), "{err}"); + } + } } diff --git a/crates/tiles/src/cog.rs b/crates/tiles/src/cog.rs index 604e7042dc..6376bf0ecf 100644 --- a/crates/tiles/src/cog.rs +++ b/crates/tiles/src/cog.rs @@ -547,7 +547,10 @@ fn read(url: &str, at: u64, len: u64, ceiling: crate::address::Reach, done: Done done(Err(format!("{len} bytes is too large to read from a GeoTIFF"))); return; } - let end = at.saturating_add(len) - 1; + let Some(end) = at.checked_add(len).and_then(|e| e.checked_sub(1)) else { + done(Err("byte range overflows GeoTIFF offset".into())); + return; + }; if is_local_file(url) { if let Err(e) = local_read_allowed(url, ceiling) { done(Err(e)); @@ -2855,4 +2858,14 @@ mod tests { forget_local_file(&url); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn overflowing_byte_range_returns_error() { + let _turn = crate::cache::turn(); + crate::cache::set_fetcher(|url, _done| panic!("unexpected fetch for overflowing range: {url}")); + let (tx, rx) = std::sync::mpsc::channel(); + read("https://example.invalid/a.tif", u64::MAX, 16, crate::address::Reach::Public, Box::new(move |r| tx.send(r).unwrap())); + let err = rx.recv_timeout(Duration::from_secs(5)).unwrap().unwrap_err(); + assert!(err.contains("overflows"), "{err}"); + } } diff --git a/crates/tiles/src/pmtiles.rs b/crates/tiles/src/pmtiles.rs index 5533bb6b36..8ddb2a3832 100644 --- a/crates/tiles/src/pmtiles.rs +++ b/crates/tiles/src/pmtiles.rs @@ -711,7 +711,7 @@ fn find(archive: String, info: Arc, id: u64, dir: Arc>, depth: if e.run_length > 0 { let tile = info.tile; // Within the tile data section (when the header gives its length). - let inside = info.data_length == 0 || e.offset.saturating_add(e.length) <= info.data_length; + let inside = info.data_length == 0 || e.offset.checked_add(e.length).is_some_and(|end| end <= info.data_length); let Some(at) = info.data_offset.checked_add(e.offset).filter(|_| inside) else { done(Err("a tile outside the archive".into())); return; @@ -724,11 +724,11 @@ fn find(archive: String, info: Arc, id: u64, dir: Arc>, depth: done(Err("PMTiles directories nested too deep".into())); return; } - if e.offset.saturating_add(e.length) > info.leaf_length { + let inside = e.offset.checked_add(e.length).is_some_and(|end| end <= info.leaf_length); + let Some(at) = info.leaf_offset.checked_add(e.offset).filter(|_| inside) else { done(Err("a leaf directory outside the archive".into())); return; - } - let at = info.leaf_offset.saturating_add(e.offset); + }; let key = (archive.clone(), at); // Continues the lookup once the leaf is there. let next: Box>, String>) + Send> = { @@ -836,7 +836,10 @@ fn read(archive: &str, at: u64, len: u64, done: Done) { done(Err(format!("{len} bytes is too large to read from an archive"))); return; } - let end = at.saturating_add(len) - 1; + let Some(end) = at.checked_add(len).and_then(|e| e.checked_sub(1)) else { + done(Err("byte range overflows archive offset".into())); + return; + }; let url = format!("{archive}{}{at}-{end}", crate::cache::RANGE); if is_local(archive) { if let Err(e) = check_local(archive) { @@ -2109,6 +2112,16 @@ pub(crate) mod tests { let _ = std::fs::remove_dir_all(dir); } + #[test] + fn overflowing_byte_range_returns_error() { + let _turn = crate::cache::turn(); + crate::cache::set_fetcher(|url, _done| panic!("unexpected fetch for overflowing range: {url}")); + let (tx, rx) = std::sync::mpsc::channel(); + read("https://example.invalid/a.pmtiles", u64::MAX, 16, Box::new(move |r| tx.send(r).unwrap())); + let err = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap().unwrap_err(); + assert!(err.contains("overflows"), "{err}"); + } + #[test] fn check_local_path_rejects_mixed_separators_and_drive_relative() { for good in [ diff --git a/crates/tiles/src/stac.rs b/crates/tiles/src/stac.rs index b4dd88b69e..6127029b34 100644 --- a/crates/tiles/src/stac.rs +++ b/crates/tiles/src/stac.rs @@ -905,39 +905,67 @@ pub fn resolve(base: &str, href: &str) -> Option { Some(crate::logins::inherit(base, &resolved)) } +/// Whether `s` begins with an RFC 3986 scheme followed by `://`. +fn has_scheme(s: &str) -> bool { + let Some((scheme, _)) = s.split_once("://") else { return false }; + let mut bytes = scheme.bytes(); + bytes.next().is_some_and(|b| b.is_ascii_alphabetic()) && bytes.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.')) +} + fn resolve_plain(base: &str, href: &str) -> Option { let href = href.trim(); if href.is_empty() || href.len() > MAX_TEXT || href.chars().any(char::is_control) { return None; } - if href.contains("://") { + if has_scheme(href) { return Some(href.to_string()); } let (scheme, rest) = base.split_once("://")?; - let host_end = rest.find('/').unwrap_or(rest.len()); + let host_end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); let origin = format!("{scheme}://{}", rest.get(..host_end)?); if let Some(abs) = href.strip_prefix("//") { return Some(format!("{scheme}://{abs}")); } + let (href_path, tail) = match href.find(['?', '#']) { + Some(i) => (href.get(..i)?, href.get(i..)?), + None => (href, ""), + }; + let normalize = |raw: &str| { + let mut out: Vec<&str> = Vec::new(); + let segments: Vec<&str> = raw.split('/').collect(); + let last = segments.len().saturating_sub(1); + for (i, seg) in segments.iter().enumerate() { + match *seg { + "." => {} + ".." => { + if out.len() > 1 { + out.pop(); + } + } + s => out.push(s), + } + if i == last && matches!(*seg, "." | "..") { + out.push(""); + } + } + out.join("/") + }; if href.starts_with('/') { - return Some(format!("{origin}{href}")); + return Some(format!("{origin}{}{tail}", normalize(href_path))); } - // Relative to the base's folder, with `./` and `../` worked out. let path = rest.get(host_end..).unwrap_or("").split(['?', '#']).next().unwrap_or(""); - let mut parts: Vec<&str> = path.split('/').filter(|p| !p.is_empty()).collect(); - if !path.ends_with('/') { - parts.pop(); - } - for seg in href.split('/') { - match seg { - "." => {} - ".." => { - parts.pop(); - } - s => parts.push(s), - } + if href_path.is_empty() { + // RFC 3986 section 5.2.2: an empty reference path keeps the document path, and keeps its + // query only when the reference supplies none. A base fragment is never inherited. + let query = if href.starts_with('?') { + "" + } else { + rest.split('#').next().and_then(|r| r.find('?').and_then(|i| r.get(i..))).unwrap_or("") + }; + return Some(format!("{origin}{path}{query}{tail}")); } - Some(format!("{origin}/{}", parts.join("/"))) + let dir = path.rfind('/').map_or("/", |i| path.get(..=i).unwrap_or("/")); + Some(format!("{origin}{}{tail}", normalize(&format!("{dir}{href_path}")))) } impl Asset { @@ -1647,6 +1675,19 @@ mod tests { assert_eq!(resolve("https://x.org/a", "//y.org/d.tif").as_deref(), Some("https://y.org/d.tif")); assert_eq!(resolve("https://x.org/a", "s3://b/k").as_deref(), Some("s3://b/k")); assert_eq!(resolve("https://x.org/a", ""), None); + // RFC 3986 query/fragment links, scheme detection, and authority boundary on `?` and `#`. + assert_eq!(resolve("https://api.example/v1/search", "?token=page2").as_deref(), Some("https://api.example/v1/search?token=page2")); + assert_eq!( + resolve("https://api.example/v1/search?limit=10", "?next=https://other.example/x").as_deref(), + Some("https://api.example/v1/search?next=https://other.example/x") + ); + assert_eq!( + resolve("https://api.example/v1/search?limit=10#old", "#new").as_deref(), + Some("https://api.example/v1/search?limit=10#new") + ); + assert_eq!(resolve("https://stac.example?f=json", "/items/1").as_deref(), Some("https://stac.example/items/1")); + assert_eq!(resolve("https://stac.example?f=json", "items/1").as_deref(), Some("https://stac.example/items/1")); + assert_eq!(resolve("https://x.org/a/b", "rel/https://not-a-scheme").as_deref(), Some("https://x.org/a/rel/https://not-a-scheme")); } /// JAXA Earth's codes for a failed retrieval: read whole, or the asset says they weren't.