diff --git a/README.md b/README.md index 1c49e0d..4d054e1 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,13 @@ JSON and CSV reports, ICMP and HTTP ping, IPv4 and IPv6 forcing, source address, interface and firewall mark binding, custom CA bundles and the server list filters. +When a LibreSpeed server returns optional approximate IP location metadata, JSON +reports add `client.location` and CSV reports append `City`, `Region`, `Country`, +`Country Name`, `Latitude`, and `Longitude` after `IP`. The existing JSON client +fields and the first nine CSV columns retain their previous meanings and +positions. No browser GPS location is requested. Legacy `rawIspInfo` city, +region, country, and `loc` fields remain available as fallbacks. + > [!NOTE] > Agreement is a test, not a claim. `tests/parity` runs both binaries against > the same backend and compares their output, error output and exit status. @@ -117,8 +124,9 @@ filters. | Compared | Result | | --- | --- | -| Reports and errors | Same: `--list`, `--csv-header`, `--simple`, `--csv`, `--json`, `--json-stream`, the `--debug` lines, usage errors, error lines and the exit status of a failed run | +| Reports and errors | Same apart from documented additive location metadata: `--list`, `--simple`, `--csv`, `--json`, `--json-stream`, the `--debug` lines, usage errors, error lines and the exit status of a failed run | | `--help` | Every shared option reads the same apart from a typo corrected in `--telemetry-json` | +| `--csv-header` | Pinned Go emits nine columns; Rust appends six location columns | | Only here | `--http2`, and `--version` names this repository instead of the Go one | ## Differences from the Go implementation @@ -133,6 +141,11 @@ deliberately different. such as bidi overrides and zero-width joiners, and the invisible tag block, in terminal, CSV and JSON output alike. The characters are removed, not escaped. Go cleans only C0, DEL and C1, and only in terminal output. +- **Approximate location metadata is additive.** When a server returns location + data, Rust adds it to terminal, JSON/JSON-stream and 15-column CSV output + while preserving the legacy `processedString` and `rawIspInfo` fields. The + pinned Go client retains its legacy terminal/JSON/CSV layouts. No browser GPS + or exact device location is requested. - **CSV formulas are defused.** A field starting with `=`, `+`, `-` or `@` gets a leading single quote, because spreadsheets evaluate what is left after unquoting. diff --git a/src/defs/mod.rs b/src/defs/mod.rs index 502bf3b..55a8d9c 100644 --- a/src/defs/mod.rs +++ b/src/defs/mod.rs @@ -7,7 +7,10 @@ pub mod telemetry; pub use server::Server; pub use telemetry::{TelemetryExtra, TelemetryLog, TelemetryServer}; -use serde::{Deserialize, Serialize}; +use serde::ser::SerializeMap; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +use crate::output::sanitize; /// The program name, as reported by `--version`. pub const PROG_NAME: &str = "librespeed-cli"; @@ -59,6 +62,14 @@ pub struct GetIPResult { // view is available through ip_info(). #[serde(rename = "rawIspInfo", default)] pub raw_isp_info: serde_json::Value, + /// Optional approximate IP-derived location supplied by newer backends. + #[serde( + rename = "location", + default, + deserialize_with = "deserialize_optional_location", + skip_serializing_if = "Option::is_none" + )] + pub location: Option, } impl GetIPResult { @@ -105,6 +116,379 @@ impl GetIPResult { _ => String::new(), } } + + /// The structured approximate location to display or report. + /// + /// A top-level location object takes precedence. Older backends only expose + /// city, region, country and `loc` inside rawIspInfo, so those fields remain + /// usable as a legacy fallback instead of being discarded. + pub fn approximate_location(&self) -> Option { + if let Some(location) = &self.location { + let location = location.normalized(); + if !location.is_empty() { + return Some(location); + } + } + + let location = if let serde_json::Value::Object(raw) = &self.raw_isp_info { + Location::from_value(&serde_json::Value::Object(raw.clone())) + } else { + Location::from_ip_info(&self.ip_info()) + }; + + if location.is_empty() { + None + } else { + Some(location) + } + } +} + +/// Approximate IP-derived location metadata. +#[derive(Debug, Default, Clone, PartialEq)] +pub struct Location { + pub city: String, + pub region: String, + pub country: String, + pub country_name: String, + pub latitude: Option, + pub longitude: Option, +} + +impl Location { + fn from_value(value: &serde_json::Value) -> Self { + let Some(object) = value.as_object() else { + return Self::default(); + }; + + let nested_location = object + .get("location") + .and_then(serde_json::Value::as_object); + let string_from = |source: &serde_json::Map, key: &str| { + sanitize( + source + .get(key) + .and_then(serde_json::Value::as_str) + .unwrap_or_default(), + ) + .trim() + .to_string() + }; + let string = |key: &str| { + let top = string_from(object, key); + if top.is_empty() { + nested_location + .map(|source| string_from(source, key)) + .unwrap_or_default() + } else { + top + } + }; + + let raw_country = string("country"); + let country_name_explicit = ["countryName", "country_name"] + .into_iter() + .filter_map(|key| { + let top = string_from(object, key); + if top.is_empty() { + nested_location + .map(|source| string_from(source, key)) + .filter(|value| !value.is_empty()) + } else { + Some(top) + } + }) + .find(|value| !value.is_empty()) + .unwrap_or_default(); + let country_code_alias = [ + "countryCode", + "country_code", + "iso_code", + "country_iso_code", + ] + .into_iter() + .filter_map(|key| { + let top = string_from(object, key); + if top.is_empty() { + nested_location + .map(|source| string_from(source, key)) + .filter(|value| !value.is_empty()) + } else { + Some(top) + } + }) + .find(|value| !value.is_empty()) + .unwrap_or_default(); + let country = if !country_code_alias.is_empty() { + country_code_alias + } else if looks_like_country_code(&raw_country) { + raw_country.clone() + } else { + String::new() + }; + let country_name = if !country_name_explicit.is_empty() { + country_name_explicit + } else if !raw_country.is_empty() && !looks_like_country_code(&raw_country) { + raw_country + } else { + String::new() + }; + let (latitude, longitude) = parse_location_coordinates(object); + + Self { + city: string("city"), + region: string("region"), + country, + country_name, + latitude, + longitude, + } + } + + pub(crate) fn from_ip_info(info: &IPInfoResponse) -> Self { + let (latitude, longitude) = parse_location_string(&info.location); + Self { + city: info.city.clone(), + region: info.region.clone(), + country: info.country.clone(), + country_name: String::new(), + latitude, + longitude, + } + } + + pub fn is_empty(&self) -> bool { + sanitize(&self.city).trim().is_empty() + && sanitize(&self.region).trim().is_empty() + && sanitize(&self.country).trim().is_empty() + && sanitize(&self.country_name).trim().is_empty() + && self.latitude.is_none() + && self.longitude.is_none() + } + + fn normalized(&self) -> Self { + Self { + city: sanitize(&self.city).trim().to_string(), + region: sanitize(&self.region).trim().to_string(), + country: sanitize(&self.country).trim().to_string(), + country_name: sanitize(&self.country_name).trim().to_string(), + latitude: self.valid_latitude(), + longitude: self.valid_longitude(), + } + } + + fn valid_latitude(&self) -> Option { + self.latitude + .filter(|value| value.is_finite() && (-90.0..=90.0).contains(value)) + } + + fn valid_longitude(&self) -> Option { + self.longitude + .filter(|value| value.is_finite() && (-180.0..=180.0).contains(value)) + } + + /// Formats the approximate location for terminal/report text. + pub fn human_readable(&self) -> Option { + let mut place = Vec::new(); + let country_name = sanitize(&self.country_name).trim().to_string(); + let country_code = sanitize(&self.country).trim().to_string(); + let country = if country_name.is_empty() { + country_code.as_str() + } else { + country_name.as_str() + }; + + for value in [self.city.as_str(), self.region.as_str(), country] { + let value = sanitize(value).trim().to_string(); + if !value.is_empty() && !place.iter().any(|existing: &String| existing == &value) { + place.push(value); + } + } + + let coordinates = match (self.valid_latitude(), self.valid_longitude()) { + (Some(latitude), Some(longitude)) => Some(format!( + "latitude {}, longitude {}", + format_coordinate(latitude), + format_coordinate(longitude) + )), + (Some(latitude), None) => Some(format!("latitude {}", format_coordinate(latitude))), + (None, Some(longitude)) => Some(format!("longitude {}", format_coordinate(longitude))), + _ => None, + }; + + match (place.join(", "), coordinates) { + (place, Some(coordinates)) if !place.is_empty() => { + Some(format!("{place} ({coordinates})")) + } + (place, None) if !place.is_empty() => Some(place), + (place, Some(coordinates)) if place.is_empty() => Some(coordinates), + _ => None, + } + } +} + +impl<'de> Deserialize<'de> for Location { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let value = serde_json::Value::deserialize(deserializer)?; + Ok(Self::from_value(&value)) + } +} + +impl Serialize for Location { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let city = sanitize(&self.city); + let region = sanitize(&self.region); + let country = sanitize(&self.country); + let country_name = sanitize(&self.country_name); + let latitude = self.valid_latitude(); + let longitude = self.valid_longitude(); + + let mut fields = 0usize; + for value in [&city, ®ion, &country, &country_name] { + if !value.is_empty() { + fields += 1; + } + } + if latitude.is_some() { + fields += 1; + } + if longitude.is_some() { + fields += 1; + } + + let mut map = serializer.serialize_map(Some(fields))?; + if !city.is_empty() { + map.serialize_entry("city", &city)?; + } + if !region.is_empty() { + map.serialize_entry("region", ®ion)?; + } + if !country.is_empty() { + map.serialize_entry("country", &country)?; + } + if !country_name.is_empty() { + map.serialize_entry("countryName", &country_name)?; + } + if let Some(latitude) = latitude { + map.serialize_entry("latitude", &latitude)?; + } + if let Some(longitude) = longitude { + map.serialize_entry("longitude", &longitude)?; + } + map.end() + } +} + +fn deserialize_optional_location<'de, D>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + let value = Option::::deserialize(deserializer)?; + match value { + Some(value) if value.is_object() => { + let location = Location::from_value(&value); + Ok((!location.is_empty()).then_some(location)) + } + _ => Ok(None), + } +} + +fn parse_valid_coordinate( + value: Option<&serde_json::Value>, + minimum: f64, + maximum: f64, +) -> Option { + let parsed = match value { + Some(serde_json::Value::Number(number)) => number.as_f64(), + Some(serde_json::Value::String(value)) => value.trim().parse::().ok(), + _ => None, + }?; + + (parsed.is_finite() && (minimum..=maximum).contains(&parsed)).then_some(parsed) +} + +fn looks_like_country_code(value: &str) -> bool { + value.len() == 2 && value.bytes().all(|byte| byte.is_ascii_alphabetic()) +} + +fn first_valid_coordinate( + object: &serde_json::Map, + keys: &[&str], + minimum: f64, + maximum: f64, +) -> Option { + keys.iter() + .find_map(|key| parse_valid_coordinate(object.get(*key), minimum, maximum)) +} + +fn parse_location_coordinates( + object: &serde_json::Map, +) -> (Option, Option) { + let mut latitude = first_valid_coordinate(object, &["latitude", "lat"], -90.0, 90.0); + let mut longitude = first_valid_coordinate(object, &["longitude", "lon"], -180.0, 180.0); + + for container in ["coordinates", "location"] { + if let Some(nested) = object.get(container).and_then(serde_json::Value::as_object) { + if latitude.is_none() { + latitude = first_valid_coordinate(nested, &["latitude", "lat"], -90.0, 90.0); + } + if longitude.is_none() { + longitude = first_valid_coordinate(nested, &["longitude", "lon"], -180.0, 180.0); + } + if latitude.is_none() || longitude.is_none() { + if let Some(loc) = nested.get("loc").and_then(serde_json::Value::as_str) { + let (loc_latitude, loc_longitude) = parse_location_string(loc); + if latitude.is_none() { + latitude = loc_latitude; + } + if longitude.is_none() { + longitude = loc_longitude; + } + } + } + } + } + + for key in ["loc", "location"] { + if let Some(loc) = object.get(key).and_then(serde_json::Value::as_str) { + let (loc_latitude, loc_longitude) = parse_location_string(loc); + if latitude.is_none() { + latitude = loc_latitude; + } + if longitude.is_none() { + longitude = loc_longitude; + } + } + } + + (latitude, longitude) +} + +fn parse_location_string(value: &str) -> (Option, Option) { + let mut coordinates = value.split(','); + let latitude = coordinates + .next() + .and_then(|value| value.trim().parse::().ok()) + .filter(|value| value.is_finite() && (-90.0..=90.0).contains(value)); + let longitude = coordinates + .next() + .and_then(|value| value.trim().parse::().ok()) + .filter(|value| value.is_finite() && (-180.0..=180.0).contains(value)); + (latitude, longitude) +} + +fn format_coordinate(value: f64) -> String { + if value == 0.0 { + "0".to_string() + } else { + value.to_string() + } } /// The JSON returned by IPInfo.io's API. @@ -194,6 +578,226 @@ mod tests { assert_eq!(parsed.ip(), "192.0.2.1"); } + #[test] + fn get_ip_result_reads_structured_location() { + let json = r#"{ + "processedString":"203.0.113.7 - Example ISP", + "rawIspInfo":{"ip":"203.0.113.7","org":"AS64496 Example ISP"}, + "location":{ + "city":"Boydton", + "region":"Virginia", + "country":"US", + "countryName":"United States", + "latitude":36.6676, + "longitude":-78.3875 + } + }"#; + let parsed: GetIPResult = serde_json::from_str(json).expect("should parse"); + let location = parsed.location.as_ref().expect("top-level location"); + assert_eq!(location.city, "Boydton"); + assert_eq!(location.region, "Virginia"); + assert_eq!(location.country, "US"); + assert_eq!(location.country_name, "United States"); + assert_eq!(location.latitude, Some(36.6676)); + assert_eq!(location.longitude, Some(-78.3875)); + assert_eq!( + parsed + .approximate_location() + .and_then(|value| value.human_readable()), + Some( + "Boydton, Virginia, United States (latitude 36.6676, longitude -78.3875)" + .to_string() + ) + ); + } + + #[test] + fn structured_location_accepts_numeric_strings_but_rejects_bad_coordinates() { + let json = r#"{ + "location":{ + "city":"Numeric City", + "latitude":"36.6676", + "longitude":"-78.3875" + } + }"#; + let parsed: GetIPResult = serde_json::from_str(json).expect("should parse"); + let location = parsed.location.expect("string coordinates"); + assert_eq!(location.latitude, Some(36.6676)); + assert_eq!(location.longitude, Some(-78.3875)); + + for (latitude, longitude, want_latitude, want_longitude) in [ + ("91", "-78", None, Some(-78.0)), + ("36", "181", Some(36.0), None), + ("NaN", "Infinity", None, None), + ("null", "null", None, None), + ] { + let json = format!( + r#"{{"location":{{"city":"Partial City","latitude":"{latitude}","longitude":"{longitude}"}}}}"# + ); + let parsed: GetIPResult = serde_json::from_str(&json).expect("should parse"); + let location = parsed.location.expect("valid text should remain"); + assert_eq!(location.latitude, want_latitude, "for latitude {latitude}"); + assert_eq!( + location.longitude, want_longitude, + "for longitude {longitude}" + ); + } + } + + #[test] + fn structured_location_accepts_coordinate_aliases_and_fallbacks() { + for json in [ + r#"{"location":{"city":"Boydton","latitude":91,"longitude":181,"lat":"36.6676","lon":"-78.3875","loc":"37,-79"}}"#, + r#"{"location":{"city":"Boydton","coordinates":{"latitude":"36.6676","longitude":"-78.3875"}}}"#, + r#"{"location":{"city":"Boydton","loc":"36.6676,-78.3875"}}"#, + r#"{"location":{"city":"Boydton","location":{"lat":36.6676,"lon":-78.3875}}}"#, + ] { + let parsed: GetIPResult = serde_json::from_str(json).expect("should parse"); + let location = parsed.location.expect("coordinate fallback"); + assert_eq!(location.latitude, Some(36.6676), "for {json}"); + assert_eq!(location.longitude, Some(-78.3875), "for {json}"); + } + } + + #[test] + fn partial_location_place_and_coordinate_metadata_remains_usable() { + for (json, want) in [ + ( + r#"{"location":{"city":"Boydton","latitude":36.6676}}"#, + "Boydton (latitude 36.6676)", + ), + ( + r#"{"location":{"country":"US","longitude":-78.3875}}"#, + "US (longitude -78.3875)", + ), + (r#"{"location":{"latitude":36.6676}}"#, "latitude 36.6676"), + ( + r#"{"location":{"longitude":-78.3875}}"#, + "longitude -78.3875", + ), + ] { + let parsed: GetIPResult = serde_json::from_str(json).expect("should parse"); + let location = parsed.location.expect("partial location"); + assert_eq!( + location.human_readable(), + Some(want.to_string()), + "for {json}" + ); + } + } + + #[test] + fn get_ip_result_tolerates_missing_and_malformed_location() { + for location in ["null", "123", "\"Boydton\"", "[]", "{}"] { + let json = format!(r#"{{"processedString":"x","location":{location}}}"#); + let parsed: GetIPResult = serde_json::from_str(&json).expect("should parse"); + assert!( + parsed.location.is_none(), + "malformed location accepted: {location}" + ); + } + + let parsed: GetIPResult = + serde_json::from_str(r#"{"processedString":"x"}"#).expect("should parse"); + assert!(parsed.location.is_none()); + } + + #[test] + fn invisible_only_top_city_falls_back_to_legacy_location() { + let json = r#"{ + "processedString":"203.0.113.7 - Example ISP", + "rawIspInfo":{ + "ip":"203.0.113.7", + "city":"Legacy City", + "region":"Legacy Region", + "country":"US", + "loc":"36.25,-78.25" + }, + "location":{"city":"\u200b\u2060"} + }"#; + let parsed: GetIPResult = serde_json::from_str(json).expect("should parse"); + assert!( + parsed.location.is_none(), + "invisible-only city was retained" + ); + + let location = parsed.approximate_location().expect("legacy location"); + assert_eq!(location.city, "Legacy City"); + assert_eq!(location.region, "Legacy Region"); + assert_eq!(location.country, "US"); + assert_eq!( + location.human_readable(), + Some("Legacy City, Legacy Region, US (latitude 36.25, longitude -78.25)".to_string()) + ); + } + + #[test] + fn invisible_country_name_falls_back_to_usable_country_code() { + for country_key in ["country", "country_code", "countryCode"] { + let json = format!( + r#"{{"location":{{"city":"Boydton","countryName":"\u200b\u202e","{country_key}":"US"}}}}"# + ); + let parsed: GetIPResult = serde_json::from_str(&json).expect("should parse"); + let location = parsed.location.expect("usable country code"); + assert_eq!( + location.human_readable(), + Some("Boydton, US".to_string()), + "for {country_key}" + ); + + let serialized = serde_json::to_value(&location).expect("serialize"); + assert_eq!(serialized["country"], "US", "for {country_key}"); + assert!(serialized.get("countryName").is_none(), "for {country_key}"); + } + } + + #[test] + fn legacy_raw_isp_info_remains_available_as_location_fallback() { + let json = r#"{ + "processedString":"203.0.113.7 - Example ISP", + "rawIspInfo":{ + "ip":"203.0.113.7", + "city":"Testville", + "region":"Testshire", + "country":"XX", + "countryName":"Test Country", + "loc":"36.25,-78.25", + "org":"AS64496 Example ISP" + } + }"#; + let parsed: GetIPResult = serde_json::from_str(json).expect("should parse"); + let location = parsed.approximate_location().expect("legacy location"); + assert_eq!(location.city, "Testville"); + assert_eq!(location.region, "Testshire"); + assert_eq!(location.country, "XX"); + assert_eq!(location.country_name, "Test Country"); + assert_eq!(location.latitude, Some(36.25)); + assert_eq!(location.longitude, Some(-78.25)); + assert_eq!(parsed.ip_info().organization, "AS64496 Example ISP"); + } + + #[test] + fn structured_location_output_is_sanitized() { + let location = Location { + city: "C\u{200b}ity\u{202e}".into(), + region: "R\u{061c}egion".into(), + country: "X\u{00ad}X".into(), + country_name: "Evil\u{202e}Country".into(), + latitude: Some(36.6676), + longitude: Some(-78.3875), + }; + + let serialized = serde_json::to_string(&location).expect("serialize"); + assert_eq!( + serialized, + r#"{"city":"City","region":"Region","country":"XX","countryName":"EvilCountry","latitude":36.6676,"longitude":-78.3875}"# + ); + assert_eq!( + location.human_readable(), + Some("City, Region, EvilCountry (latitude 36.6676, longitude -78.3875)".to_string()) + ); + } + // The address lives only in processedString whenever rawIspInfo carries // none: live backends answer with an empty string, a JSON null, or -- with // the current ipinfo schema -- an object that has no ip field at all. diff --git a/src/helper.rs b/src/helper.rs index ee9a75a..6ebd10e 100644 --- a/src/helper.rs +++ b/src/helper.rs @@ -146,6 +146,13 @@ pub async fn do_speed_test( "IP info: {}\n", output::sanitize(&isp_info.processed_string) ); + if let Some(location) = isp_info + .approximate_location() + .and_then(|location| location.human_readable()) + { + write_ui!(out, "Approximate location: {}\n", location); + write_debug!(out, "Approximate location: {}\n", location); + } // Latency and jitter. let spinner = if out.quiet { @@ -321,6 +328,7 @@ pub async fn do_speed_test( if cli.csv { // The text fields came off the wire; the report sanitizes and // defuses them as it renders them. + let location = isp_info.approximate_location(); reps_csv.push(CSVReport { timestamp: report::timestamp_now(), name: current_server.name.clone(), @@ -331,6 +339,30 @@ pub async fn do_speed_test( upload: round2(upload_value), share: share_link.clone(), ip: isp_info.ip(), + city: location + .as_ref() + .map(|location| location.city.clone()) + .unwrap_or_default(), + region: location + .as_ref() + .map(|location| location.region.clone()) + .unwrap_or_default(), + country: location + .as_ref() + .map(|location| location.country.clone()) + .unwrap_or_default(), + country_name: location + .as_ref() + .map(|location| location.country_name.clone()) + .unwrap_or_default(), + latitude: location + .as_ref() + .and_then(|location| location.latitude) + .filter(|value| value.is_finite() && (-90.0..=90.0).contains(value)), + longitude: location + .as_ref() + .and_then(|location| location.longitude) + .filter(|value| value.is_finite() && (-180.0..=180.0).contains(value)), }); } else if cli.json || cli.json_stream { let mut ip_info = isp_info.ip_info(); @@ -343,7 +375,7 @@ pub async fn do_speed_test( name: current_server.name.clone(), url: current_server.server.clone(), }, - client: Client::new(ip_info), + client: Client::with_location(ip_info, isp_info.approximate_location()), tls: status.tls.as_ref().map(|t| report::TLSReport { version: t.version.clone(), cipher: t.cipher.clone(), diff --git a/src/report.rs b/src/report.rs index e0476c1..65ce379 100644 --- a/src/report.rs +++ b/src/report.rs @@ -6,7 +6,7 @@ use serde::{Serialize, Serializer}; -use crate::defs::IPInfoResponse; +use crate::defs::{IPInfoResponse, Location}; use crate::output::sanitize; /// Renders a float as Go's `strconv.FormatFloat(v, 'f', -1, 64)` does: the @@ -69,6 +69,24 @@ fn csv_float(v: &f64, s: S) -> Result { s.serialize_str(&plain_float(*v)) } +fn csv_optional_latitude(v: &Option, s: S) -> Result { + match v { + Some(value) if value.is_finite() && (-90.0..=90.0).contains(value) => { + s.serialize_str(&plain_float(*value)) + } + _ => s.serialize_str(""), + } +} + +fn csv_optional_longitude(v: &Option, s: S) -> Result { + match v { + Some(value) if value.is_finite() && (-180.0..=180.0).contains(value) => { + s.serialize_str(&plain_float(*value)) + } + _ => s.serialize_str(""), + } +} + /// Serializes a string that came off the wire, with the terminal-steering and /// text-hiding characters removed. fn clean(v: &str, s: S) -> Result { @@ -199,6 +217,8 @@ pub struct ReportServer { pub struct Client { #[serde(flatten)] ip_info: IPInfoResponse, + #[serde(skip_serializing_if = "Option::is_none")] + location: Option, } impl Client { @@ -208,13 +228,18 @@ impl Client { /// `IPInfoResponse` breaks this function rather than reaching the report /// with whatever the backend put in it. pub fn new(ip_info: IPInfoResponse) -> Self { + Self::with_location(ip_info, None) + } + + /// Builds the client block with an optional structured location. + pub fn with_location(ip_info: IPInfoResponse, location: Option) -> Self { let IPInfoResponse { ip, hostname, city, region, country, - location, + location: legacy_location, organization, postal, timezone, @@ -228,12 +253,13 @@ impl Client { city: sanitize(&city), region: sanitize(®ion), country: sanitize(&country), - location: sanitize(&location), + location: sanitize(&legacy_location), organization: sanitize(&organization), postal: sanitize(&postal), timezone: sanitize(&timezone), readme: sanitize(&readme), }, + location, } } } @@ -298,10 +324,22 @@ pub struct CSVReport { pub share: String, #[serde(rename = "IP", serialize_with = "csv_text")] pub ip: String, + #[serde(rename = "City", serialize_with = "csv_text")] + pub city: String, + #[serde(rename = "Region", serialize_with = "csv_text")] + pub region: String, + #[serde(rename = "Country", serialize_with = "csv_text")] + pub country: String, + #[serde(rename = "Country Name", serialize_with = "csv_text")] + pub country_name: String, + #[serde(rename = "Latitude", serialize_with = "csv_optional_latitude")] + pub latitude: Option, + #[serde(rename = "Longitude", serialize_with = "csv_optional_longitude")] + pub longitude: Option, } /// The CSV column names, in order. -pub const CSV_HEADERS: [&str; 9] = [ +pub const CSV_HEADERS: [&str; 15] = [ "Timestamp", "Server Name", "Address", @@ -311,6 +349,12 @@ pub const CSV_HEADERS: [&str; 9] = [ "Upload", "Share", "IP", + "City", + "Region", + "Country", + "Country Name", + "Latitude", + "Longitude", ]; fn writer(delimiter: u8) -> csv::Writer> { @@ -364,11 +408,11 @@ mod tests { fn header_uses_the_configured_delimiter() { assert_eq!( csv_header(b',').unwrap().trim_end(), - "Timestamp,Server Name,Address,Ping,Jitter,Download,Upload,Share,IP" + "Timestamp,Server Name,Address,Ping,Jitter,Download,Upload,Share,IP,City,Region,Country,Country Name,Latitude,Longitude" ); assert_eq!( csv_header(b';').unwrap().trim_end(), - "Timestamp;Server Name;Address;Ping;Jitter;Download;Upload;Share;IP" + "Timestamp;Server Name;Address;Ping;Jitter;Download;Upload;Share;IP;City;Region;Country;Country Name;Latitude;Longitude" ); } @@ -387,7 +431,26 @@ mod tests { let out = csv_rows(&[rep], b',').unwrap(); assert_eq!( out, - "2026-08-06T15:41:36.067293+02:00,\"Prague, Czech Republic (CESNET)\",https://speedtest.cesnet.cz,6.36,0.82,228.39,553.97,,\n" + "2026-08-06T15:41:36.067293+02:00,\"Prague, Czech Republic (CESNET)\",https://speedtest.cesnet.cz,6.36,0.82,228.39,553.97,,,,,,,,\n" + ); + } + + #[test] + fn rows_append_structured_location_columns() { + let rep = CSVReport { + ip: "203.0.113.7".into(), + city: "Boydton".into(), + region: "Virginia".into(), + country: "US".into(), + country_name: "United States".into(), + latitude: Some(36.6676), + longitude: Some(-78.3875), + ..Default::default() + }; + let out = csv_rows(&[rep], b',').unwrap(); + assert!( + out.ends_with(",203.0.113.7,Boydton,Virginia,US,United States,36.6676,-78.3875\n"), + "{out}" ); } @@ -407,7 +470,7 @@ mod tests { assert!(out.contains(",'@SUM(1+1),")); assert!(out.contains(",'-2+3,")); // The TAB is stripped first, and what is left still gets the prefix. - assert!(out.ends_with(",'=cmd\n"), "{out}"); + assert!(out.ends_with(",'=cmd,,,,,,\n"), "{out}"); // A benign value is untouched. assert!(!csv_rows( &[CSVReport { @@ -434,7 +497,7 @@ mod tests { let out = csv_rows(&[rep], b',').unwrap(); assert_eq!( out, - ",Evil[31m,http://evil1m,0,0,0,0,https://x/?id=1,203.0.113.9[2J\n" + ",Evil[31m,http://evil1m,0,0,0,0,https://x/?id=1,203.0.113.9[2J,,,,,,\n" ); } @@ -492,13 +555,23 @@ mod tests { name: "Evil\x1b[31m\u{9b}1m\u{202e}txen\u{e0041}".into(), url: "http://evil\u{ad}.example".into(), }, - client: Client::new(IPInfoResponse { - ip: "203.0.113.9\x1b[2J".into(), - hostname: "h\u{9b}31m.example".into(), - organization: "Evil\u{e0041}ISP".into(), - timezone: "UTC\u{2028}".into(), - ..Default::default() - }), + client: Client::with_location( + IPInfoResponse { + ip: "203.0.113.9\x1b[2J".into(), + hostname: "h\u{9b}31m.example".into(), + organization: "Evil\u{e0041}ISP".into(), + timezone: "UTC\u{2028}".into(), + ..Default::default() + }, + Some(Location { + city: "C\u{200b}ity".into(), + region: "R\u{61c}egion".into(), + country: "X\u{ad}X".into(), + country_name: "Evil\u{202e}Country".into(), + latitude: Some(36.6676), + longitude: Some(-78.3875), + }), + ), share: "https://x/?id=1\u{7f}".into(), ..Default::default() }; @@ -509,6 +582,10 @@ mod tests { assert!(out.contains(r#""hostname":"h31m.example""#), "{out}"); assert!(out.contains(r#""org":"EvilISP""#), "{out}"); assert!(out.contains(r#""timezone":"UTC""#), "{out}"); + assert!( + out.contains(r#""location":{"city":"City","region":"Region","country":"XX","countryName":"EvilCountry","latitude":36.6676,"longitude":-78.3875}"#), + "{out}" + ); assert!(out.contains(r#""share":"https://x/?id=1""#), "{out}"); // Nothing that steers a terminal survives anywhere in the document. assert_eq!(sanitize(&out), out, "{out}"); diff --git a/tests/csv_text.rs b/tests/csv_text.rs index dc27615..d8a2a26 100644 --- a/tests/csv_text.rs +++ b/tests/csv_text.rs @@ -1,7 +1,7 @@ -//! The text columns of a CSV report -- Server Name, Address, Share and IP -- -//! are transformed, not merely escaped: characters are removed and a leading -//! apostrophe can be added, so a parser does not get back what the server -//! sent. These tests pin that, and the order the two steps run in. +//! The text columns of a CSV report -- Server Name, Address, Share, IP and +//! location text -- are transformed, not merely escaped: characters are removed +//! and a leading apostrophe can be added, so a parser does not get back what +//! the server sent. These tests pin that, and the order the two steps run in. use librespeed_cli::report::{csv_rows, CSVReport}; @@ -14,6 +14,10 @@ fn stored(value: &str) -> String { address: value.into(), share: value.into(), ip: value.into(), + city: value.into(), + region: value.into(), + country: value.into(), + country_name: value.into(), ..Default::default() }; let out = csv_rows(&[rep], b',').unwrap(); @@ -21,7 +25,7 @@ fn stored(value: &str) -> String { .has_headers(false) .from_reader(out.as_bytes()); let record = reader.records().next().unwrap().unwrap(); - let columns = [1, 2, 7, 8].map(|i| record.get(i).unwrap().to_string()); + let columns = [1, 2, 7, 8, 9, 10, 11, 12].map(|i| record.get(i).unwrap().to_string()); assert!(columns.iter().all(|c| *c == columns[0]), "{columns:?}"); columns[0].clone() } diff --git a/tests/integration.rs b/tests/integration.rs index 67e2e53..1f1eb9f 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -177,7 +177,7 @@ fn handle(mut stream: TcpStream, telemetry_hits: Arc) -> std::io::R // sequences, C1 controls, bidi overrides, invisible tag characters and // the HTML delimiters Go's JSON encoder escapes. ("GET", "/getIP-hostile.php") => { - let json = br#"{"processedString":"203.0.113.9\u001b[2J - Evil\u202eISP","rawIspInfo":{"ip":"203.0.113.9\u001b[2J","hostname":"h\u009b31m.example","city":"C\u200bity","region":"R\u061cegion","country":"X\u00adX","loc":"0,0\u180e","org":"=Evil\udb40\udc41ISP & ","postal":"0\u007f","timezone":"UTC\u2028","readme":"x"}}"#; + let json = br#"{"processedString":"203.0.113.9\u001b[2J - Evil\u202eISP","rawIspInfo":{"ip":"203.0.113.9\u001b[2J","hostname":"h\u009b31m.example","city":"C\u200bity","region":"R\u061cegion","country":"X\u00adX","loc":"0,0\u180e","org":"=Evil\udb40\udc41ISP & ","postal":"0\u007f","timezone":"UTC\u2028","readme":"x"},"location":{"city":"C\u200bity","region":"R\u061cegion","country":"X\u00adX","countryName":"Evil\u202eCountry","latitude":"36.6676","longitude":"-78.3875"}}"#; respond(&mut stream, json, "application/json")? } ("POST", "/results/telemetry.php") => { @@ -241,7 +241,7 @@ fn csv_header_matches_the_go_implementation() { assert!(out.status.success()); assert_eq!( stdout_of(&out).trim_end(), - "Timestamp,Server Name,Address,Ping,Jitter,Download,Upload,Share,IP" + "Timestamp,Server Name,Address,Ping,Jitter,Download,Upload,Share,IP,City,Region,Country,Country Name,Latitude,Longitude" ); } @@ -339,6 +339,12 @@ fn json_report_has_the_expected_shape() { assert_eq!(report["server"]["url"], backend.url()); assert_eq!(report["client"]["ip"], "203.0.113.7"); assert_eq!(report["client"]["org"], "AS64496 Example ISP"); + assert_eq!(report["client"]["location"]["city"], "Testville"); + assert_eq!(report["client"]["location"]["region"], "Testshire"); + assert_eq!(report["client"]["location"]["country"], "XX"); + assert!(report["client"]["location"].get("countryName").is_none()); + assert_eq!(report["client"]["location"]["latitude"], 0.0); + assert_eq!(report["client"]["location"]["longitude"], 0.0); // `readme` is deliberately stripped from the report. assert!(report["client"].get("readme").is_none()); @@ -381,12 +387,15 @@ fn csv_report_honours_a_custom_delimiter() { assert!(stdout.ends_with('\n'), "unterminated row: {stdout:?}"); assert!(!stdout.ends_with("\n\n"), "extra blank line: {stdout:?}"); - // The row splits into the nine documented columns. + // The row splits into the 15 documented columns. let fields: Vec<&str> = stdout.trim_end_matches('\n').split(';').collect(); - assert_eq!(fields.len(), 9, "unexpected row: {stdout:?}"); + assert_eq!(fields.len(), 15, "unexpected row: {stdout:?}"); assert_eq!(fields[1], "Mock csv"); assert_eq!(fields[2], backend.url()); assert_eq!(fields[8], "203.0.113.7"); + assert_eq!(fields[9], "Testville"); + assert_eq!(fields[10], "Testshire"); + assert_eq!(fields[11], "XX"); } // A header and a body written by consecutive runs have to make one valid file; @@ -767,6 +776,10 @@ fn hostile_backend_text_is_stripped_from_every_output() { ); assert!(raw.contains(r#""hostname":"h31m.example""#), "{raw}"); assert!(raw.contains(r#""timezone":"UTC""#), "{raw}"); + assert!( + raw.contains(r#""location":{"city":"City","region":"Region","country":"XX","countryName":"EvilCountry","latitude":36.6676,"longitude":-78.3875}"#), + "{raw}" + ); // The CSV row carries the same cleaned text, including the IP column. let out = run(&[ @@ -783,7 +796,10 @@ fn hostile_backend_text_is_stripped_from_every_output() { ]); let row = stdout_of(&out); assert!(row.contains(",Evil[31mRed1m TXEN tag & ,"), "{row}"); - assert!(row.ends_with(",203.0.113.9[2J\n"), "{row}"); + assert!( + row.ends_with(",203.0.113.9[2J,City,Region,XX,EvilCountry,36.6676,-78.3875\n"), + "{row}" + ); } // A usage error is reported on both streams, the way the Go client's CLI diff --git a/tests/parity/cases.rs b/tests/parity/cases.rs index 8c166da..901cf96 100644 --- a/tests/parity/cases.rs +++ b/tests/parity/cases.rs @@ -18,6 +18,7 @@ pub const GO_COMMIT: &str = "8aefd77bd4bde428cd86d3622102f0ac0443d96e"; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Why { Sanitized, + LocationMetadata, CsvFormulas, CsvQuoting, TelemetryStatus, @@ -44,6 +45,7 @@ impl Why { pub fn readme(self) -> &'static str { match self { Why::Sanitized => "**Everything a server says is sanitized.**", + Why::LocationMetadata => "**Approximate location metadata is additive.**", Why::CsvFormulas => "**CSV formulas are defused.**", Why::CsvQuoting => "**CSV quoting follows the csv crate.**", Why::TelemetryStatus => "**A telemetry reply other than 2xx fails the upload.**", @@ -236,8 +238,24 @@ fn reports() -> Vec { }; vec![ measured("simple", &["--simple"]), - measured("csv", &["--csv"]), - measured("csv_delim_semicolon", &["--csv", "--csv-delimiter", ";"]), + measured("csv", &["--csv"]).stdout( + &[Why::LocationMetadata], + &[ + ",Fixture Live,http://127.0.0.1:/,,,,,,127.0.0.1", + ], + &[ + ",Fixture Live,http://127.0.0.1:/,,,,,,127.0.0.1,,,,,,", + ], + ), + measured("csv_delim_semicolon", &["--csv", "--csv-delimiter", ";"]).stdout( + &[Why::LocationMetadata], + &[ + ";Fixture Live;http://127.0.0.1:/;;;;;;127.0.0.1", + ], + &[ + ";Fixture Live;http://127.0.0.1:/;;;;;;127.0.0.1;;;;;;", + ], + ), measured("json", &["--json"]), measured("debug", &["--debug"]), measured("timeout_0", &["--json", "--timeout", "0"]), @@ -247,7 +265,13 @@ fn reports() -> Vec { SERVERS, &["--duration", "2", "--server", "1", "--json-stream"], ), - listed("csv_header", SERVERS, &["--csv-header"]), + listed("csv_header", SERVERS, &["--csv-header"]).stdout( + &[Why::LocationMetadata], + &["Timestamp,Server Name,Address,Ping,Jitter,Download,Upload,Share,IP"], + &[ + "Timestamp,Server Name,Address,Ping,Jitter,Download,Upload,Share,IP,City,Region,Country,Country Name,Latitude,Longitude", + ], + ), listed("list", SERVERS, &["--list"]), no_transfer("nodl_noul_json", SERVERS, &["--json"]), listed( @@ -667,7 +691,7 @@ fn delimiters() -> Vec { vec![ listed("csv_delim_multi", SERVERS, &["--csv-delimiter", ";;", "--csv-header"]) .stdout( - &[Why::CsvDelimiter], + &[Why::CsvDelimiter, Why::LocationMetadata], &[ "Timestamp;Server Name;Address;Ping;Jitter;Download;Upload;Share;IP", ], @@ -732,42 +756,49 @@ fn lists() -> Vec { "special_csv", SPECIAL, &[ - "--duration", "0", "--server", "1", "--server", "2", "--server", "3", "--server", - "4", "--server", "5", "--no-download", "--no-upload", "--csv", + "--duration", + "0", + "--server", + "1", + "--server", + "2", + "--server", + "3", + "--server", + "4", + "--server", + "5", + "--no-download", + "--no-upload", + "--csv", ], ) .stdout( - &[Why::CsvQuoting, Why::CsvFormulas], + &[Why::CsvQuoting, Why::CsvFormulas, Why::LocationMetadata], &[ + ",AT&T ,http://127.0.0.1:/,,,,,,127.0.0.1", ",\" Leading space\",http://127.0.0.1:/,,,,,,127.0.0.1", ",\"\\.\",http://127.0.0.1:/,,,,,,127.0.0.1", + ",\"Quote\"\"d;semi,comma\",http://127.0.0.1:,,,,,,127.0.0.1", ",=2+5+cmd|' /C calc'!A0,http://127.0.0.1:/,,,,,,127.0.0.1", ], &[ - ", Leading space,http://127.0.0.1:/,,,,,,127.0.0.1", - ",\\.,http://127.0.0.1:/,,,,,,127.0.0.1", - ",'=2+5+cmd|' /C calc'!A0,http://127.0.0.1:/,,,,,,127.0.0.1", + ",AT&T ,http://127.0.0.1:/,,,,,,127.0.0.1,,,,,,", + ", Leading space,http://127.0.0.1:/,,,,,,127.0.0.1,,,,,,", + ",\\.,http://127.0.0.1:/,,,,,,127.0.0.1,,,,,,", + ",\"Quote\"\"d;semi,comma\",http://127.0.0.1:,,,,,,127.0.0.1,,,,,,", + ",'=2+5+cmd|' /C calc'!A0,http://127.0.0.1:/,,,,,,127.0.0.1,,,,,,", ], ), - listed("schemeless_list", SCHEMELESS, &["--list"]) - .stdout( + listed("schemeless_list", SCHEMELESS, &["--list"]).stdout( &[Why::SchemeCase], - &[ - "3: Upper (http://Example.COM/x) ", - ], - &[ - "3: Upper (HTTP://Example.COM/x) ", - ], + &["3: Upper (http://Example.COM/x) "], + &["3: Upper (HTTP://Example.COM/x) "], ), - listed("schemeless_port_list", SCHEMELESS_PORT, &["--list"]) - .stdout( + listed("schemeless_port_list", SCHEMELESS_PORT, &["--list"]).stdout( &[Why::SchemelessPort], - &[ - "1: S1 (localhost:8080/backend) ", - ], - &[ - "1: S1 (http://localhost:8080/backend) ", - ], + &["1: S1 (localhost:8080/backend) "], + &["1: S1 (http://localhost:8080/backend) "], ), ] } @@ -787,27 +818,27 @@ fn hostile() -> Vec { ), no_transfer("hostile_json", HOSTILE, &["--json"]) .stdout( - &[Why::Sanitized], + &[Why::Sanitized, Why::LocationMetadata], &[ "[{\"timestamp\":\"\",\"server\":{\"name\":\"Evil\\u001b[31mRed\u{9b}1m \u{202e}TXEN\u{202c} \u{e0041}\u{e0042}tag \u{61c}\u{ad}\u{180e} \\u0026 \\u003cb\\u003e \u{a0}nbsp\",\"url\":\"http://127.0.0.1:/\"},\"client\":{\"ip\":\"203.0.113.9\\u001b[2J\",\"hostname\":\"h\u{9b}31m.example\",\"city\":\"C\u{200b}ity\",\"region\":\"R\u{61c}egion\",\"country\":\"X\u{ad}X\",\"loc\":\"0,0\u{180e}\",\"org\":\"=Evil\u{e0041}ISP\",\"postal\":\"0\u{7f}\",\"timezone\":\"UTC\\u2028\"},\"bytes_sent\":,\"bytes_received\":,\"ping\":,\"jitter\":,\"upload\":,\"download\":,\"share\":\"\"}]", ], &[ - "[{\"timestamp\":\"\",\"server\":{\"name\":\"Evil[31mRed1m TXEN tag \\u0026 \\u003cb\\u003e \u{a0}nbsp\",\"url\":\"http://127.0.0.1:/\"},\"client\":{\"ip\":\"203.0.113.9[2J\",\"hostname\":\"h31m.example\",\"city\":\"City\",\"region\":\"Region\",\"country\":\"XX\",\"loc\":\"0,0\",\"org\":\"=EvilISP\",\"postal\":\"0\",\"timezone\":\"UTC\"},\"bytes_sent\":,\"bytes_received\":,\"ping\":,\"jitter\":,\"upload\":,\"download\":,\"share\":\"\"}]", + "[{\"timestamp\":\"\",\"server\":{\"name\":\"Evil[31mRed1m TXEN tag \\u0026 \\u003cb\\u003e \u{a0}nbsp\",\"url\":\"http://127.0.0.1:/\"},\"client\":{\"ip\":\"203.0.113.9[2J\",\"hostname\":\"h31m.example\",\"city\":\"City\",\"region\":\"Region\",\"country\":\"XX\",\"loc\":\"0,0\",\"org\":\"=EvilISP\",\"postal\":\"0\",\"timezone\":\"UTC\",\"location\":{\"city\":\"City\",\"region\":\"Region\",\"country\":\"XX\",\"latitude\":0.0}},\"bytes_sent\":,\"bytes_received\":,\"ping\":,\"jitter\":,\"upload\":,\"download\":,\"share\":\"\"}]", ], ), no_transfer("hostile_csv", HOSTILE, &["--csv"]) .stdout( - &[Why::Sanitized], + &[Why::Sanitized, Why::LocationMetadata], &[ ",Evil\u{1b}[31mRed\u{9b}1m \u{202e}TXEN\u{202c} \u{e0041}\u{e0042}tag \u{61c}\u{ad}\u{180e} & \u{a0}nbsp,http://127.0.0.1:/,,,,,,203.0.113.9\u{1b}[2J", ], &[ - ",Evil[31mRed1m TXEN tag & \u{a0}nbsp,http://127.0.0.1:/,,,,,,203.0.113.9[2J", + ",Evil[31mRed1m TXEN tag & \u{a0}nbsp,http://127.0.0.1:/,,,,,,203.0.113.9[2J,City,Region,XX,,0,", ], ), no_transfer("hostile_ui", HOSTILE, &[]) .stderr( - &[Why::Sanitized], + &[Why::Sanitized, Why::LocationMetadata], &[ "Selected server: Evil[31mRed1m \u{202e}TXEN\u{202c} \u{e0041}\u{e0042}tag \u{61c}\u{ad}\u{180e} & \u{a0}nbsp [127.0.0.1]", "Sponsored by: Spon\u{202e}sor]0;title @ https://example.org", @@ -817,11 +848,12 @@ fn hostile() -> Vec { "Selected server: Evil[31mRed1m TXEN tag & \u{a0}nbsp [127.0.0.1]", "Sponsored by: Sponsor]0;title @ https://example.org", "You're testing from: 203.0.113.9[2J - EvilISP", + "Approximate location: City, Region, XX (latitude 0)", ], ), no_transfer("hostile_debug", HOSTILE, &["--debug", "--simple"]) .stderr( - &[Why::Sanitized], + &[Why::Sanitized, Why::LocationMetadata], &[ "Testing against Evil[31mRed1m \u{202e}TXEN\u{202c} \u{e0041}\u{e0042}tag \u{61c}\u{ad}\u{180e} & \u{a0}nbsp (http://127.0.0.1:/)", "IP info: 203.0.113.9[2J - Evil\u{202e}ISP", @@ -830,6 +862,7 @@ fn hostile() -> Vec { &[ "Testing against Evil[31mRed1m TXEN tag & \u{a0}nbsp (http://127.0.0.1:/)", "IP info: 203.0.113.9[2J - EvilISP", + "Approximate location: City, Region, XX (latitude 0)", "Skipping ICMP for server Evil[31mRed1m TXEN tag & \u{a0}nbsp, will use HTTP ping", ], ), diff --git a/tests/parity/normalize.rs b/tests/parity/normalize.rs index 42cd8fa..295fed7 100644 --- a/tests/parity/normalize.rs +++ b/tests/parity/normalize.rs @@ -174,22 +174,48 @@ fn csv_row(line: &str) -> Option { if delimiter.is_alphanumeric() || delimiter == '"' { return None; } - let mut fields: Vec<&str> = line.rsplitn(7, delimiter).collect(); - if fields.len() != 7 { + let mut fields = vec!["".to_string()]; + let mut field = String::new(); + let mut quoted = false; + let data = after.get(delimiter.len_utf8()..)?; + let mut chars = data.chars().peekable(); + while let Some(ch) = chars.next() { + if ch == '"' { + field.push(ch); + if quoted { + if chars.peek() == Some(&'"') { + chars.next(); + field.push('"'); + } else { + quoted = false; + } + } else { + quoted = true; + } + } else if ch == delimiter && !quoted { + fields.push(field.clone()); + field.clear(); + } else { + field.push(ch); + } + } + fields.push(field); + if fields.len() != 9 && fields.len() != 15 { return None; } - fields.reverse(); - let mut row = vec![fields[0].to_string()]; - for measured in &fields[1..5] { - row.push(if is_go_rounded(measured) { - "".to_string() + + for index in 3..7 { + let raw = fields.get(index)?.trim(); + let value = if raw.starts_with('"') && raw.ends_with('"') && raw.len() >= 2 { + raw[1..raw.len() - 1].replace("\"\"", "\"") } else { - measured.to_string() - }); + raw.to_string() + }; + if is_go_rounded(&value) { + fields[index] = "".to_string(); + } } - row.push(fields[5].to_string()); - row.push(fields[6].to_string()); - Some(row.join(&delimiter.to_string())) + Some(fields.join(&delimiter.to_string())) } /// The measured members of a report and of a progress event. `seconds` is @@ -481,6 +507,38 @@ mod tests { ); } + #[test] + fn csv_rows_support_go_nine_columns() { + assert_eq!( + one(",Fixture Live,http://127.0.0.1:/,0.06,0,68285.34,44536.7,,127.0.0.1"), + ",Fixture Live,http://127.0.0.1:/,,,,,,127.0.0.1" + ); + } + + #[test] + fn csv_rows_support_rust_location_columns() { + assert_eq!( + one(",Fixture Live,http://127.0.0.1:/,0.06,0,68285.34,44536.7,,127.0.0.1,City,Region,XX,,0,"), + ",Fixture Live,http://127.0.0.1:/,,,,,,127.0.0.1,City,Region,XX,,0," + ); + } + + #[test] + fn csv_rows_preserve_quoting_outside_measurements() { + assert_eq!( + one(",\" Leading space\",http://127.0.0.1//,0.06,0,1,2,,127.0.0.1"), + ",\" Leading space\",http://127.0.0.1//,,,,,,127.0.0.1" + ); + assert_eq!( + one(",\"Quote\"\"d;semi,comma\",http://127.0.0.1/,0.06,0,1,2,,127.0.0.1"), + ",\"Quote\"\"d;semi,comma\",http://127.0.0.1/,,,,,,127.0.0.1" + ); + assert_eq!( + one(",\\.,http://127.0.0.1//,0.06,0,1,2,,127.0.0.1"), + ",\\.,http://127.0.0.1//,,,,,,127.0.0.1" + ); + } + #[test] fn a_number_go_would_not_print_is_left_alone() { for odd in [