Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Geospatial: fix the review findings (nesting, prime meridian, ring sorting, ZIP bombs, DBF)

KAPPI19254a3f1d1db6a1
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 40009eda..c98d0d7f 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -750,10 +750,12 @@ What each format keeps:
**Coordinate systems.** Geographic systems (degrees) and the projections most projected data uses, read from a `.prj`
(ESRI or OGC WKT 1), a GeoJSON `crs` name or an EPSG code: Transverse Mercator (UTM, Gauss-Krüger, state plane, via
Krüger's series), Mercator and Web Mercator, Lambert Conformal Conic (1 and 2 parallels), Albers;
-metres, feet and US survey feet. They agree with PROJ to well under a millimetre: `GeoCrsTests` checks ten systems against reference
-positions computed with pyproj. Anything else (Lambert azimuthal,
-stereographic, oblique Mercator, WKT 2, geocentric, local) is **refused with its name** (`error.geo_unsupported_crs`)
-rather than read as degrees. Coordinates outside the Earth with no usable system (`error.geo_unknown_crs`, a CSV or
+metres, feet and US survey feet. They agree with PROJ to well under a millimetre: `GeoCrsTests` checks fifteen systems against reference
+positions computed with pyproj. Anything else (Lambert azimuthal, stereographic, oblique Mercator, WKT 2, geocentric,
+local) is **refused with its name** (`error.geo_unsupported_crs`) rather than read as degrees. So is a projected system
+whose geographic part has a prime meridian other than Greenwich or an angular unit other than degrees (ESRI's NTF Paris
+Lambert zones count their longitudes from Paris in grads): the projection's formulas assume neither, and the data would
+land about 170 km from where it is. Coordinates outside the Earth with no usable system (`error.geo_unknown_crs`, a CSV or
GeoJSON in metres, a Shapefile without `.prj`) are refused too.
**Datums are not shifted.** WGS 84, NAD83, ETRS89, GDA, JGD, Korea 2000, CGCS2000, RGF93, SIRGAS and every other datum on
@@ -778,17 +780,26 @@ tens to hundreds of metres off, and the file carries the note `notice.geo_datum_
- The files are limited to 2 GB (`error.geo_too_large`); whole files are read into memory, a few at a time.
**Safety.** XML (KML, GPX) is read without DTDs or external entities, so a file can't read other files or expand into
-gigabytes, and a document is limited to 512 million characters (which also stops a KMZ that unpacks to far more than
-it says). Counts and indexes in binary Shapefiles are checked against the record before anything is allocated, nesting
-of JSON, WKT and WKT definitions is limited, and every failure is a reason the user can act on: a damaged file, a
-system Filee can't convert, a CSV with no coordinates (`error.geo_*` in the language files). Nothing is written when a
+gigabytes. The tree is built from `XmlReader` in `GeoXml.Load` rather than by `XDocument.Load` (whose time is quadratic
+in the depth: 48 seconds for 100,000 nested levels), and elements nested more than 256 levels are refused while reading;
+MultiGeometry may nest 32 levels. A document is limited to about 67 million characters and 3 million elements (a file
+of tiny elements costs about 25 bytes of memory per character: 40 million characters in a 150 KB KMZ took 1.1 GB before
+the element limit, and now stops at about 260 MB). A KMZ whose `.kml` is declared larger than 256 MB is refused before it is unpacked, and the unpacked bytes are
+counted as they are read (`LimitedStream`), since a ZIP header can understate its size. Counts and indexes in binary
+Shapefiles are checked against the record before anything is allocated, the attribute table is read only as far as there
+are shapes, rings are sorted into polygons smallest outer ring first with the cancellation token honoured, nesting of
+JSON, WKT and WKT definitions is limited, and every failure is a reason the user can act on: a damaged file, a system
+Filee can't convert, a CSV with no coordinates (`error.geo_*` in the language files). Nothing is written when a
conversion fails.
-Tests: `GeoFormatTests`, `GeoShapefileTests`, `GeoCrsTests` and `GeoRobustnessTests` in `tests/Filee.Engines.Tests`. The
-reference files in `tests/Filee.Engines.Tests/Geo` were written by GDAL (synthetic data), the Shapefile builder in
-`GeoBuilders.cs` follows the ESRI specification for the cases GDAL won't write, and the written Shapefiles are parsed
-in the tests from the specification, not read back with the engine. `GeoRobustnessTests` reads every reference file
-truncated at every length and with random bytes changed.
+Tests: `GeoFormatTests`, `GeoShapefileTests`, `GeoCrsTests`, `GeoHostileInputTests`, `GeoZipTests` and
+`GeoRobustnessTests` in `tests/Filee.Engines.Tests`. The Shapefiles in `tests/Filee.Engines.Tests/Geo` were written by
+GDAL (synthetic data; `Geo/make-test-geo.py` recreates them), so Filee's reader and writer are not only checked against
+each other. Everything else is written in the tests: `GeoBuilders.cs` has GeoJSON, KML and GPX text and a Shapefile and
+dBASE builder that follows the ESRI specification for the cases GDAL won't write, and the Shapefiles Filee writes are
+parsed in the tests from the specification, not read back with the engine. `GeoRobustnessTests` reads every file
+truncated at several lengths and with random bytes changed; `GeoHostileInputTests` keeps each input that once crashed the
+process, took minutes or used gigabytes.
Not here yet: raster data (GeoTIFF, bands), GeoPackage, zipped Shapefiles as input, datum shifts, more projections.
diff --git a/src/Filee.Engines/Geo/DbfFormat.cs b/src/Filee.Engines/Geo/DbfFormat.cs
index f219557a..b19529c9 100644
--- a/src/Filee.Engines/Geo/DbfFormat.cs
+++ b/src/Filee.Engines/Geo/DbfFormat.cs
@@ -26,6 +26,12 @@ internal readonly record struct DbfLosses(bool NamesChanged, bool TextCut, bool
internal static class DbfFormat
{
+ /// <summary>Names tools write in a .cpg for Korean Windows text, all code page 949.</summary>
+ private static readonly HashSet<string> KoreanNames = new(StringComparer.OrdinalIgnoreCase)
+ {
+ "CP949", "UHC", "MS949", "WINDOWS-949", "X-WINDOWS-949", "KS_C_5601-1987",
+ };
+
private const int MaxTextBytes = 254;
private const int MaxFields = 255;
private const int MaxNumberWidth = 24;
@@ -34,10 +40,13 @@ internal static class DbfFormat
// ---- Reading ----
- /// <summary>Reads a table; <paramref name="cpg"/> is the text of the .cpg file, or null.</summary>
- public static DbfTable Read(string path, string? cpg, CancellationToken cancellationToken)
+ /// <summary>
+ /// Reads a table; <paramref name="cpg"/> is the text of the .cpg file, or null. At most <paramref name="maxRows"/> rows
+ /// are read, and only their bytes: a table of millions of rows beside a few shapes costs nothing.
+ /// </summary>
+ public static DbfTable Read(string path, string? cpg, int maxRows, CancellationToken cancellationToken)
{
- var bytes = File.ReadAllBytes(path);
+ var bytes = ReadStart(path, maxRows);
if (bytes.Length < 33)
throw new InvalidDataException("The .dbf file is too short to be a dBASE table.");
var recordCount = BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(4));
@@ -63,7 +72,8 @@ internal static class DbfFormat
if (position > recordLength)
throw new InvalidDataException("The .dbf field lengths do not fit the record length.");
- var encoding = Resolve(cpg, bytes[29]) ?? Detect(bytes, headerLength, recordLength, table.Fields, offsets, recordCount);
+ var rowLimit = (uint)Math.Max(maxRows, 0);
+ var encoding = Resolve(cpg, bytes[29]) ?? Detect(bytes, headerLength, recordLength, table.Fields, offsets, Math.Min(recordCount, rowLimit));
// Field names were read as Latin-1 above; re-read them in the table's encoding (they are ASCII almost always).
for (var i = 0; i < table.Fields.Count; i++)
{
@@ -74,7 +84,7 @@ internal static class DbfFormat
}
var available = (bytes.Length - headerLength) / recordLength;
- var count = (int)Math.Min(recordCount, (uint)available);
+ var count = (int)Math.Min(Math.Min(recordCount, (uint)available), rowLimit);
for (var r = 0; r < count; r++)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -92,6 +102,25 @@ internal static class DbfFormat
return table;
}
+ /// <summary>The header and the first <paramref name="maxRows"/> records of the file (all of it if it is shorter).</summary>
+ private static byte[] ReadStart(string path, int maxRows)
+ {
+ using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
+ var head = new byte[12];
+ var got = file.ReadAtLeast(head, head.Length, throwOnEndOfStream: false);
+ if (got < head.Length)
+ return head[..got];
+ var headerLength = BinaryPrimitives.ReadUInt16LittleEndian(head.AsSpan(8));
+ var recordLength = BinaryPrimitives.ReadUInt16LittleEndian(head.AsSpan(10));
+ // The records, and the end marker after them.
+ var wanted = headerLength + (long)Math.Max(maxRows, 0) * recordLength + 1;
+ // At least the fixed header, so a header that claims to be shorter is reported as damaged, not as a short file.
+ var bytes = new byte[(int)Math.Min(file.Length, Math.Max(wanted, 33))];
+ file.Position = 0;
+ file.ReadExactly(bytes);
+ return bytes;
+ }
+
private static string Latin1(ReadOnlySpan<byte> bytes) => Encoding.Latin1.GetString(bytes);
private static object? Value(DbfField field, ReadOnlySpan<byte> cell, Encoding encoding)
@@ -116,7 +145,7 @@ internal static class DbfFormat
? real == Math.Floor(real) && Math.Abs(real) < 1e15 && field.Decimals == 0 ? (long)real : real
: null;
}
- case 'L':
+ case 'L' when cell.Length > 0:
return (char)cell[0] switch
{
'T' or 't' or 'Y' or 'y' => true,
@@ -152,6 +181,8 @@ internal static class DbfFormat
{
if (name.Equals("UTF-8", StringComparison.OrdinalIgnoreCase) || name.Equals("UTF8", StringComparison.OrdinalIgnoreCase) || name == "65001")
return new UTF8Encoding(false);
+ if (KoreanNames.Contains(name))
+ return Encoding.GetEncoding(949);
if (int.TryParse(name, NumberStyles.None, CultureInfo.InvariantCulture, out var page))
return Encoding.GetEncoding(page);
if (name.StartsWith("ANSI ", StringComparison.OrdinalIgnoreCase) && int.TryParse(name.AsSpan(5), NumberStyles.None, CultureInfo.InvariantCulture, out page))
diff --git a/src/Filee.Engines/Geo/GeoCrs.cs b/src/Filee.Engines/Geo/GeoCrs.cs
index fcfcc6e2..622e24b0 100644
--- a/src/Filee.Engines/Geo/GeoCrs.cs
+++ b/src/Filee.Engines/Geo/GeoCrs.cs
@@ -119,9 +119,10 @@ internal abstract class GeoCrs
var compatible = IsWgs84Compatible(datum, node.Child("DATUM")?.Child("SPHEROID"));
var unit = node.Child("UNIT")?.Number(1) ?? Math.PI / 180;
var meridian = node.Child("PRIMEM")?.Number(1) ?? 0;
- // Angles in radians (UNIT factor) → degrees. A prime meridian other than Greenwich is given in the same unit.
+ // Angles in radians (UNIT factor) → degrees. PRIMEM is in degrees from Greenwich whatever the unit of the system:
+ // GDAL and ESRI both write the Paris meridian as 2.33722917 next to UNIT["Grad"], not as 2.5969 grads.
var toDegrees = Math.Abs(unit * Degrees - 1) < 1e-9 ? 1 : unit * Degrees;
- return new GeographicCrs(name, toDegrees, meridian * toDegrees, approximate: !compatible);
+ return new GeographicCrs(name, toDegrees, meridian, approximate: !compatible);
}
private static GeoCrs FromProjected(WktNode node)
@@ -132,6 +133,13 @@ internal abstract class GeoCrs
var spheroid = datum?.Child("SPHEROID");
if (spheroid is null || spheroid.Number(1) is not { } axis || axis <= 0)
throw Unsupported($"{name} (no ellipsoid)");
+ // The projection's own longitudes are counted from the prime meridian and its angles in the unit of the geographic
+ // system. Neither is applied here, and ignoring them puts the data far from where it is (NTF Paris Lambert II is
+ // 2.3 degrees west of its true place), so a system with another prime meridian or angular unit is refused.
+ if (geographic.Child("PRIMEM") is { } primeMeridian && Math.Abs(primeMeridian.Number(1) ?? 0) > 1e-9)
+ throw Unsupported($"{name} (prime meridian {primeMeridian.Text(0)} {primeMeridian.Number(1)?.ToString(CultureInfo.InvariantCulture)}°)");
+ if (geographic.Child("UNIT") is { } angular && angular.Number(1) is { } angularFactor && Math.Abs(angularFactor * Degrees - 1) > 1e-9)
+ throw Unsupported($"{name} (angular unit {angular.Text(0)})");
var ellipsoid = Ellipsoid.FromInverseFlattening(axis, spheroid.Number(2) ?? 0);
var approximate = !IsWgs84Compatible(datum?.Text(0) ?? geographic.Text(0) ?? "", spheroid);
var unit = node.Children("UNIT").LastOrDefault()?.Number(1) ?? 1;
diff --git a/src/Filee.Engines/Geo/GeoCsvFormat.cs b/src/Filee.Engines/Geo/GeoCsvFormat.cs
index ce7327d0..c7c9e197 100644
--- a/src/Filee.Engines/Geo/GeoCsvFormat.cs
+++ b/src/Filee.Engines/Geo/GeoCsvFormat.cs
@@ -69,7 +69,9 @@ internal static class GeoCsvFormat
if (geometry is not null)
located++;
var properties = new List<KeyValuePair<string, object?>>();
- for (var c = 0; c < header.Count; c++)
+ // A row shorter than the header has nothing in the columns it lacks: those are not made up for every row
+ // (a wide header over many short rows would otherwise take rows x columns of memory).
+ for (var c = 0; c < Math.Min(header.Count, row.Count); c++)
{
if (!used.Contains(c))
properties.Add(new(names[c], GeoText.Typed(Cell(c))));
@@ -101,13 +103,20 @@ internal static class GeoCsvFormat
private static List<string> UniqueNames(List<string> header)
{
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
+ // The next number to try for a repeated name: a header of 100,000 identical names costs 100,000 steps, not 5 billion.
+ var next = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
var names = new List<string>();
for (var i = 0; i < header.Count; i++)
{
var name = header[i].Length == 0 ? $"column{i + 1}" : header[i];
var unique = name;
- for (var n = 2; !seen.Add(unique); n++)
- unique = $"{name}_{n}";
+ if (!seen.Add(unique))
+ {
+ var n = next.GetValueOrDefault(name, 2);
+ while (!seen.Add(unique = $"{name}_{n}"))
+ n++;
+ next[name] = n + 1;
+ }
names.Add(unique);
}
return names;
diff --git a/src/Filee.Engines/Geo/GeoJsonFormat.cs b/src/Filee.Engines/Geo/GeoJsonFormat.cs
index 7294f5ac..c29fed16 100644
--- a/src/Filee.Engines/Geo/GeoJsonFormat.cs
+++ b/src/Filee.Engines/Geo/GeoJsonFormat.cs
@@ -102,7 +102,7 @@ internal static class GeoJsonFormat
private static object? Value(JsonElement element) => element.ValueKind switch
{
JsonValueKind.String => element.GetString(),
- JsonValueKind.Number => element.TryGetInt64(out var whole) ? whole : element.GetDouble(),
+ JsonValueKind.Number => element.TryGetInt64(out var whole) ? whole : double.IsFinite(element.GetDouble()) ? element.GetDouble() : element.GetRawText(),
JsonValueKind.True => true,
JsonValueKind.False => false,
JsonValueKind.Null or JsonValueKind.Undefined => null,
@@ -190,7 +190,10 @@ internal static class GeoJsonFormat
case 2: z = number.GetDouble(); break;
}
}
- return new Coord(x!.Value, y!.Value, z);
+ // 1e400 reads as infinity: as a longitude or latitude that is no position, as a height it is no height.
+ if (!double.IsFinite(x!.Value) || !double.IsFinite(y!.Value))
+ throw new InvalidDataException($"A position in {where} holds a number too large for a coordinate.");
+ return new Coord(x.Value, y!.Value, double.IsFinite(z) ? z : double.NaN);
}
// ---- Writing ----
diff --git a/src/Filee.Engines/Geo/KmlFormat.cs b/src/Filee.Engines/Geo/KmlFormat.cs
index 7d19002a..812f336d 100644
--- a/src/Filee.Engines/Geo/KmlFormat.cs
+++ b/src/Filee.Engines/Geo/KmlFormat.cs
@@ -14,8 +14,14 @@ internal static class KmlFormat
{
private static readonly XNamespace Kml = "http://www.opengis.net/kml/2.2";
- /// <summary>Reads a .kml or a .kmz file.</summary>
- public static GeoDataset Read(string path, bool zipped, CancellationToken cancellationToken)
+ /// <summary>The largest .kml a KMZ may hold, declared or really unpacked: a ZIP of a few KB can claim far more.</summary>
+ internal const long MaxKmlBytes = 256L << 20;
+
+ /// <summary>How deep MultiGeometry may nest before the file is refused (real files nest one level).</summary>
+ private const int MaxGeometryDepth = 32;
+
+ /// <summary>Reads a .kml or a .kmz file; <paramref name="maxKmlBytes"/> limits the .kml inside a KMZ.</summary>
+ public static GeoDataset Read(string path, bool zipped, CancellationToken cancellationToken, long maxKmlBytes = MaxKmlBytes)
{
XDocument document;
if (zipped)
@@ -34,7 +40,10 @@ internal static class KmlFormat
var entry = archive.Entries.FirstOrDefault(e => e.FullName.Equals("doc.kml", StringComparison.OrdinalIgnoreCase))
?? archive.Entries.FirstOrDefault(e => e.FullName.EndsWith(".kml", StringComparison.OrdinalIgnoreCase))
?? throw new InvalidDataException("The KMZ has no .kml file inside.");
- using var stream = entry.Open();
+ if (entry.Length > maxKmlBytes)
+ throw new InvalidDataException($"The .kml inside the KMZ is too large ({entry.Length / (1 << 20)} MB, the limit is {maxKmlBytes / (1 << 20)} MB).");
+ // The size in a ZIP header can be wrong: the unpacked bytes are counted as they are read.
+ using var stream = new LimitedStream(entry.Open(), maxKmlBytes, "The .kml inside the KMZ is larger than " + maxKmlBytes / (1 << 20) + " MB.");
document = GeoXml.Load(stream);
}
}
@@ -74,7 +83,7 @@ internal static class KmlFormat
if (names.Add(key))
properties.Add(new(key, GeoText.Typed(value.Trim())));
}
- var geometries = placemark.Elements().Select(ReadGeometry).OfType<GeoGeometry>().ToList();
+ var geometries = placemark.Elements().Select(e => ReadGeometry(e, 0)).OfType<GeoGeometry>().ToList();
GeoGeometry? geometry = geometries.Count switch
{
0 => null,
@@ -84,8 +93,10 @@ internal static class KmlFormat
return new GeoFeature(geometry, properties);
}
- private static GeoGeometry? ReadGeometry(XElement element)
+ private static GeoGeometry? ReadGeometry(XElement element, int depth)
{
+ if (depth > MaxGeometryDepth)
+ throw new InvalidDataException($"The KML nests geometries more than {MaxGeometryDepth} levels deep.");
switch (element.Name.LocalName)
{
case "Point":
@@ -124,7 +135,7 @@ internal static class KmlFormat
}
case "MultiGeometry":
{
- var parts = element.Elements().Select(ReadGeometry).OfType<GeoGeometry>().ToList();
+ var parts = element.Elements().Select(e => ReadGeometry(e, depth + 1)).OfType<GeoGeometry>().ToList();
return parts.Count switch
{
0 => null,
@@ -148,7 +159,7 @@ internal static class KmlFormat
if (coordinates is null)
return line;
// Some writers put spaces after the commas ("1, 2, 3"): glue those back before splitting on white space.
- var text = System.Text.RegularExpressions.Regex.Replace(coordinates.Value, @"\s*,\s*", ",");
+ var text = GlueCommas(coordinates.Value);
foreach (var tuple in text.Split([' ', '\t', '\r', '\n'], StringSplitOptions.RemoveEmptyEntries))
{
var parts = tuple.Split(',');
@@ -160,6 +171,36 @@ internal static class KmlFormat
return line;
}
+ /// <summary>
+ /// The text without the white space next to commas (a run of white space elsewhere shrinks to its first character).
+ /// Linear: a regular expression for this takes quadratic time on a long run of spaces.
+ /// </summary>
+ private static string GlueCommas(string text)
+ {
+ if (!text.Contains(',', StringComparison.Ordinal))
+ return text;
+ var builder = new System.Text.StringBuilder(text.Length);
+ var space = ''; // white space seen since the last character: kept unless a comma is next to it
+ var afterComma = false;
+ foreach (var ch in text)
+ {
+ if (char.IsWhiteSpace(ch))
+ {
+ if (!afterComma && space == '')
+ space = ch;
+ continue;
+ }
+ if (ch != ',' && space != '')
+ builder.Append(space);
+ space = '';
+ builder.Append(ch);
+ afterComma = ch == ',';
+ }
+ if (space != '')
+ builder.Append(space);
+ return builder.ToString();
+ }
+
private static List<Coord> TrackCoordinates(XElement track)
{
var line = new List<Coord>();
@@ -323,8 +364,24 @@ internal static class KmlFormat
/// <summary>XML helpers shared by the KML and GPX formats.</summary>
internal static class GeoXml
{
- /// <summary>Parses XML without DTDs or external entities, so a hostile file can't read files or expand into gigabytes.</summary>
- public static XDocument Load(Stream stream)
+ /// <summary>How many levels of elements a KML or GPX file may nest (real files nest a dozen).</summary>
+ internal const int MaxElementDepth = 256;
+
+ /// <summary>
+ /// How many elements a KML or GPX file may hold. Each costs about 100 bytes in the tree whatever its size, so a
+ /// file of tiny elements ("&lt;a/&gt;" repeated) would use 25 bytes of memory per character: 40 million characters
+ /// in a 150 KB KMZ took 1.1 GB. Real files hold a few elements per feature; this allows a million features.
+ /// </summary>
+ internal const int MaxElements = 3_000_000;
+
+ /// <summary>
+ /// Parses XML without DTDs or external entities, so a hostile file can't read files or expand into gigabytes, and
+ /// refuses elements nested more than <see cref="MaxElementDepth"/> levels. The tree is built here from the reader
+ /// rather than by <c>XDocument.Load</c>, which takes time quadratic in the depth (a 1.4 MB file nested 100,000 deep
+ /// kept it busy for 48 seconds, the reader alone needs a quarter of a second) and so couldn't be allowed to see such
+ /// a file. Namespace declarations and prefixes are not kept; names are the local name and namespace.
+ /// </summary>
+ public static XDocument Load(Stream stream, int maxElements = MaxElements)
{
var settings = new XmlReaderSettings
{
@@ -332,13 +389,54 @@ internal static class GeoXml
XmlResolver = null,
MaxCharactersFromEntities = 0,
CheckCharacters = false,
- // Also the limit for a KMZ: the .kml inside is unpacked while it is read, so a ZIP bomb stops here.
- MaxCharactersInDocument = 1L << 29,
+ // About 1 GB of memory at the most: the tree takes some 16 bytes for every character.
+ MaxCharactersInDocument = 1L << 26,
};
try
{
using var reader = XmlReader.Create(stream, settings);
- return XDocument.Load(reader, LoadOptions.None);
+ var document = new XDocument();
+ XContainer current = document;
+ var depth = 0;
+ var elements = 0;
+ while (reader.Read())
+ {
+ switch (reader.NodeType)
+ {
+ case XmlNodeType.Element:
+ if (++depth > MaxElementDepth)
+ throw new InvalidDataException($"The file nests elements more than {MaxElementDepth} levels deep.");
+ if (++elements > maxElements)
+ throw new InvalidDataException("The file has more than " + maxElements.ToString("N0", System.Globalization.CultureInfo.InvariantCulture) + " elements.");
+ var element = new XElement(XName.Get(reader.LocalName, reader.NamespaceURI));
+ var empty = reader.IsEmptyElement;
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ if (reader.NamespaceURI != "http://www.w3.org/2000/xmlns/")
+ element.SetAttributeValue(XName.Get(reader.LocalName, reader.NamespaceURI), reader.Value);
+ }
+ reader.MoveToElement();
+ }
+ current.Add(element);
+ if (empty)
+ depth--;
+ else
+ current = element;
+ break;
+ case XmlNodeType.EndElement:
+ current = current.Parent ?? (XContainer)document;
+ depth--;
+ break;
+ case XmlNodeType.Text or XmlNodeType.CDATA or XmlNodeType.SignificantWhitespace or XmlNodeType.Whitespace:
+ // Text outside the root element (white space between declarations) is no content.
+ if (current is XElement)
+ current.Add(new XText(reader.Value));
+ break;
+ }
+ }
+ return document;
}
catch (XmlException ex)
{
diff --git a/src/Filee.Engines/Geo/LimitedStream.cs b/src/Filee.Engines/Geo/LimitedStream.cs
new file mode 100644
index 00000000..57e7aa38
--- /dev/null
+++ b/src/Filee.Engines/Geo/LimitedStream.cs
@@ -0,0 +1,44 @@
+// A read-only wrapper that counts the bytes read through it and fails once they pass a limit, so a ZIP entry that
+// unpacks to far more than its header says (a ZIP bomb) stops at a known size instead of filling the memory.
+
+namespace Filee.Engines.Geo;
+
+/// <summary>Reads at most <c>limit</c> bytes of <paramref name="inner"/>, then throws <see cref="InvalidDataException"/>.</summary>
+internal sealed class LimitedStream(Stream inner, long limit, string message) : Stream
+{
+ private long _read;
+
+ public override bool CanRead => true;
+ public override bool CanSeek => false;
+ public override bool CanWrite => false;
+ public override long Length => throw new NotSupportedException();
+
+ public override long Position
+ {
+ get => _read;
+ set => throw new NotSupportedException();
+ }
+
+ public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count));
+
+ public override int Read(Span<byte> buffer)
+ {
+ var read = inner.Read(buffer);
+ _read += read;
+ if (_read > limit)
+ throw new InvalidDataException(message);
+ return read;
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ inner.Dispose();
+ base.Dispose(disposing);
+ }
+
+ public override void Flush() { }
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+ public override void SetLength(long value) => throw new NotSupportedException();
+ public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+}
diff --git a/src/Filee.Engines/Geo/ShapefileFormat.cs b/src/Filee.Engines/Geo/ShapefileFormat.cs
index 72ec6ca2..c85816c7 100644
--- a/src/Filee.Engines/Geo/ShapefileFormat.cs
+++ b/src/Filee.Engines/Geo/ShapefileFormat.cs
@@ -84,7 +84,7 @@ internal static class ShapefileFormat
position += 8;
if (contentLength < 4 || position + contentLength > end)
throw new InvalidDataException($"The .shp is cut off or damaged at shape {geometries.Count + 1}.");
- geometries.Add(ReadShape(bytes.AsSpan(position, (int)contentLength), geometries.Count + 1));
+ geometries.Add(ReadShape(bytes.AsSpan(position, (int)contentLength), geometries.Count + 1, cancellationToken));
position += (int)contentLength;
}
@@ -92,7 +92,8 @@ internal static class ShapefileFormat
if (Sidecar(path, "dbf") is { } dbfPath)
{
var cpgPath = Sidecar(path, "cpg");
- table = DbfFormat.Read(dbfPath, cpgPath is null ? null : File.ReadAllText(cpgPath), cancellationToken);
+ // Only as many rows as there are shapes: a table of millions of rows next to a few shapes is not read.
+ table = DbfFormat.Read(dbfPath, cpgPath is null ? null : File.ReadAllText(cpgPath), geometries.Count, cancellationToken);
if (table.Rows.Count < geometries.Count)
throw new InvalidDataException($"The .dbf has {table.Rows.Count} rows but the .shp has {geometries.Count} shapes.");
}
@@ -109,15 +110,16 @@ internal static class ShapefileFormat
dataset.Features.Add(new GeoFeature(geometries[i], properties));
}
- if (Sidecar(path, "prj") is { } prjPath)
+ // An empty .prj says nothing about the coordinate system, so it counts as no .prj.
+ if (Sidecar(path, "prj") is { } prjPath && File.ReadAllText(prjPath) is { } wkt && !string.IsNullOrWhiteSpace(wkt))
{
- dataset.Crs = GeoCrs.FromWkt(File.ReadAllText(prjPath));
+ dataset.Crs = GeoCrs.FromWkt(wkt);
dataset.CrsDeclared = true;
}
return dataset;
}
- private static GeoGeometry? ReadShape(ReadOnlySpan<byte> c, int number)
+ private static GeoGeometry? ReadShape(ReadOnlySpan<byte> c, int number, CancellationToken cancellationToken)
{
var type = BinaryPrimitives.ReadInt32LittleEndian(c);
switch (type)
@@ -149,7 +151,7 @@ internal static class ShapefileFormat
return points.Count == 0 ? null : points.Count == 1 ? new GeoPoint(points[0]) : new GeoMultiPoint(points);
}
case 3 or 13 or 23 or 5 or 15 or 25:
- return ReadParts(c, type, number);
+ return ReadParts(c, type, number, cancellationToken);
default:
if (type == 31)
throw new ConversionRefusedException("error.geo_unsupported_shape", "MultiPatch");
@@ -157,7 +159,7 @@ internal static class ShapefileFormat
}
}
- private static GeoGeometry? ReadParts(ReadOnlySpan<byte> c, int type, int number)
+ private static GeoGeometry? ReadParts(ReadOnlySpan<byte> c, int type, int number, CancellationToken cancellationToken)
{
Need(c, 44, number);
var parts = BinaryPrimitives.ReadInt32LittleEndian(c[36..]);
@@ -201,44 +203,55 @@ internal static class ShapefileFormat
_ => new GeoMultiLineString(kept),
};
}
- return Polygons(lines);
+ return Polygons(lines, cancellationToken);
}
- /// <summary>Sorts rings into polygons with holes: outer rings run clockwise, holes counter-clockwise.</summary>
- private static GeoGeometry? Polygons(List<List<Coord>> lines)
+ /// <summary>
+ /// Sorts rings into polygons with holes: outer rings run clockwise, holes counter-clockwise. Every ring's area and
+ /// bounds are worked out once, and a hole is tried against the outer rings smallest first, so it stops at the first
+ /// (smallest) one that contains it; a file of tens of thousands of rings takes well under a second, and the
+ /// <paramref name="cancellationToken"/> is honoured while it is sorted.
+ /// </summary>
+ internal static GeoGeometry? Polygons(List<List<Coord>> lines, CancellationToken cancellationToken)
{
- var rings = lines.Select(l => GeoRings.Close(l)).OfType<IReadOnlyList<Coord>>().Where(r => GeoRings.SignedArea(r) != 0).ToList();
+ var rings = new List<(IReadOnlyList<Coord> Ring, double Area)>();
+ foreach (var line in lines)
+ {
+ if (GeoRings.Close(line) is { } ring && GeoRings.SignedArea(ring) is var area && area != 0)
+ rings.Add((ring, area));
+ }
if (rings.Count == 0)
return null;
- var outers = rings.Where(r => GeoRings.SignedArea(r) < 0).ToList();
- var holes = rings.Where(r => GeoRings.SignedArea(r) > 0).ToList();
+ var outers = rings.Where(r => r.Area < 0).ToList();
+ var holes = rings.Where(r => r.Area > 0).ToList();
if (outers.Count == 0)
{
// Every ring runs counter-clockwise: the writer used the other convention, so they are all outer rings.
outers = holes;
holes = [];
}
- var assigned = outers.Select(o => new List<IReadOnlyList<Coord>> { o }).ToList();
- var bounds = outers.Select(Bounds).ToList();
- foreach (var hole in holes)
+ var bounds = outers.Select(o => Bounds(o.Ring)).ToArray();
+ var smallestFirst = Enumerable.Range(0, outers.Count).OrderBy(i => Math.Abs(outers[i].Area)).ToArray();
+ var assigned = outers.Select(o => new List<IReadOnlyList<Coord>> { o.Ring }).ToList();
+ var holeCount = 0;
+ foreach (var (hole, _) in holes)
{
+ if (++holeCount % 64 == 0)
+ cancellationToken.ThrowIfCancellationRequested();
var probe = hole[0];
- var best = -1;
- var bestArea = double.MaxValue;
- for (var i = 0; i < outers.Count; i++)
+ var found = false;
+ foreach (var i in smallestFirst)
{
- if (probe.X < bounds[i].MinX || probe.X > bounds[i].MaxX || probe.Y < bounds[i].MinY || probe.Y > bounds[i].MaxY)
+ var box = bounds[i];
+ if (probe.X < box.MinX || probe.X > box.MaxX || probe.Y < box.MinY || probe.Y > box.MaxY)
continue;
- var area = Math.Abs(GeoRings.SignedArea(outers[i]));
- if (area < bestArea && GeoRings.Contains(outers[i], probe))
- {
- best = i;
- bestArea = area;
- }
+ if (!GeoRings.Contains(outers[i].Ring, probe))
+ continue;
+ assigned[i].Add(hole);
+ found = true;
+ break;
}
- if (best >= 0)
- assigned[best].Add(hole);
- else
+ if (!found)
assigned.Add([hole]); // a hole outside every outer ring is a ring of its own
}
var polygons = assigned.Select(rs => new GeoPolygon(rs)).ToList();
diff --git a/tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj b/tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj
index f2305ad0..90946d30 100644
--- a/tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj
+++ b/tests/Filee.Engines.Tests/Filee.Engines.Tests.csproj
@@ -23,7 +23,7 @@
<ItemGroup>
<!-- Small OFL test fonts for FontTests (see Fonts/OFL.txt and Fonts/make-test-fonts.py). -->
<None Update="Fonts\*.ttf;Fonts\*.otf;Fonts\*.woff2" CopyToOutputDirectory="PreserveNewest" />
- <!-- Small reference files written by GDAL for the geospatial tests (synthetic data). -->
+ <!-- Small Shapefiles written by GDAL for the geospatial tests (synthetic data; Geo/make-test-geo.py recreates them). -->
<None Update="Geo\*" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>
diff --git a/tests/Filee.Engines.Tests/Geo/gdal_points.geojson b/tests/Filee.Engines.Tests/Geo/gdal_points.geojson
deleted file mode 100644
index f9cebad5..00000000
--- a/tests/Filee.Engines.Tests/Geo/gdal_points.geojson
+++ /dev/null
@@ -1,9 +0,0 @@
-{
-"type": "FeatureCollection",
-"name": "gdal_points",
-"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
-"features": [
-{ "type": "Feature", "properties": { "name": "A", "n": 1 }, "geometry": { "type": "Point", "coordinates": [ 10.5, 20.25 ] } },
-{ "type": "Feature", "properties": { "name": "B", "n": 2 }, "geometry": { "type": "Point", "coordinates": [ -5.0, 40.0 ] } }
-]
-}
diff --git a/tests/Filee.Engines.Tests/Geo/gdal_points.kml b/tests/Filee.Engines.Tests/Geo/gdal_points.kml
deleted file mode 100644
index c9f4f492..00000000
--- a/tests/Filee.Engines.Tests/Geo/gdal_points.kml
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="utf-8" ?>
-<kml xmlns="http://www.opengis.net/kml/2.2">
-<Document id="root_doc">
-<Folder><name>gdal_points</name>
- <Placemark>
- <name>A</name>
- <description>first</description>
- <Point><coordinates>10.5,20.25</coordinates></Point>
- </Placemark>
- <Placemark>
- <name>B</name>
- <description>second</description>
- <Point><coordinates>-5,40</coordinates></Point>
- </Placemark>
-</Folder>
-</Document></kml>
diff --git a/tests/Filee.Engines.Tests/Geo/gdal_waypoints.gpx b/tests/Filee.Engines.Tests/Geo/gdal_waypoints.gpx
deleted file mode 100644
index ce28adf1..00000000
--- a/tests/Filee.Engines.Tests/Geo/gdal_waypoints.gpx
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0"?>
-<gpx version="1.1" creator="GDAL 3.9.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.topografix.com/GPX/1/1" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">
-<metadata>
-<bounds minlat="20.250000000000000" minlon="-5.000000000000000" maxlat="40.000000000000000" maxlon="10.500000000000000"/>
-</metadata>
-<wpt lat="20.25" lon="10.5">
- <ele>12.5</ele>
- <name>A</name>
-</wpt>
-<wpt lat="40.0" lon="-5.0">
- <ele>0.0</ele>
- <name>B</name>
-</wpt>
-</gpx>
diff --git a/tests/Filee.Engines.Tests/Geo/make-test-geo.py b/tests/Filee.Engines.Tests/Geo/make-test-geo.py
new file mode 100644
index 00000000..9112887a
--- /dev/null
+++ b/tests/Filee.Engines.Tests/Geo/make-test-geo.py
@@ -0,0 +1,60 @@
+"""Writes the Shapefile test fixtures in this folder with GDAL (through Fiona).
+
+Why they exist: GeoShapefileTests and GeoFormatTests read Shapefiles that an independent implementation wrote, so a
+mistake in Filee's own reader can't cancel out against the same mistake in Filee's own writer. The data is synthetic
+(a few points, polygons and lines made up for the tests): no third-party data, nothing to license. GDAL itself is not
+shipped. Everything else the tests need (GeoJSON, KML, GPX, CSV and the damaged or unusual Shapefiles) is written in
+the tests, see GeoBuilders.cs.
+
+ pip install fiona pyproj
+ python make-test-geo.py
+
+The files are rewritten next to this script. The .dbf files hold the date they were written on, so a regenerated set
+differs from the committed one in those bytes only; the tests don't depend on them.
+
+Sets: gdal_points (every attribute type, Korean / accented / CJK text), gdal_polygons (a hole; a multi-part polygon),
+gdal_linesz (3D lines), gdal_utm33 (points in UTM zone 33N with an ESRI .prj, positions from PROJ).
+"""
+import os
+import warnings
+
+import fiona
+from fiona.crs import CRS
+from pyproj import Transformer
+
+warnings.filterwarnings("ignore")
+OUT = os.path.dirname(os.path.abspath(__file__))
+wgs = CRS.from_epsg(4326)
+
+# Points with every attribute type; Korean, accented and CJK text.
+schema = {"geometry": "Point", "properties": {"name": "str:40", "n": "int", "v": "float", "ok": "bool", "day": "date"}}
+with fiona.open(os.path.join(OUT, "gdal_points.shp"), "w", driver="ESRI Shapefile", schema=schema, crs=wgs, encoding="UTF-8") as dst:
+ dst.write({"geometry": {"type": "Point", "coordinates": (126.9780, 37.5665)}, "properties": {"name": "서울 City Hall", "n": 1, "v": 1.5, "ok": True, "day": "2024-02-29"}})
+ dst.write({"geometry": {"type": "Point", "coordinates": (2.2945, 48.8584)}, "properties": {"name": "Café Eiffel – Paris", "n": -20, "v": 0.001, "ok": False, "day": "2000-01-01"}})
+ dst.write({"geometry": {"type": "Point", "coordinates": (-0.1276, 51.5072)}, "properties": {"name": "北京 / London", "n": 300, "v": -12345.6789, "ok": True, "day": None}})
+
+# Polygons: a hole, and a multipolygon with an island.
+schema = {"geometry": "MultiPolygon", "properties": {"id": "int", "label": "str:20"}}
+with fiona.open(os.path.join(OUT, "gdal_polygons.shp"), "w", driver="ESRI Shapefile", schema=schema, crs=wgs, encoding="UTF-8") as dst:
+ shell = [(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)]
+ hole = [(2, 2), (4, 2), (4, 4), (2, 4), (2, 2)]
+ dst.write({"geometry": {"type": "MultiPolygon", "coordinates": [[shell, hole]]}, "properties": {"id": 1, "label": "with hole"}})
+ island = [(20, 20), (25, 20), (25, 25), (20, 25), (20, 20)]
+ dst.write({"geometry": {"type": "MultiPolygon", "coordinates": [[shell], [island]]}, "properties": {"id": 2, "label": "two parts"}})
+
+# 3D lines.
+schema = {"geometry": "3D LineString", "properties": {"id": "int"}}
+with fiona.open(os.path.join(OUT, "gdal_linesz.shp"), "w", driver="ESRI Shapefile", schema=schema, crs=wgs) as dst:
+ dst.write({"geometry": {"type": "LineString", "coordinates": [(0, 0, 10), (1, 1, 20.5), (2, 0, 30)]}, "properties": {"id": 1}})
+
+# UTM 33N points (written by GDAL with an ESRI .prj). The tests know the longitude / latitude of each.
+tr = Transformer.from_crs(4326, 32633, always_xy=True)
+schema = {"geometry": "Point", "properties": {"name": "str:20"}}
+with fiona.open(os.path.join(OUT, "gdal_utm33.shp"), "w", driver="ESRI Shapefile", schema=schema, crs=CRS.from_epsg(32633)) as dst:
+ for name, lon, lat in [("Vienna", 16.3738, 48.2082), ("Prague", 14.4378, 50.0755), ("Berlin", 13.4050, 52.5200)]:
+ x, y = tr.transform(lon, lat)
+ dst.write({"geometry": {"type": "Point", "coordinates": (x, y)}, "properties": {"name": name}})
+
+for f in sorted(os.listdir(OUT)):
+ if f.startswith("gdal_"):
+ print(f, os.path.getsize(os.path.join(OUT, f)))
diff --git a/tests/Filee.Engines.Tests/GeoBuilders.cs b/tests/Filee.Engines.Tests/GeoBuilders.cs
index cc60fbc7..4c9ebde2 100644
--- a/tests/Filee.Engines.Tests/GeoBuilders.cs
+++ b/tests/Filee.Engines.Tests/GeoBuilders.cs
@@ -23,6 +23,64 @@ internal static class GeoFixtures
return Path.Combine(folder, name + "." + extension);
}
+ /// <summary>Two points, A (10.5, 20.25) and B (-5, 40), written the way GDAL writes them (see Geo/make-test-geo.py for the Shapefiles).</summary>
+ internal const string PointsGeoJson = """
+ {
+ "type": "FeatureCollection",
+ "name": "points",
+ "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
+ "features": [
+ { "type": "Feature", "properties": { "name": "A", "n": 1 }, "geometry": { "type": "Point", "coordinates": [ 10.5, 20.25 ] } },
+ { "type": "Feature", "properties": { "name": "B", "n": 2 }, "geometry": { "type": "Point", "coordinates": [ -5.0, 40.0 ] } }
+ ]
+ }
+ """;
+
+ internal const string PointsKml = """
+ <?xml version="1.0" encoding="utf-8" ?>
+ <kml xmlns="http://www.opengis.net/kml/2.2">
+ <Document id="root_doc">
+ <Folder><name>points</name>
+ <Placemark>
+ <name>A</name>
+ <description>first</description>
+ <Point><coordinates>10.5,20.25</coordinates></Point>
+ </Placemark>
+ <Placemark>
+ <name>B</name>
+ <description>second</description>
+ <Point><coordinates>-5,40</coordinates></Point>
+ </Placemark>
+ </Folder>
+ </Document></kml>
+ """;
+
+ internal const string PointsGpx = """
+ <?xml version="1.0"?>
+ <gpx version="1.1" creator="GDAL 3.9.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.topografix.com/GPX/1/1" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">
+ <metadata>
+ <bounds minlat="20.250000000000000" minlon="-5.000000000000000" maxlat="40.000000000000000" maxlon="10.500000000000000"/>
+ </metadata>
+ <wpt lat="20.25" lon="10.5">
+ <ele>12.5</ele>
+ <name>A</name>
+ </wpt>
+ <wpt lat="40.0" lon="-5.0">
+ <ele>0.0</ele>
+ <name>B</name>
+ </wpt>
+ </gpx>
+ """;
+
+ /// <summary>The two points as a file of <paramref name="extension"/> (geojson, kml or gpx) named points.&lt;extension&gt; in a fresh folder.</summary>
+ public static string Points(EngineFixture fx, string extension) => WriteText(fx, "points." + extension, extension switch
+ {
+ "geojson" => PointsGeoJson,
+ "kml" => PointsKml,
+ "gpx" => PointsGpx,
+ _ => throw new ArgumentOutOfRangeException(nameof(extension)),
+ });
+
/// <summary>Converts <paramref name="input"/> to <paramref name="target"/> as the app would.</summary>
public static async Task<ConversionJob> ConvertAsync(this EngineFixture fx, string input, string target, Action<Preset>? tweak = null)
{
diff --git a/tests/Filee.Engines.Tests/GeoCrsTests.cs b/tests/Filee.Engines.Tests/GeoCrsTests.cs
index d6766200..1b5e8620 100644
--- a/tests/Filee.Engines.Tests/GeoCrsTests.cs
+++ b/tests/Filee.Engines.Tests/GeoCrsTests.cs
@@ -118,13 +118,37 @@ public class GeoCrsTests
[Fact]
public void Geographic_system_in_grads_with_the_Paris_meridian_is_converted_to_degrees_from_Greenwich()
{
- var crs = GeoCrs.FromWkt("""GEOGCS["NTF (Paris)",DATUM["Nouvelle_Triangulation_Francaise",SPHEROID["Clarke 1880 (IGN)",6378249.2,293.4660212936269]],PRIMEM["Paris",2.5969213],UNIT["grad",0.01570796326794897]]""");
+ // As GDAL / ESRI write EPSG:4807: the prime meridian in degrees (Paris is 2.33722917 degrees east), the unit grads.
+ var crs = GeoCrs.FromWkt("""GEOGCS["GCS_NTF_Paris",DATUM["Nouvelle_Triangulation_Francaise_(Paris)",SPHEROID["Clarke_1880_IGN",6378249.2,293.466021293627]],PRIMEM["Paris",2.33722917],UNIT["Grad",0.0157079632679489]]""");
var position = crs.ToLonLat(new Coord(0, 50));
- Assert.Equal(2.5969213 * 0.9, position.X, 9);
+ Assert.Equal(2.33722917, position.X, 9);
Assert.Equal(45, position.Y, 9);
+ Assert.Equal(2.33722917 + 10 * 0.9, crs.ToLonLat(new Coord(10, 50)).X, 9);
Assert.True(crs.IsApproximate);
}
+ [Fact]
+ public void A_projected_system_with_another_prime_meridian_or_angular_unit_is_refused_not_placed_far_away()
+ {
+ // ESRI's NTF Paris Lambert Zone II (EPSG:27572): its central meridian 0 is Paris, so ignoring PRIMEM puts
+ // everything 2.3 degrees (170 km) west of where it is.
+ const string paris = """PROJCS["NTF_Paris_Lambert_Zone_II",GEOGCS["GCS_NTF_Paris",DATUM["Nouvelle_Triangulation_Francaise_(Paris)",SPHEROID["Clarke_1880_IGN",6378249.2,293.466021293627]],PRIMEM["Paris",2.33722917],UNIT["Grad",0.0157079632679489]],PROJECTION["Lambert_Conformal_Conic"],PARAMETER["False_Easting",600000.0],PARAMETER["False_Northing",2200000.0],PARAMETER["Central_Meridian",0.0],PARAMETER["Standard_Parallel_1",52.0],PARAMETER["Scale_Factor",0.99987742],PARAMETER["Latitude_Of_Origin",52.0],UNIT["Meter",1.0]]""";
+ var error = Assert.Throws<ConversionRefusedException>(() => GeoCrs.FromWkt(paris));
+ Assert.Equal("error.geo_unsupported_crs", error.ErrorKey);
+ Assert.Contains("NTF_Paris_Lambert_Zone_II", error.Detail);
+ Assert.Contains("prime meridian", error.Detail);
+
+ // Greenwich, but angles in grads.
+ var grads = paris.Replace("PRIMEM[\"Paris\",2.33722917]", "PRIMEM[\"Greenwich\",0.0]");
+ var gradError = Assert.Throws<ConversionRefusedException>(() => GeoCrs.FromWkt(grads));
+ Assert.Contains("angular unit Grad", gradError.Detail);
+
+ // Another meridian in degrees (Ferro-like) is refused too; Greenwich in degrees still works.
+ var ferro = """PROJCS["Test",GEOGCS["g",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Ferro",-17.6666667],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["Central_Meridian",31.0],UNIT["Meter",1.0]]""";
+ Assert.Contains("prime meridian Ferro", Assert.Throws<ConversionRefusedException>(() => GeoCrs.FromWkt(ferro)).Detail);
+ Assert.NotNull(GeoCrs.FromWkt(ferro.Replace("PRIMEM[\"Ferro\",-17.6666667]", "PRIMEM[\"Greenwich\",0.0]")));
+ }
+
[Theory]
[InlineData("""GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]""", false)]
[InlineData("""GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]""", false)]
diff --git a/tests/Filee.Engines.Tests/GeoFormatTests.cs b/tests/Filee.Engines.Tests/GeoFormatTests.cs
index d0bbff03..2c77867a 100644
--- a/tests/Filee.Engines.Tests/GeoFormatTests.cs
+++ b/tests/Filee.Engines.Tests/GeoFormatTests.cs
@@ -117,9 +117,9 @@ public class GeoFormatTests(EngineFixture fx) : IClassFixture<EngineFixture>
}
[Fact]
- public async Task Gdal_kml_name_and_description_become_attributes()
+ public async Task Kml_name_and_description_become_attributes()
{
- using var doc = await ToGeoJsonAsync(GeoFixtures.Copy(fx, "gdal_points", "kml"));
+ using var doc = await ToGeoJsonAsync(GeoFixtures.Points(fx, "kml"));
var features = Features(doc);
Assert.Equal(2, features.GetArrayLength());
Assert.Equal([10.5, 20.25], GeoFixtures.Position(features[0].GetProperty("geometry")));
@@ -128,9 +128,9 @@ public class GeoFormatTests(EngineFixture fx) : IClassFixture<EngineFixture>
}
[Fact]
- public async Task Gdal_gpx_waypoint_elevation_becomes_the_height()
+ public async Task Gpx_waypoint_elevation_becomes_the_height()
{
- using var doc = await ToGeoJsonAsync(GeoFixtures.Copy(fx, "gdal_waypoints", "gpx"));
+ using var doc = await ToGeoJsonAsync(GeoFixtures.Points(fx, "gpx"));
var features = Features(doc);
Assert.Equal(2, features.GetArrayLength());
Assert.Equal([10.5, 20.25, 12.5], GeoFixtures.Position(features[0].GetProperty("geometry")));
@@ -139,9 +139,9 @@ public class GeoFormatTests(EngineFixture fx) : IClassFixture<EngineFixture>
}
[Fact]
- public async Task Gdal_geojson_converts_to_the_same_geojson_rewritten_one_feature_per_line()
+ public async Task GeoJson_converts_to_the_same_geojson_rewritten_one_feature_per_line()
{
- var output = (await fx.ConvertOkAsync(GeoFixtures.Copy(fx, "gdal_points", "geojson"), "geojson")).Single();
+ var output = (await fx.ConvertOkAsync(GeoFixtures.Points(fx, "geojson"), "geojson")).Single();
var lines = File.ReadAllLines(output);
Assert.Equal(4, lines.Length); // the opening, one line for each of the two features, the closing
Assert.StartsWith("""{"type":"Feature",""", lines[1]);
@@ -155,7 +155,7 @@ public class GeoFormatTests(EngineFixture fx) : IClassFixture<EngineFixture>
public async Task Every_format_converts_into_every_other_and_back_to_the_same_places_and_names()
{
var formats = new[] { "kml", "kmz", "gpx", "shp", "csv", "geojson" };
- var source = GeoFixtures.Copy(fx, "gdal_points", "geojson");
+ var source = GeoFixtures.Points(fx, "geojson");
var made = new Dictionary<string, string> { ["geojson"] = source };
foreach (var format in formats.Where(f => f != "geojson"))
made[format] = (await fx.ConvertOkAsync(source, format)).First(path => path.EndsWith("." + format, StringComparison.Ordinal));
@@ -383,7 +383,7 @@ public class GeoFormatTests(EngineFixture fx) : IClassFixture<EngineFixture>
[Fact]
public async Task Kmz_is_written_as_a_zip_with_doc_kml_and_read_back_whatever_the_kml_is_called()
{
- var geojson = GeoFixtures.Copy(fx, "gdal_points", "geojson");
+ var geojson = GeoFixtures.Points(fx, "geojson");
var kmz = (await fx.ConvertOkAsync(geojson, "kmz")).Single();
using (var zip = ZipFile.OpenRead(kmz))
Assert.Equal(["doc.kml"], zip.Entries.Select(e => e.FullName).ToArray());
@@ -627,7 +627,7 @@ public class GeoFormatTests(EngineFixture fx) : IClassFixture<EngineFixture>
[Fact]
public async Task Csv_output_is_longitude_latitude_columns_for_points_and_wkt_otherwise()
{
- var points = File.ReadAllText((await fx.ConvertOkAsync(GeoFixtures.Copy(fx, "gdal_points", "geojson"), "csv")).Single()).TrimStart('\uFEFF');
+ var points = File.ReadAllText((await fx.ConvertOkAsync(GeoFixtures.Points(fx, "geojson"), "csv")).Single()).TrimStart('\uFEFF');
Assert.StartsWith("longitude,latitude,name,n\r\n10.5,20.25,A,1\r\n-5,40,B,2\r\n", points);
var polygons = File.ReadAllText((await fx.ConvertOkAsync(GeoFixtures.Copy(fx, "gdal_polygons", "shp"), "csv")).Single()).TrimStart('\uFEFF');
diff --git a/tests/Filee.Engines.Tests/GeoHostileInputTests.cs b/tests/Filee.Engines.Tests/GeoHostileInputTests.cs
new file mode 100644
index 00000000..95daaea9
--- /dev/null
+++ b/tests/Filee.Engines.Tests/GeoHostileInputTests.cs
@@ -0,0 +1,315 @@
+// Inputs a review of the geospatial engine fed it: geometry nested far deeper than any real file, a prime meridian the
+// projection ignored, tens of thousands of rings in one record, a ZIP that claims to hold less than it does, a huge
+// attribute table next to a few shapes, and the odd details of dBASE, .cpg, .prj and GeoJSON numbers. Each of these once
+// crashed the process, took minutes, used gigabytes or gave a wrong answer.
+
+using System.IO.Compression;
+using System.Text;
+using Filee.Core.Conversion;
+using Filee.Engines.Geo;
+
+namespace Filee.Engines.Tests;
+
+public class GeoHostileInputTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ static GeoHostileInputTests() => Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+
+ private const string Wgs84Prj = """GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]""";
+
+ private static string Nested(string tag, int levels, string inner) =>
+ string.Concat(Enumerable.Repeat($"<{tag}>", levels)) + inner + string.Concat(Enumerable.Repeat($"</{tag}>", levels));
+
+ // ---- Nesting ----
+
+ [Theory]
+ [InlineData(40)]
+ [InlineData(5_000)]
+ [InlineData(100_000)]
+ public async Task KML_geometry_nested_beyond_the_limit_is_refused_not_a_stack_overflow(int levels)
+ {
+ var kml = "<kml><Placemark>" + Nested("MultiGeometry", levels, "<Point><coordinates>1,2</coordinates></Point>") + "</Placemark></kml>";
+ var (key, detail) = await fx.ConvertFailsAsync(GeoFixtures.WriteText(fx, "deep.kml", kml), "geojson");
+ Assert.Equal("error.conversion_failed", key);
+ Assert.Contains("levels deep", detail);
+ }
+
+ [Fact]
+ public async Task KML_geometry_nested_within_the_limit_is_read()
+ {
+ var kml = "<kml><Placemark>" + Nested("MultiGeometry", 30, "<Point><coordinates>1,2</coordinates></Point>") + "</Placemark></kml>";
+ var output = (await fx.ConvertOkAsync(GeoFixtures.WriteText(fx, "ok.kml", kml), "geojson")).Single();
+ using var doc = GeoFixtures.ReadJson(output);
+ Assert.Equal([1.0, 2.0], GeoFixtures.Position(doc.RootElement.GetProperty("features")[0].GetProperty("geometry")));
+ }
+
+ [Fact]
+ public void A_file_of_countless_tiny_elements_is_refused_before_it_fills_the_memory()
+ {
+ // 40 million characters of "<a/>" in a KMZ of 150 KB took 1.1 GB: the number of elements is limited.
+ var xml = "<kml><Placemark>" + string.Concat(Enumerable.Repeat("<a/>", 1000)) + "</Placemark></kml>";
+ using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
+ Assert.Equal("The file has more than 100 elements.", Assert.Throws<InvalidDataException>(() => GeoXml.Load(stream, maxElements: 100)).Message);
+ using var again = new MemoryStream(Encoding.UTF8.GetBytes(xml));
+ Assert.NotNull(GeoXml.Load(again)); // within the real limit it loads
+ Assert.Equal(3_000_000, GeoXml.MaxElements);
+ }
+
+ [Fact]
+ public async Task Folders_nested_within_the_limit_are_read()
+ {
+ var kml = "<kml>" + Nested("Folder", 200, "<Placemark><Point><coordinates>3,4</coordinates></Point></Placemark>") + "</kml>";
+ var output = (await fx.ConvertOkAsync(GeoFixtures.WriteText(fx, "folders.kml", kml), "geojson")).Single();
+ using var doc = GeoFixtures.ReadJson(output);
+ Assert.Equal(1, doc.RootElement.GetProperty("features").GetArrayLength());
+ }
+
+ [Theory]
+ [InlineData("kml", "<kml>", "<Folder>", "</Folder>", "</kml>")]
+ [InlineData("gpx", """<gpx><wpt lat="1" lon="2"><extensions>""", "<x>", "</x>", "</extensions></wpt></gpx>")]
+ public async Task Elements_nested_very_deep_in_any_part_of_the_file_are_refused_at_once(string format, string head, string open, string close, string tail)
+ {
+ // XDocument.Load needs about 48 seconds for a file like this and a recursive walk could end the process: the
+ // engine stops reading at 256 levels, which the message proves (a slow regression would still pass this test,
+ // but could not give this message).
+ var text = head + string.Concat(Enumerable.Repeat(open, 100_000)) + string.Concat(Enumerable.Repeat(close, 100_000)) + tail;
+ var (key, detail) = await fx.ConvertFailsAsync(GeoFixtures.WriteText(fx, "deep." + format, text), "geojson");
+ Assert.Equal("error.conversion_failed", key);
+ Assert.Contains("256 levels deep", detail);
+ }
+
+ [Fact]
+ public async Task Namespaces_prefixes_and_attributes_still_read_as_before_with_the_tree_built_by_the_engine()
+ {
+ const string gpx = """<?xml version="1.0"?><g:gpx xmlns:g="http://www.topografix.com/GPX/1/1" xmlns:x="urn:x" x:flag="1"><g:wpt lat="47.5" lon="8.25"><g:name>A &amp; B</g:name><!-- comment --><g:ele><![CDATA[412.5]]></g:ele></g:wpt></g:gpx>""";
+ using var doc = GeoFixtures.ReadJson((await fx.ConvertOkAsync(GeoFixtures.WriteText(fx, "prefixed.gpx", gpx), "geojson")).Single());
+ var feature = doc.RootElement.GetProperty("features")[0];
+ Assert.Equal([8.25, 47.5, 412.5], GeoFixtures.Position(feature.GetProperty("geometry")));
+ Assert.Equal("A & B", feature.GetProperty("properties").GetProperty("name").GetString());
+ }
+
+ // ---- Quadratic and wide inputs ----
+
+ [Fact]
+ public async Task A_csv_header_of_a_hundred_thousand_identical_names_gets_unique_names_at_once()
+ {
+ var header = "lat,lon," + string.Join(',', Enumerable.Repeat("a", 100_000));
+ var row = "1,2," + string.Join(',', Enumerable.Repeat("x", 100_000));
+ using var doc = GeoFixtures.ReadJson((await fx.ConvertOkAsync(GeoFixtures.WriteText(fx, "wide.csv", header + "\n" + row + "\n"), "geojson")).Single());
+ var properties = doc.RootElement.GetProperty("features")[0].GetProperty("properties");
+ Assert.Equal(100_000, properties.EnumerateObject().Count());
+ Assert.True(properties.TryGetProperty("a", out _));
+ Assert.True(properties.TryGetProperty("a_2", out _));
+ Assert.True(properties.TryGetProperty("a_100000", out _));
+ }
+
+ [Fact]
+ public async Task A_wide_csv_header_over_many_short_rows_does_not_make_rows_times_columns_attributes()
+ {
+ // 20,000 columns and 20,000 rows of two cells: 400 million empty attributes if each row were padded to the header.
+ var text = new StringBuilder("lat,lon," + string.Join(',', Enumerable.Range(0, 20_000).Select(i => "c" + i)) + "\n");
+ for (var i = 0; i < 20_000; i++)
+ text.Append("1,2\n");
+ using var doc = GeoFixtures.ReadJson((await fx.ConvertOkAsync(GeoFixtures.WriteText(fx, "short.csv", text.ToString()), "geojson")).Single());
+ Assert.Equal(20_000, doc.RootElement.GetProperty("features").GetArrayLength());
+ }
+
+ [Fact]
+ public async Task A_long_run_of_white_space_in_a_kml_coordinates_element_is_read_in_linear_time()
+ {
+ var spaces = new string(' ', 2_000_000);
+ // Three positions separated by long runs of spaces, the last written "2, 2"; and a point with spaces around its comma.
+ var kml = $"<kml><Placemark><LineString><coordinates>0,0{spaces}1,1{spaces}2, 2</coordinates></LineString></Placemark>"
+ + $"<Placemark><Point><coordinates>5{spaces},{spaces}6</coordinates></Point></Placemark></kml>";
+ using var doc = GeoFixtures.ReadJson((await fx.ConvertOkAsync(GeoFixtures.WriteText(fx, "spaces.kml", kml), "geojson")).Single());
+ var features = doc.RootElement.GetProperty("features");
+ var line = features[0].GetProperty("geometry").GetProperty("coordinates");
+ Assert.Equal(3, line.GetArrayLength());
+ Assert.Equal([2.0, 2.0], [line[2][0].GetDouble(), line[2][1].GetDouble()]);
+ Assert.Equal([5.0, 6.0], GeoFixtures.Position(features[1].GetProperty("geometry")));
+ }
+
+ // ---- Prime meridian ----
+
+ [Fact]
+ public async Task A_shapefile_in_NTF_Paris_Lambert_is_refused_instead_of_landing_170_km_west()
+ {
+ const string paris = """PROJCS["NTF_Paris_Lambert_Zone_II",GEOGCS["GCS_NTF_Paris",DATUM["Nouvelle_Triangulation_Francaise_(Paris)",SPHEROID["Clarke_1880_IGN",6378249.2,293.466021293627]],PRIMEM["Paris",2.33722917],UNIT["Grad",0.0157079632679489]],PROJECTION["Lambert_Conformal_Conic"],PARAMETER["False_Easting",600000.0],PARAMETER["False_Northing",2200000.0],PARAMETER["Central_Meridian",0.0],PARAMETER["Standard_Parallel_1",52.0],PARAMETER["Scale_Factor",0.99987742],PARAMETER["Latitude_Of_Origin",52.0],UNIT["Meter",1.0]]""";
+ var shp = new ShapefileBuilder(1).Point(600000, 2200000).Save(fx.NewFolder(), "paris", paris);
+ var (key, detail) = await fx.ConvertFailsAsync(shp, "geojson");
+ Assert.Equal("error.geo_unsupported_crs", key);
+ Assert.Contains("prime meridian", detail);
+ }
+
+ // ---- Rings ----
+
+ /// <summary>Squares on a grid, each with a hole inside: all the outer rings first, then all the holes.</summary>
+ private static (double X, double Y)[][] SquaresWithHoles(int count)
+ {
+ var side = (int)Math.Ceiling(Math.Sqrt(count));
+ var outers = new List<(double, double)[]>();
+ var holes = new List<(double, double)[]>();
+ for (var i = 0; i < count; i++)
+ {
+ double x = i % side * 10, y = i / side * 10;
+ outers.Add([(x, y), (x, y + 8), (x + 8, y + 8), (x + 8, y), (x, y)]); // clockwise
+ holes.Add([(x + 2, y + 2), (x + 6, y + 2), (x + 6, y + 6), (x + 2, y + 6), (x + 2, y + 2)]); // counter-clockwise
+ }
+ return [.. outers, .. holes];
+ }
+
+ [Fact]
+ public void A_record_of_twenty_thousand_rings_is_sorted_into_polygons_and_holes_without_crawling()
+ {
+ const int count = 10_000;
+ var shp = new ShapefileBuilder(5).Parts(5, SquaresWithHoles(count)).Save(fx.NewFolder(), "rings", Wgs84Prj);
+ // Before the fix this took 79 s for a file of this size; a timeout of a minute keeps a slow machine honest
+ // without asserting a speed.
+ using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(1));
+ var dataset = ShapefileFormat.Read(shp, timeout.Token);
+
+ var polygons = Assert.IsType<GeoMultiPolygon>(Assert.Single(dataset.Features).Geometry).Polygons;
+ Assert.Equal(count, polygons.Count);
+ Assert.All(polygons, p => Assert.Equal(2, p.Rings.Count)); // each outer ring with the one hole inside it
+ Assert.Equal(1, polygons[0].Rings[1][0].X - polygons[0].Rings[0][0].X - 1); // the hole belongs to the first square
+ var last = polygons[^1];
+ Assert.True(last.Rings[1][0].X > last.Rings[0].Min(p => p.X) && last.Rings[1][0].X < last.Rings[0].Max(p => p.X));
+ }
+
+ [Fact]
+ public void Sorting_the_rings_of_a_record_honours_the_cancellation_token()
+ {
+ var rings = SquaresWithHoles(500).Select(r => r.Select(p => new Coord(p.X, p.Y)).ToList()).ToList();
+ using var cancelled = new CancellationTokenSource();
+ cancelled.Cancel();
+ Assert.Throws<OperationCanceledException>(() => ShapefileFormat.Polygons(rings, cancelled.Token));
+ Assert.NotNull(ShapefileFormat.Polygons(rings, CancellationToken.None));
+ }
+
+ // ---- ZIP bombs ----
+
+ [Fact]
+ public void A_kmz_whose_kml_is_declared_larger_than_the_limit_is_refused_before_it_is_unpacked()
+ {
+ var path = Path.Combine(fx.NewFolder(), "big.kmz");
+ using (var zip = ZipFile.Open(path, ZipArchiveMode.Create))
+ using (var writer = new StreamWriter(zip.CreateEntry("doc.kml").Open()))
+ writer.Write(GeoFormatTests.KmlSample);
+ var error = Assert.Throws<InvalidDataException>(() => KmlFormat.Read(path, zipped: true, CancellationToken.None, maxKmlBytes: 100));
+ Assert.Contains("too large", error.Message);
+ Assert.NotNull(KmlFormat.Read(path, zipped: true, CancellationToken.None)); // within the real limit it reads
+ }
+
+ [Fact]
+ public void A_stream_stops_at_its_limit_however_much_is_behind_it()
+ {
+ // What counts when a ZIP header understates the unpacked size: the bytes really read.
+ using (var exact = new LimitedStream(new MemoryStream(new byte[100]), 100, "limit"))
+ Assert.Equal(100, ReadAll(exact));
+ using var over = new LimitedStream(new MemoryStream(new byte[1000]), 100, "limit reached");
+ Assert.Equal("limit reached", Assert.Throws<InvalidDataException>(() => ReadAll(over)).Message);
+ }
+
+ private static int ReadAll(Stream stream)
+ {
+ var total = 0;
+ var buffer = new byte[16];
+ int read;
+ while ((read = stream.Read(buffer)) > 0)
+ total += read;
+ return total;
+ }
+
+ // ---- dBASE ----
+
+ [Fact]
+ public async Task A_big_attribute_table_next_to_a_few_shapes_is_read_only_as_far_as_the_shapes()
+ {
+ var dbf = new DbfBuilder().Field("ID", 'N', 8).Field("NAME", 'C', 30);
+ for (var i = 0; i < 50_000; i++)
+ dbf.Row(i.ToString(), "row " + i);
+ var folder = fx.NewFolder();
+ var shp = new ShapefileBuilder(1).Point(1, 1).Save(folder, "one", Wgs84Prj, dbf);
+
+ var table = DbfFormat.Read(Path.ChangeExtension(shp, "dbf"), null, 1, CancellationToken.None);
+ Assert.Single(table.Rows);
+ Assert.Empty(DbfFormat.Read(Path.ChangeExtension(shp, "dbf"), null, 0, CancellationToken.None).Rows);
+ Assert.Equal(50_000, DbfFormat.Read(Path.ChangeExtension(shp, "dbf"), null, int.MaxValue, CancellationToken.None).Rows.Count);
+
+ using var doc = GeoFixtures.ReadJson((await fx.ConvertOkAsync(shp, "geojson")).Single());
+ var features = doc.RootElement.GetProperty("features");
+ Assert.Equal(1, features.GetArrayLength());
+ Assert.Equal("row 0", features[0].GetProperty("properties").GetProperty("NAME").GetString());
+ }
+
+ [Fact]
+ public void Fields_of_length_zero_of_every_type_are_read_as_empty_not_a_crash()
+ {
+ var dbf = new DbfBuilder();
+ foreach (var type in "CNFLDMIBO+TGY")
+ dbf.Field("F" + type, type, 0);
+ dbf.Field("REAL", 'C', 4).Row("", "", "", "", "", "", "", "", "", "", "", "", "", "ok").Row();
+ var path = Path.Combine(fx.NewFolder(), "zero.dbf");
+ dbf.Save(path);
+
+ var table = DbfFormat.Read(path, null, 10, CancellationToken.None);
+ Assert.Equal(2, table.Rows.Count);
+ Assert.Equal("ok", table.Rows[0]![^1]);
+ Assert.All(table.Rows[0]!.Take(table.Fields.Count - 1), value => Assert.True(value is null or ""));
+ }
+
+ [Theory]
+ [InlineData("CP949")]
+ [InlineData("cp949")]
+ [InlineData("UHC")]
+ [InlineData("MS949")]
+ [InlineData("windows-949")]
+ [InlineData("KS_C_5601-1987")]
+ public async Task Korean_code_page_names_in_a_cpg_are_understood(string cpg)
+ {
+ const string text = "서울특별시 종로구";
+ var dbf = new DbfBuilder { Encoding = Encoding.GetEncoding(949) }.Field("NAME", 'C', 40).Row(text);
+ var folder = fx.NewFolder();
+ var shp = new ShapefileBuilder(1).Point(1, 1).Save(folder, "kr", Wgs84Prj, dbf);
+ File.WriteAllText(Path.Combine(folder, "kr.cpg"), cpg);
+ using var doc = GeoFixtures.ReadJson((await fx.ConvertOkAsync(shp, "geojson")).Single());
+ Assert.Equal(text, doc.RootElement.GetProperty("features")[0].GetProperty("properties").GetProperty("NAME").GetString());
+ }
+
+ // ---- .prj ----
+
+ [Theory]
+ [InlineData("")]
+ [InlineData(" \r\n")]
+ [InlineData("")]
+ public async Task An_empty_prj_counts_as_no_prj(string prj)
+ {
+ // Degrees convert as they are...
+ var folder = fx.NewFolder();
+ var shp = new ShapefileBuilder(1).Point(16.37, 48.2).Save(folder, "empty", prj);
+ using (var doc = GeoFixtures.ReadJson((await fx.ConvertOkAsync(shp, "geojson")).Single()))
+ Assert.Equal([16.37, 48.2], GeoFixtures.Position(doc.RootElement.GetProperty("features")[0].GetProperty("geometry")));
+ // ...and metres, with nothing to say what they are, are refused as for a missing .prj (not as an unsupported system).
+ var projected = new ShapefileBuilder(1).Point(602065.2, 5340353.6).Save(fx.NewFolder(), "metres", prj);
+ var (key, _) = await fx.ConvertFailsAsync(projected, "geojson");
+ Assert.Equal("error.geo_unknown_crs", key);
+ }
+
+ // ---- GeoJSON numbers ----
+
+ [Fact]
+ public async Task GeoJson_numbers_beyond_the_double_range_are_no_height_no_position_and_text_in_attributes()
+ {
+ var height = """{"type":"Feature","properties":{"big":1e400,"n":1},"geometry":{"type":"Point","coordinates":[1,2,1e400]}}""";
+ using (var doc = GeoFixtures.ReadJson((await fx.ConvertOkAsync(GeoFixtures.WriteText(fx, "z.geojson", height), "geojson")).Single()))
+ {
+ var feature = doc.RootElement.GetProperty("features")[0];
+ Assert.Equal([1.0, 2.0], GeoFixtures.Position(feature.GetProperty("geometry")));
+ Assert.Equal("1e400", feature.GetProperty("properties").GetProperty("big").GetString());
+ Assert.Equal(1, feature.GetProperty("properties").GetProperty("n").GetInt64());
+ }
+ var position = """{"type":"Point","coordinates":[1e400,2]}""";
+ var (key, detail) = await fx.ConvertFailsAsync(GeoFixtures.WriteText(fx, "x.geojson", position), "kml");
+ Assert.Equal("error.conversion_failed", key);
+ Assert.Contains("too large", detail);
+ }
+}
diff --git a/tests/Filee.Engines.Tests/GeoRobustnessTests.cs b/tests/Filee.Engines.Tests/GeoRobustnessTests.cs
index a8153fac..cb25c653 100644
--- a/tests/Filee.Engines.Tests/GeoRobustnessTests.cs
+++ b/tests/Filee.Engines.Tests/GeoRobustnessTests.cs
@@ -3,7 +3,6 @@
// read files or expand entities is refused, names with brackets and Korean text work, several files in one job get
// their own consistent names, and a cancelled conversion stops.
-using System.Diagnostics;
using System.Text;
using Filee.Core.Conversion;
using Filee.Core.Presets;
@@ -46,7 +45,7 @@ public class GeoRobustnessTests(EngineFixture fx) : IClassFixture<EngineFixture>
}
/// <summary>Truncates and corrupts the file <paramref name="target"/> of a copied reference set and reads <paramref name="main"/> each time.</summary>
- private void Fuzz(string set, string main, string target, int seed, int mutations = 120)
+ private void Fuzz(string set, string main, string target, int seed, int mutations = 40)
{
var original = Path.Combine(GeoFixtures.Folder, set + "." + target);
var bytes = File.ReadAllBytes(original);
@@ -54,7 +53,7 @@ public class GeoRobustnessTests(EngineFixture fx) : IClassFixture<EngineFixture>
var mainPath = Path.Combine(folder, set + "." + main);
var targetPath = Path.Combine(folder, set + "." + target);
- var lengths = bytes.Length <= 400 ? Enumerable.Range(0, bytes.Length) : Enumerable.Range(0, 400).Select(i => i * bytes.Length / 400);
+ var lengths = bytes.Length <= 150 ? Enumerable.Range(0, bytes.Length) : Enumerable.Range(0, 150).Select(i => i * bytes.Length / 150);
foreach (var length in lengths)
{
File.WriteAllBytes(targetPath, bytes[..length]);
@@ -81,17 +80,13 @@ public class GeoRobustnessTests(EngineFixture fx) : IClassFixture<EngineFixture>
[InlineData("gdal_linesz", "shp", "shp")]
[InlineData("gdal_utm33", "shp", "shp")]
[InlineData("gdal_utm33", "shp", "prj")]
- [InlineData("gdal_points", "geojson", "geojson")]
- [InlineData("gdal_points", "kml", "kml")]
- [InlineData("gdal_waypoints", "gpx", "gpx")]
public void Damaged_reference_files_are_read_or_refused_never_a_crash(string set, string main, string target)
{
- var watch = Stopwatch.StartNew();
Fuzz(set, main, target, seed: set.Length * 31 + target.Length);
- Assert.True(watch.Elapsed < TimeSpan.FromSeconds(60), $"took {watch.Elapsed}");
}
[Theory]
+ [InlineData("geojson")]
[InlineData("kml")]
[InlineData("gpx")]
[InlineData("csv")]
@@ -110,16 +105,16 @@ public class GeoRobustnessTests(EngineFixture fx) : IClassFixture<EngineFixture>
}
else
{
- original = Encoding.UTF8.GetBytes(format switch { "kml" => GeoFormatTests.KmlSample, "gpx" => GeoFormatTests.GpxSample, _ => CsvSample });
+ original = Encoding.UTF8.GetBytes(format switch { "geojson" => GeoFixtures.PointsGeoJson, "kml" => GeoFormatTests.KmlSample, "gpx" => GeoFormatTests.GpxSample, _ => CsvSample });
}
var target = Path.Combine(folder, "damaged." + format);
- for (var length = 0; length < original.Length; length += Math.Max(1, original.Length / 250))
+ for (var length = 0; length < original.Length; length += Math.Max(1, original.Length / 120))
{
File.WriteAllBytes(target, original[..length]);
ReadOrRefuse(target);
}
var random = new Random(3);
- for (var i = 0; i < 200; i++)
+ for (var i = 0; i < 80; i++)
{
var copy = (byte[])original.Clone();
for (var change = random.Next(1, 6); change > 0; change--)
@@ -136,7 +131,7 @@ public class GeoRobustnessTests(EngineFixture fx) : IClassFixture<EngineFixture>
var folder = fx.NewFolder();
foreach (var extension in new[] { "shp", "geojson", "kml", "kmz", "gpx", "csv" })
{
- for (var i = 0; i < 40; i++)
+ for (var i = 0; i < 15; i++)
{
var bytes = new byte[random.Next(0, 3000)];
random.NextBytes(bytes);
@@ -166,16 +161,14 @@ public class GeoRobustnessTests(EngineFixture fx) : IClassFixture<EngineFixture>
}
[Fact]
- public async Task An_entity_bomb_is_refused_quickly()
+ public async Task An_entity_bomb_is_refused()
{
var builder = new StringBuilder("""<?xml version="1.0"?><!DOCTYPE kml [<!ENTITY a0 "lol">""");
for (var i = 1; i < 10; i++)
builder.Append($"<!ENTITY a{i} \"{string.Concat(Enumerable.Repeat($"&a{i - 1};", 10))}\">");
builder.Append("]><kml><Placemark><name>&a9;</name><Point><coordinates>1,2</coordinates></Point></Placemark></kml>");
- var watch = Stopwatch.StartNew();
var (key, _) = await fx.ConvertFailsAsync(GeoFixtures.WriteText(fx, "bomb.kml", builder.ToString()), "geojson");
Assert.Equal("error.conversion_failed", key);
- Assert.True(watch.Elapsed < TimeSpan.FromSeconds(5), $"took {watch.Elapsed}");
}
// ---- Names, parallel files, cancellation ----
diff --git a/tests/Filee.Engines.Tests/GeoZipTests.cs b/tests/Filee.Engines.Tests/GeoZipTests.cs
index 8b2642b6..769b0fa6 100644
--- a/tests/Filee.Engines.Tests/GeoZipTests.cs
+++ b/tests/Filee.Engines.Tests/GeoZipTests.cs
@@ -24,22 +24,22 @@ public class GeoZipTests(EngineFixture fx) : IClassFixture<EngineFixture>
[Fact]
public async Task A_shapefile_becomes_one_zip_with_its_five_files_and_nothing_else()
{
- var input = GeoFixtures.Copy(fx, "gdal_points", "geojson");
+ var input = GeoFixtures.Points(fx, "geojson");
var folder = Path.GetDirectoryName(input)!;
var before = Names(folder);
var outputs = await fx.ConvertOkAsync(input, "shp", Zip);
var zip = Assert.Single(outputs);
Assert.EndsWith(".zip", zip);
- Assert.Equal(["gdal_points.cpg", "gdal_points.dbf", "gdal_points.prj", "gdal_points.shp", "gdal_points.shx"], Entries(zip));
+ Assert.Equal(["points.cpg", "points.dbf", "points.prj", "points.shp", "points.shx"], Entries(zip));
// The folder gained the ZIP and no loose files: the Shapefile files that were there already are the fixture's own.
- Assert.Equal([.. before.Append("gdal_points.zip").Order()], Names(folder));
+ Assert.Equal([.. before.Append("points.zip").Order()], Names(folder));
}
[Fact]
public async Task The_zipped_shapefile_is_the_same_shapefile_as_the_loose_one()
{
- var input = GeoFixtures.Copy(fx, "gdal_points", "geojson");
+ var input = GeoFixtures.Points(fx, "geojson");
var loose = await fx.ConvertOkAsync(input, "shp");
var zip = (await fx.ConvertOkAsync(input, "shp", Zip)).Single();
@@ -85,11 +85,11 @@ public class GeoZipTests(EngineFixture fx) : IClassFixture<EngineFixture>
[Fact]
public async Task The_conflict_policy_applies_to_the_zip()
{
- var input = GeoFixtures.Copy(fx, "gdal_points", "geojson");
+ var input = GeoFixtures.Points(fx, "geojson");
var first = (await fx.ConvertOkAsync(input, "shp", Zip)).Single();
var second = (await fx.ConvertOkAsync(input, "shp", Zip)).Single();
- Assert.Equal("gdal_points.zip", Path.GetFileName(first));
- Assert.Equal("gdal_points (2).zip", Path.GetFileName(second));
+ Assert.Equal("points.zip", Path.GetFileName(first));
+ Assert.Equal("points (2).zip", Path.GetFileName(second));
var length = new FileInfo(first).Length;
File.WriteAllText(first, "stale");
@@ -106,14 +106,14 @@ public class GeoZipTests(EngineFixture fx) : IClassFixture<EngineFixture>
[Fact]
public async Task The_name_pattern_names_the_zip()
{
- var input = GeoFixtures.Copy(fx, "gdal_points", "geojson");
+ var input = GeoFixtures.Points(fx, "geojson");
var zip = (await fx.ConvertOkAsync(input, "shp", preset =>
{
preset.Output.ZipResult = true;
preset.Output.FileNamePattern = "{name}_wgs84";
})).Single();
- Assert.Equal("gdal_points_wgs84.zip", Path.GetFileName(zip));
- Assert.Contains("gdal_points.shp", Entries(zip)); // the files inside keep the source's name
+ Assert.Equal("points_wgs84.zip", Path.GetFileName(zip));
+ Assert.Contains("points.shp", Entries(zip)); // the files inside keep the source's name
}
[Fact]