diff --git a/README.md b/README.md index 0abd605..39dd9aa 100644 --- a/README.md +++ b/README.md @@ -219,6 +219,14 @@ GLOBAL OPTIONS: Implies --share ``` +When the selected 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` columns after `IP`. The existing JSON client +fields and first nine CSV columns retain their previous meanings and positions. No browser +GPS location is requested. The legacy JSON `client.city`, `client.region`, and +`client.country` fields continue to come from `rawIspInfo`; `client.location` is the +normalized structured view and is preferred for approximate location display. + ## Use a custom backend server list The `librespeed-cli` supports loading custom backend server list from a JSON file (remotely via `--server-json` or locally via `--local-json`). The format is as below: @@ -279,6 +287,10 @@ For `telemetryLevel`, four values are available: Currently, `--telemetry-json` only supports loading a local JSON file. +The telemetry `ispinfo` multipart field preserves `processedString` and `rawIspInfo` and, +when available, adds the normalized approximate `location` object. A third-party telemetry +server may receive that metadata if telemetry is enabled. + ## Bugs? Although we have tested the cli, it's still in its early days. Please open an issue if you encounter any bugs, or even diff --git a/defs/defs.go b/defs/defs.go index 98da5c7..bbad039 100644 --- a/defs/defs.go +++ b/defs/defs.go @@ -2,8 +2,14 @@ package defs import ( "encoding/json" + "math" "net" + "strconv" "strings" + "unicode" + + "golang.org/x/text/language" + "golang.org/x/text/language/display" ) var ( @@ -19,6 +25,615 @@ var ( type GetIPResult struct { ProcessedString string `json:"processedString"` RawISPInfo json.RawMessage `json:"rawIspInfo"` + Location *LocationInfo `json:"location,omitempty"` +} + +// LocationInfo is normalized approximate IP-derived location metadata. +// It is intentionally separate from browser and GPS location. +type LocationInfo struct { + Latitude float64 `json:"latitude,omitempty"` + Longitude float64 `json:"longitude,omitempty"` + City string `json:"city,omitempty"` + Region string `json:"region,omitempty"` + Country string `json:"country,omitempty"` + CountryName string `json:"countryName,omitempty"` + + // LatitudeSet and LongitudeSet distinguish an explicit zero coordinate + // from an omitted coordinate for callers constructing location values + // outside JSON unmarshalling. + LatitudeSet bool `json:"-"` + LongitudeSet bool `json:"-"` + coordinatesPaired bool +} + +var countryIdentityAliases = buildCountryIdentityAliases() + +func buildCountryIdentityAliases() map[string]string { + aliases := make(map[string]string) + + // Build the complete alpha-2 country-code to English-name policy from CLDR. + // This also avoids maintaining a partial hand-written ISO country table. + namer := display.English.Regions() + for _, region := range language.Supported.Regions() { + code := region.String() + if len(code) != 2 { + continue + } + code = strings.ToUpper(code) + normalizedCode := normalizeCountryIdentity(code) + aliases[normalizedCode] = code + + name := strings.TrimSpace(namer.Name(region)) + if name != "" { + aliases[normalizeCountryIdentity(name)] = code + } + } + + // Preserve common English aliases and alpha-3 spellings outside CLDR labels. + for alias, code := range map[string]string{ + "usa": "US", + "us": "US", + "united states": "US", + "united states of america": "US", + "america": "US", + "deu": "DE", + "ger": "DE", + "gbr": "GB", + "uk": "GB", + "great britain": "GB", + "fin": "FI", + } { + aliases[normalizeCountryIdentity(alias)] = code + } + return aliases +} + +// SetLatitude records a valid latitude, including zero. +// Invalid values clear the latitude instead of preserving a misleading value. +func (l *LocationInfo) SetLatitude(latitude float64) { + if l == nil { + return + } + if isValidLatitude(latitude) { + l.Latitude = latitude + l.LatitudeSet = true + return + } + l.Latitude = 0 + l.LatitudeSet = false +} + +// SetLongitude records a valid longitude, including zero. +// Invalid values clear the longitude instead of preserving a misleading value. +func (l *LocationInfo) SetLongitude(longitude float64) { + if l == nil { + return + } + if isValidLongitude(longitude) { + l.Longitude = longitude + l.LongitudeSet = true + return + } + l.Longitude = 0 + l.LongitudeSet = false +} + +// SetCoordinates records both coordinates and marks zero values as present. +func (l *LocationInfo) SetCoordinates(latitude, longitude float64) { + l.SetLatitude(latitude) + l.SetLongitude(longitude) + l.coordinatesPaired = l.ValidLatitude() && l.ValidLongitude() +} + +// UnmarshalJSON accepts numeric strings and numbers for optional coordinates, +// while discarding malformed coordinates instead of failing the whole IP result. +func (l *LocationInfo) UnmarshalJSON(data []byte) error { + *l = LocationInfo{} + trimmed := strings.TrimSpace(string(data)) + if trimmed == "" || trimmed == "null" || trimmed[0] != '{' { + return nil + } + + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil { + return nil + } + + l.City = rawString(fields["city"]) + l.Region = rawString(fields["region"]) + l.Country = rawString(fields["country"]) + l.CountryName = rawString(fields["countryName"]) + if l.CountryName == "" { + l.CountryName = rawString(fields["country_name"]) + } + + if latitude, ok := rawCoordinate(fields["latitude"]); ok && isValidLatitude(latitude) { + l.SetLatitude(latitude) + } + if longitude, ok := rawCoordinate(fields["longitude"]); ok && isValidLongitude(longitude) { + l.SetLongitude(longitude) + } + if !l.ValidLatitude() { + for _, key := range []string{"lat"} { + if latitude, ok := rawCoordinate(fields[key]); ok && isValidLatitude(latitude) { + l.SetLatitude(latitude) + break + } + } + } + if !l.ValidLongitude() { + for _, key := range []string{"lon"} { + if longitude, ok := rawCoordinate(fields[key]); ok && isValidLongitude(longitude) { + l.SetLongitude(longitude) + break + } + } + } + if (!l.ValidLatitude() || !l.ValidLongitude()) && len(fields["loc"]) > 0 { + var locText string + if err := json.Unmarshal(fields["loc"], &locText); err == nil { + parts := strings.Split(locText, ",") + if len(parts) == 2 { + if !l.ValidLatitude() { + if latitude, err := strconv.ParseFloat(strings.TrimSpace(parts[0]), 64); err == nil && + isValidLatitude(latitude) { + l.SetLatitude(latitude) + } + } + if !l.ValidLongitude() { + if longitude, err := strconv.ParseFloat(strings.TrimSpace(parts[1]), 64); err == nil && + isValidLongitude(longitude) { + l.SetLongitude(longitude) + } + } + } + } + } + if l.LatitudeSet && l.LongitudeSet { + l.coordinatesPaired = true + } + + return nil +} + +// MarshalJSON emits only present, valid coordinates and the available text fields. +func (l LocationInfo) MarshalJSON() ([]byte, error) { + wire := struct { + Latitude *float64 `json:"latitude,omitempty"` + Longitude *float64 `json:"longitude,omitempty"` + City string `json:"city,omitempty"` + Region string `json:"region,omitempty"` + Country string `json:"country,omitempty"` + CountryName string `json:"countryName,omitempty"` + }{ + City: CleanLocationText(l.City), + Region: CleanLocationText(l.Region), + Country: CleanLocationText(l.Country), + CountryName: CleanLocationText(l.CountryName), + } + if l.ValidLatitude() { + latitude := l.Latitude + wire.Latitude = &latitude + } + if l.ValidLongitude() { + longitude := l.Longitude + wire.Longitude = &longitude + } + return json.Marshal(wire) +} + +// UnmarshalJSON makes location optional and malformed-safe without affecting +// the legacy processedString or rawIspInfo fields. +func (g *GetIPResult) UnmarshalJSON(data []byte) error { + var wire struct { + ProcessedString string `json:"processedString"` + RawISPInfo json.RawMessage `json:"rawIspInfo"` + Location json.RawMessage `json:"location"` + } + if err := json.Unmarshal(data, &wire); err != nil { + return err + } + + g.ProcessedString = wire.ProcessedString + g.RawISPInfo = wire.RawISPInfo + g.Location = nil + if len(wire.Location) > 0 { + var location LocationInfo + if err := json.Unmarshal(wire.Location, &location); err == nil && location.HasData() { + g.Location = &location + } + } + return nil +} + +// CleanLocationText removes control and invisible formatting characters and +// trims surrounding whitespace so unusable text cannot suppress fallbacks. +func CleanLocationText(value string) string { + value = strings.Map(func(r rune) rune { + if r < 0x20 || (r >= 0x7f && r <= 0x9f) || unicode.Is(unicode.Cf, r) { + return -1 + } + return r + }, value) + return strings.TrimSpace(value) +} + +func rawString(raw json.RawMessage) string { + if len(raw) == 0 { + return "" + } + var value string + if err := json.Unmarshal(raw, &value); err != nil { + return "" + } + return CleanLocationText(value) +} + +func rawCoordinate(raw json.RawMessage) (float64, bool) { + if len(raw) == 0 { + return 0, false + } + trimmed := strings.TrimSpace(string(raw)) + if trimmed == "" || trimmed == "null" { + return 0, false + } + + var number float64 + if err := json.Unmarshal(raw, &number); err == nil { + if math.IsNaN(number) || math.IsInf(number, 0) { + return 0, false + } + return number, true + } + + var text string + if err := json.Unmarshal(raw, &text); err != nil { + return 0, false + } + text = strings.TrimSpace(text) + if text == "" { + return 0, false + } + number, err := strconv.ParseFloat(text, 64) + if err != nil || math.IsNaN(number) || math.IsInf(number, 0) { + return 0, false + } + return number, true +} + +func isValidLatitude(latitude float64) bool { + return latitude >= -90 && latitude <= 90 +} + +func isValidLongitude(longitude float64) bool { + return longitude >= -180 && longitude <= 180 +} + +func normalizeCountryIdentity(value string) string { + value = CleanLocationText(value) + value = strings.ToLower(strings.TrimSpace(value)) + value = strings.NewReplacer(".", "", "_", " ", "-", " ").Replace(value) + return strings.Join(strings.Fields(value), " ") +} + +func canonicalCountryIdentity(value string) string { + normalized := normalizeCountryIdentity(value) + if canonical, ok := countryIdentityAliases[normalized]; ok { + return canonical + } + if len(normalized) == 2 { + return strings.ToUpper(normalized) + } + return normalized +} + +func countryNameIsKnown(value string) bool { + normalized := normalizeCountryIdentity(value) + _, ok := countryIdentityAliases[normalized] + return ok +} + +func countryCodeAndNameConsistent(code, name string) bool { + code = strings.TrimSpace(code) + name = strings.TrimSpace(name) + if code == "" || name == "" { + return true + } + + canonicalCode := canonicalCountryIdentity(code) + canonicalName := canonicalCountryIdentity(name) + if canonicalCode == canonicalName { + return true + } + + // Known country names and codes must agree. Unknown names cannot be + // disproven by an ISO-style code alone, so they remain neutral. + return !countryNameIsKnown(name) +} + +func locationCountryIdentities(location *LocationInfo) ([]string, bool) { + if location == nil { + return nil, true + } + + code := strings.TrimSpace(location.Country) + name := strings.TrimSpace(location.CountryName) + if code == "" && name == "" { + return nil, true + } + if !countryCodeAndNameConsistent(code, name) { + return nil, false + } + + var identities []string + addIdentity := func(identity string) { + if identity == "" { + return + } + for _, existing := range identities { + if existing == identity { + return + } + } + identities = append(identities, identity) + } + if code != "" { + addIdentity(canonicalCountryIdentity(code)) + } + if name != "" { + addIdentity(canonicalCountryIdentity(name)) + } + return identities, true +} + +func countryIdentitiesCompatible(primary, fallback *LocationInfo) bool { + // Explicit country codes are authoritative. Never let a shared name + // override two different nonempty country codes. + primaryCode := "" + fallbackCode := "" + if primary != nil { + primaryCode = strings.TrimSpace(primary.Country) + } + if fallback != nil { + fallbackCode = strings.TrimSpace(fallback.Country) + } + if primaryCode != "" && fallbackCode != "" && + canonicalCountryIdentity(primaryCode) != canonicalCountryIdentity(fallbackCode) { + return false + } + + primaryIdentities, primaryValid := locationCountryIdentities(primary) + fallbackIdentities, fallbackValid := locationCountryIdentities(fallback) + if !primaryValid || !fallbackValid { + return false + } + if len(primaryIdentities) == 0 || len(fallbackIdentities) == 0 { + return true + } + for _, primaryIdentity := range primaryIdentities { + for _, fallbackIdentity := range fallbackIdentities { + if primaryIdentity == fallbackIdentity { + return true + } + } + } + return false +} + +func (l *LocationInfo) hasPairedCoordinates() bool { + if l == nil { + return false + } + if l.coordinatesPaired { + return l.ValidLatitude() && l.ValidLongitude() + } + // Directly constructed LocationInfo values with both nonzero coordinates + // are treated as a pair; callers with one coordinate omit the other. + return l.ValidLatitude() && l.ValidLongitude() +} + +// ValidLatitude reports whether a present latitude is within its geographic range. +func (l *LocationInfo) ValidLatitude() bool { + if l == nil { + return false + } + if l.LatitudeSet { + return isValidLatitude(l.Latitude) + } + return l.Latitude != 0 && isValidLatitude(l.Latitude) +} + +// ValidLongitude reports whether a present longitude is within its geographic range. +func (l *LocationInfo) ValidLongitude() bool { + if l == nil { + return false + } + if l.LongitudeSet { + return isValidLongitude(l.Longitude) + } + return l.Longitude != 0 && isValidLongitude(l.Longitude) +} + +// ValidCoordinates reports whether both coordinates are present and valid. +func (l *LocationInfo) ValidCoordinates() bool { + return l != nil && l.ValidLatitude() && l.ValidLongitude() +} + +// HasData reports whether the location contains displayable text or coordinates. +func (l *LocationInfo) HasData() bool { + if l == nil { + return false + } + return CleanLocationText(l.City) != "" || CleanLocationText(l.Region) != "" || + CleanLocationText(l.Country) != "" || CleanLocationText(l.CountryName) != "" || + l.ValidLatitude() || l.ValidLongitude() +} + +// LocationFromRawISPInfo derives approximate location metadata from legacy +// rawIspInfo payloads. It does not alter RawISPInfo. +func LocationFromRawISPInfo(raw json.RawMessage) *LocationInfo { + if len(raw) == 0 { + return nil + } + + var fields map[string]json.RawMessage + if err := json.Unmarshal(raw, &fields); err != nil { + return nil + } + + location := &LocationInfo{ + City: rawString(fields["city"]), + Region: rawString(fields["region"]), + Country: rawString(fields["country"]), + CountryName: rawString(fields["countryName"]), + } + if location.CountryName == "" { + location.CountryName = rawString(fields["country_name"]) + } + + if loc, ok := fields["loc"]; ok { + var locText string + if err := json.Unmarshal(loc, &locText); err == nil { + parts := strings.Split(locText, ",") + if len(parts) == 2 { + if latitude, err := strconv.ParseFloat(strings.TrimSpace(parts[0]), 64); err == nil && + isValidLatitude(latitude) { + location.SetLatitude(latitude) + } + if longitude, err := strconv.ParseFloat(strings.TrimSpace(parts[1]), 64); err == nil && + isValidLongitude(longitude) { + location.SetLongitude(longitude) + } + if location.ValidLatitude() && location.ValidLongitude() { + location.coordinatesPaired = true + } + } + } + } + + for _, key := range []string{"latitude", "lat"} { + if latitude, ok := rawCoordinate(fields[key]); ok && isValidLatitude(latitude) { + location.SetLatitude(latitude) + break + } + } + for _, key := range []string{"longitude", "lon"} { + if longitude, ok := rawCoordinate(fields[key]); ok && isValidLongitude(longitude) { + location.SetLongitude(longitude) + break + } + } + if location.ValidLatitude() && location.ValidLongitude() { + location.coordinatesPaired = true + } + + if nested, ok := fields["location"]; ok { + var nestedLocation LocationInfo + if err := json.Unmarshal(nested, &nestedLocation); err == nil { + location = MergeLocations(&nestedLocation, location) + } + } + + if !location.HasData() { + return nil + } + return location +} + +// MergeLocations combines primary structured data with legacy fallback data. +// Primary fields take precedence and fallback fills only missing fields. +// Geographic fallback fields are skipped when both country codes are present +// and disagree. +func MergeLocations(primary, fallback *LocationInfo) *LocationInfo { + if primary == nil && fallback == nil { + return nil + } + var merged LocationInfo + if primary != nil { + merged = *primary + } + merged.City = CleanLocationText(merged.City) + merged.Region = CleanLocationText(merged.Region) + merged.Country = CleanLocationText(merged.Country) + merged.CountryName = CleanLocationText(merged.CountryName) + if fallback != nil { + fallbackCopy := *fallback + fallbackCopy.City = CleanLocationText(fallbackCopy.City) + fallbackCopy.Region = CleanLocationText(fallbackCopy.Region) + fallbackCopy.Country = CleanLocationText(fallbackCopy.Country) + fallbackCopy.CountryName = CleanLocationText(fallbackCopy.CountryName) + compatibleFallback := countryIdentitiesCompatible(&merged, &fallbackCopy) + + // A place-only primary (city/region with no country identity) must not + // absorb fallback geography that carries a different country identity. + primaryPlaceOnly := merged.Country == "" && merged.CountryName == "" && + (merged.City != "" || merged.Region != "") + if primaryPlaceOnly { + fallbackIdentities, fallbackValid := locationCountryIdentities(&fallbackCopy) + if !fallbackValid || len(fallbackIdentities) > 0 { + compatibleFallback = false + } + } + + if !compatibleFallback { + if !merged.HasData() { + return nil + } + return &merged + } + + if merged.Country == "" { + merged.Country = fallbackCopy.Country + } + + if merged.City == "" { + merged.City = fallbackCopy.City + } + if merged.Region == "" { + merged.Region = fallbackCopy.Region + } + if merged.CountryName == "" && fallbackCopy.CountryName != "" { + merged.CountryName = fallbackCopy.CountryName + } + + primaryHasLatitude := merged.ValidLatitude() + primaryHasLongitude := merged.ValidLongitude() + fallbackHasLatitude := fallbackCopy.ValidLatitude() + fallbackHasLongitude := fallbackCopy.ValidLongitude() + fallbackPaired := fallbackCopy.hasPairedCoordinates() + + if !primaryHasLatitude && !primaryHasLongitude { + if fallbackPaired { + merged.SetCoordinates(fallbackCopy.Latitude, fallbackCopy.Longitude) + } else { + if fallbackHasLatitude { + merged.SetLatitude(fallbackCopy.Latitude) + } + if fallbackHasLongitude { + merged.SetLongitude(fallbackCopy.Longitude) + } + } + } else if primaryHasLatitude && !primaryHasLongitude && + fallbackPaired { + merged.SetLongitude(fallbackCopy.Longitude) + } else if !primaryHasLatitude && primaryHasLongitude && + fallbackPaired { + merged.SetLatitude(fallbackCopy.Latitude) + } + } + if !merged.HasData() { + return nil + } + return &merged +} + +// EffectiveLocation returns top-level location metadata merged with compatible +// legacy rawIspInfo fields for any values that remain missing. +func (g *GetIPResult) EffectiveLocation() *LocationInfo { + if g == nil { + return nil + } + return MergeLocations(g.Location, LocationFromRawISPInfo(g.RawISPInfo)) } // IPInfoResponse represents the returned JSON from IPInfo.io's API diff --git a/defs/defs_test.go b/defs/defs_test.go index d918d9f..1130360 100644 --- a/defs/defs_test.go +++ b/defs/defs_test.go @@ -1,6 +1,10 @@ package defs -import "testing" +import ( + "encoding/json" + "strings" + "testing" +) // The address falls back to processedString whenever rawIspInfo carries none: // live backends answer with an empty string, a JSON null, or -- with the @@ -39,3 +43,532 @@ func TestIPPrefersRawOverProcessedString(t *testing.T) { t.Errorf("IP() = %q, want %q", got, "192.0.2.1") } } + +func TestLocationFromStructuredAndLegacyMetadata(t *testing.T) { + payload := []byte(`{ + "processedString":"128.94.2.134 - AS8075", + "rawIspInfo":{"ip":"128.94.2.134","city":"Old City","region":"Old Region","country":"US","loc":"36.6676,-78.3875","org":"Microsoft"}, + "location":{"city":"Boydton","region":"Virginia","country":"US","countryName":"United States","latitude":"36.6676","longitude":"-78.3875"} + }`) + + var got GetIPResult + if err := json.Unmarshal(payload, &got); err != nil { + t.Fatalf("Unmarshal: %v", err) + } + if got.ProcessedString != "128.94.2.134 - AS8075" { + t.Errorf("ProcessedString = %q", got.ProcessedString) + } + if got.IP() != "128.94.2.134" { + t.Errorf("IP() = %q, want 128.94.2.134", got.IP()) + } + + location := got.EffectiveLocation() + if location == nil { + t.Fatal("EffectiveLocation returned nil") + } + if location.City != "Boydton" || location.Region != "Virginia" || + location.Country != "US" || location.CountryName != "United States" { + t.Errorf("location text = %#v", location) + } + if !location.ValidCoordinates() || location.Latitude != 36.6676 || location.Longitude != -78.3875 { + t.Errorf("coordinates = (%v, %v), valid=%t", location.Latitude, location.Longitude, location.ValidCoordinates()) + } +} + +func TestMalformedAndMissingLocationDoNotBreakGetIPResult(t *testing.T) { + cases := []struct { + name string + location string + }{ + {"malformed object", `{"city":"Example","latitude":"not-a-number","longitude":181}`}, + {"string", `"Example"`}, + {"missing", ``}, + {"null", `null`}, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + payload := `{"processedString":"192.0.2.1 - Example ISP","rawIspInfo":""` + if c.location != "" { + payload += `,"location":` + c.location + } + payload += `}` + + var got GetIPResult + if err := json.Unmarshal([]byte(payload), &got); err != nil { + t.Fatalf("Unmarshal: %v", err) + } + if got.ProcessedString != "192.0.2.1 - Example ISP" { + t.Errorf("ProcessedString = %q", got.ProcessedString) + } + if got.IP() != "192.0.2.1" { + t.Errorf("IP() = %q, want 192.0.2.1", got.IP()) + } + if c.location == `{"city":"Example","latitude":"not-a-number","longitude":181}` { + if got.Location == nil || got.Location.City != "Example" { + t.Errorf("text location was lost: %#v", got.Location) + } + if got.Location.ValidCoordinates() { + t.Errorf("malformed coordinates accepted: %#v", got.Location) + } + } + }) + } +} + +func TestLocationFromLegacyRawIspInfo(t *testing.T) { + location := LocationFromRawISPInfo(json.RawMessage(`{ + "ip":"128.94.2.134", + "city":"Boydton", + "region":"Virginia", + "country":"US", + "loc":"36.6676,-78.3875", + "org":"Microsoft" + }`)) + if location == nil { + t.Fatal("legacy location returned nil") + } + if location.City != "Boydton" || location.Region != "Virginia" || location.Country != "US" { + t.Errorf("legacy text = %#v", location) + } + if !location.ValidCoordinates() || location.Latitude != 36.6676 || location.Longitude != -78.3875 { + t.Errorf("legacy coordinates = (%v, %v)", location.Latitude, location.Longitude) + } +} + +func TestWhitespaceAndInvisibleLocationFallsBackToLegacy(t *testing.T) { + var got GetIPResult + payload := []byte(`{ + "processedString":"128.94.2.134 - AS8075", + "rawIspInfo":{"ip":"128.94.2.134","city":"Boydton","region":"Virginia","country":"US","countryName":"United States","loc":"36.6676,-78.3875","org":"Microsoft"}, + "location":{"city":" ","region":"\u200b","country":"\t","countryName":"\n"} + }`) + if err := json.Unmarshal(payload, &got); err != nil { + t.Fatalf("Unmarshal: %v", err) + } + + location := got.EffectiveLocation() + if location == nil { + t.Fatal("EffectiveLocation returned nil") + } + if location.City != "Boydton" || location.Region != "Virginia" || + location.Country != "US" || location.CountryName != "United States" { + t.Errorf("whitespace location did not fall back: %#v", location) + } + if !location.ValidCoordinates() || location.Latitude != 36.6676 || location.Longitude != -78.3875 { + t.Errorf("whitespace location lost coordinates: %#v", location) + } +} + +func TestFiniteCoordinateFallbacksRejectInvalidPrimaryValues(t *testing.T) { + var got GetIPResult + payload := []byte(`{ + "processedString":"128.94.2.134 - AS8075", + "rawIspInfo":{"ip":"128.94.2.134","loc":"36.6676,-78.3875","org":"Microsoft"}, + "location":{"city":"Example City","latitude":91,"longitude":"Infinity","lat":38.1234,"lon":-77.1234} + }`) + if err := json.Unmarshal(payload, &got); err != nil { + t.Fatalf("Unmarshal: %v", err) + } + + location := got.EffectiveLocation() + if location == nil { + t.Fatal("EffectiveLocation returned nil") + } + if location.City != "Example City" { + t.Errorf("place metadata lost: %#v", location) + } + if !location.ValidCoordinates() || location.Latitude != 38.1234 || location.Longitude != -77.1234 { + t.Errorf("finite fallback coordinates not used: %#v", location) + } +} + +func TestLocationMarshalPreservesRawAndLegacyFields(t *testing.T) { + got := GetIPResult{ + ProcessedString: "128.94.2.134 - AS8075", + RawISPInfo: json.RawMessage(`{"ip":"128.94.2.134","city":"Boydton","org":"Microsoft"}`), + Location: &LocationInfo{ + City: "Boydton", + Country: "US", + CountryName: "United States", + Latitude: 36.6676, + Longitude: -78.3875, + }, + } + + b, err := json.Marshal(got) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + text := string(b) + for _, want := range []string{`"processedString":"128.94.2.134 - AS8075"`, `"rawIspInfo":{"ip":"128.94.2.134","city":"Boydton","org":"Microsoft"}`, `"location":{"latitude":36.6676,"longitude":-78.3875,"city":"Boydton","country":"US","countryName":"United States"}`} { + if !strings.Contains(text, want) { + t.Errorf("marshal lacks %s: %s", want, text) + } + } +} + +func TestLocationCoordinatesCanPreserveExplicitZero(t *testing.T) { + location := &LocationInfo{} + location.SetCoordinates(0, 10) + + if !location.ValidLatitude() || location.Latitude != 0 || !location.LatitudeSet { + t.Errorf("explicit latitude zero not preserved: %#v", location) + } + if !location.ValidLongitude() || location.Longitude != 10 || !location.LongitudeSet { + t.Errorf("longitude not preserved: %#v", location) + } + + b, err := json.Marshal(location) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + if got, want := string(b), `{"latitude":0,"longitude":10}`; got != want { + t.Errorf("Marshal(location) = %s, want %s", got, want) + } +} + +func TestLocationLongitudeAloneDoesNotInferLatitude(t *testing.T) { + location := &LocationInfo{Longitude: 10} + + if location.ValidLatitude() || location.LatitudeSet { + t.Errorf("omitted latitude inferred as present: %#v", location) + } + location.SetLatitude(91) + if location.ValidLatitude() || location.LatitudeSet { + t.Errorf("invalid latitude remained present after SetLatitude: %#v", location) + } + + b, err := json.Marshal(location) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + if got, want := string(b), `{"longitude":10}`; got != want { + t.Errorf("Marshal(location) = %s, want %s", got, want) + } +} + +func TestLocationJSONPreservesExplicitZeroCoordinates(t *testing.T) { + var got GetIPResult + if err := json.Unmarshal([]byte(`{"processedString":"192.0.2.1","rawIspInfo":"","location":{"latitude":0,"longitude":10}}`), &got); err != nil { + t.Fatalf("Unmarshal: %v", err) + } + if got.Location == nil || !got.Location.ValidLatitude() || got.Location.Latitude != 0 || + !got.Location.LatitudeSet { + t.Errorf("decoded zero latitude not preserved: %#v", got.Location) + } + if got.Location == nil || !got.Location.ValidLongitude() || got.Location.Longitude != 10 || + !got.Location.LongitudeSet { + t.Errorf("decoded longitude not preserved: %#v", got.Location) + } +} + +func TestMergeLocationsDoesNotReplaceExplicitZeroCoordinate(t *testing.T) { + primary := &LocationInfo{} + primary.SetCoordinates(0, 10) + fallback := LocationFromRawISPInfo(json.RawMessage(`{"latitude":36.6676,"longitude":-78.3875}`)) + + merged := MergeLocations(primary, fallback) + if merged == nil { + t.Fatal("merged location returned nil") + } + if !merged.ValidLatitude() || merged.Latitude != 0 { + t.Errorf("explicit zero latitude replaced: %#v", merged) + } + if !merged.ValidLongitude() || merged.Longitude != 10 { + t.Errorf("primary longitude replaced: %#v", merged) + } +} + +func TestMergeLocationsFillsOmittedLatitude(t *testing.T) { + primary := &LocationInfo{Longitude: 10} + fallback := &LocationInfo{Latitude: 36.6676, Longitude: -78.3875} + + merged := MergeLocations(primary, fallback) + if merged == nil { + t.Fatal("merged location returned nil") + } + if !merged.ValidLatitude() || merged.Latitude != 36.6676 { + t.Errorf("omitted latitude not filled: %#v", merged) + } + if !merged.ValidLongitude() || merged.Longitude != 10 { + t.Errorf("primary longitude not preserved: %#v", merged) + } +} + +func TestMergeLocationsDoesNotCopyCountryNameForDifferentCountry(t *testing.T) { + primary := &LocationInfo{City: "Berlin", Country: "DE"} + fallback := &LocationInfo{ + City: "Boydton", + Region: "Virginia", + Country: "US", + CountryName: "United States", + Latitude: 36.6676, + Longitude: -78.3875, + } + + merged := MergeLocations(primary, fallback) + if merged == nil { + t.Fatal("merged location returned nil") + } + if merged.Country != "DE" { + t.Errorf("merged country = %q, want DE", merged.Country) + } + if merged.CountryName != "" { + t.Errorf("fallback country name crossed countries: %#v", merged) + } + if merged.City != "Berlin" || merged.Region != "" { + t.Errorf("fallback place crossed countries: %#v", merged) + } + if merged.ValidCoordinates() { + t.Errorf("fallback coordinates crossed countries: %#v", merged) + } +} + +func TestMergeLocationsCopiesMatchingCountryName(t *testing.T) { + primary := &LocationInfo{Country: "DE"} + fallback := &LocationInfo{Country: "de", CountryName: "Germany"} + + merged := MergeLocations(primary, fallback) + if merged == nil { + t.Fatal("merged location returned nil") + } + if merged.CountryName != "Germany" { + t.Errorf("matching country name not copied: %#v", merged) + } +} + +func TestMergeLocationsRejectsDifferentExplicitCodesWithSharedName(t *testing.T) { + primary := &LocationInfo{ + City: "Berlin", + Country: "DE", + CountryName: "Deutschland", + } + fallback := &LocationInfo{ + City: "Boydton", + Region: "Virginia", + Country: "US", + CountryName: "Deutschland", + Latitude: 36.6676, + Longitude: -78.3875, + } + + merged := MergeLocations(primary, fallback) + if merged == nil { + t.Fatal("merged location returned nil") + } + if merged.Country != "DE" || merged.CountryName != "Deutschland" { + t.Errorf("primary country identity changed: %#v", merged) + } + if merged.City != "Berlin" || merged.Region != "" { + t.Errorf("fallback place crossed differing explicit codes: %#v", merged) + } + if merged.ValidCoordinates() { + t.Errorf("fallback coordinates crossed differing explicit codes: %#v", merged) + } +} + +func TestMergeLocationsFinlandNameAndCodeAreEquivalent(t *testing.T) { + primary := &LocationInfo{CountryName: "Finland"} + fallback := &LocationInfo{ + City: "Helsinki", + Region: "Uusimaa", + Country: "FI", + Latitude: 60.1699, + Longitude: 24.9384, + } + + merged := MergeLocations(primary, fallback) + if merged == nil { + t.Fatal("merged location returned nil") + } + if merged.Country != "FI" { + t.Errorf("compatible Finland country code not copied: %#v", merged) + } + if merged.CountryName != "Finland" { + t.Errorf("primary Finland country name changed: %#v", merged) + } + if merged.City != "Helsinki" || merged.Region != "Uusimaa" { + t.Errorf("compatible Finland place not merged: %#v", merged) + } + if !merged.ValidCoordinates() || merged.Latitude != 60.1699 || merged.Longitude != 24.9384 { + t.Errorf("compatible Finland coordinates not merged: %#v", merged) + } +} + +func TestMergeLocationsCountryNameOnlyRejectsConflictingFallback(t *testing.T) { + primary := &LocationInfo{ + City: "Washington", + Region: "District of Columbia", + CountryName: "United States", + } + fallback := &LocationInfo{ + City: "Berlin", + Region: "Berlin", + Country: "DE", + CountryName: "Germany", + Latitude: 52.52, + Longitude: 13.405, + } + + merged := MergeLocations(primary, fallback) + if merged == nil { + t.Fatal("merged location returned nil") + } + if merged.Country != "" { + t.Errorf("fallback country code crossed country-name-only primary: %#v", merged) + } + if merged.CountryName != "United States" { + t.Errorf("primary country name changed: %#v", merged) + } + if merged.City != "Washington" || merged.Region != "District of Columbia" { + t.Errorf("fallback place crossed country-name-only primary: %#v", merged) + } + if merged.ValidCoordinates() { + t.Errorf("fallback coordinates crossed country-name-only primary: %#v", merged) + } +} + +func TestMergeLocationsCountryNameOnlyAcceptsCompatibleFallback(t *testing.T) { + primary := &LocationInfo{ + City: "Washington", + Region: "District of Columbia", + CountryName: "United States", + } + fallback := &LocationInfo{ + City: "Boydton", + Region: "Virginia", + Country: "US", + CountryName: "United States", + Latitude: 36.6676, + Longitude: -78.3875, + } + + merged := MergeLocations(primary, fallback) + if merged == nil { + t.Fatal("merged location returned nil") + } + if merged.Country != "US" { + t.Errorf("compatible fallback country code not copied: %#v", merged) + } + if merged.CountryName != "United States" { + t.Errorf("compatible primary country name changed: %#v", merged) + } + if merged.City != "Washington" || merged.Region != "District of Columbia" { + t.Errorf("compatible merge replaced primary place: %#v", merged) + } + if !merged.ValidCoordinates() || merged.Latitude != 36.6676 || merged.Longitude != -78.3875 { + t.Errorf("compatible fallback coordinates not merged: %#v", merged) + } +} + +func TestMergeLocationsCountryNameOnlyAcceptsAbsentFallbackIdentity(t *testing.T) { + primary := &LocationInfo{ + City: "Washington", + CountryName: "United States", + } + fallback := &LocationInfo{ + City: "Boston", + Region: "Massachusetts", + Latitude: 42.3601, + Longitude: -71.0589, + } + + merged := MergeLocations(primary, fallback) + if merged == nil { + t.Fatal("merged location returned nil") + } + if merged.Country != "" || merged.CountryName != "United States" { + t.Errorf("fallback identity changed primary country identity: %#v", merged) + } + if merged.City != "Washington" || merged.Region != "Massachusetts" { + t.Errorf("fallback place/region merge unexpected: %#v", merged) + } + if !merged.ValidCoordinates() || merged.Latitude != 42.3601 || merged.Longitude != -71.0589 { + t.Errorf("identity-absent fallback coordinates not merged: %#v", merged) + } +} + +func TestMergeLocationsPlaceOnlyRejectsCountryIdentityFallback(t *testing.T) { + primary := &LocationInfo{City: "Berlin"} + fallback := &LocationInfo{ + City: "Boydton", + Region: "Virginia", + Country: "US", + CountryName: "United States", + Latitude: 36.6676, + Longitude: -78.3875, + } + + merged := MergeLocations(primary, fallback) + if merged == nil { + t.Fatal("merged location returned nil") + } + if merged.Country != "" || merged.CountryName != "" { + t.Errorf("fallback country identity crossed place-only primary: %#v", merged) + } + if merged.City != "Berlin" || merged.Region != "" { + t.Errorf("fallback place crossed place-only primary: %#v", merged) + } + if merged.ValidCoordinates() { + t.Errorf("fallback coordinates crossed place-only primary: %#v", merged) + } +} + +func TestMergeLocationsCountryNameOnlyRejectsInconsistentFallback(t *testing.T) { + primary := &LocationInfo{CountryName: "United States"} + fallback := &LocationInfo{ + City: "Boydton", + Region: "Virginia", + Country: "US", + CountryName: "Germany", + Latitude: 36.6676, + Longitude: -78.3875, + } + + merged := MergeLocations(primary, fallback) + if merged == nil { + t.Fatal("merged location returned nil") + } + if merged.Country != "" || merged.City != "" || merged.Region != "" || + merged.ValidCoordinates() { + t.Errorf("inconsistent fallback geography copied: %#v", merged) + } + if merged.CountryName != "United States" { + t.Errorf("primary country name changed: %#v", merged) + } +} + +func TestMergeLocationsDoesNotMixUnpairedCoordinates(t *testing.T) { + t.Run("primary latitude only", func(t *testing.T) { + primary := &LocationInfo{Latitude: 36.6676} + fallback := &LocationInfo{Longitude: -78.3875} + + merged := MergeLocations(primary, fallback) + if merged == nil { + t.Fatal("merged location returned nil") + } + if !merged.ValidLatitude() || merged.Latitude != 36.6676 { + t.Errorf("primary latitude changed: %#v", merged) + } + if merged.ValidLongitude() { + t.Errorf("unpaired fallback longitude was mixed into primary: %#v", merged) + } + }) + + t.Run("primary longitude only", func(t *testing.T) { + primary := &LocationInfo{Longitude: -78.3875} + fallback := &LocationInfo{Latitude: 36.6676} + + merged := MergeLocations(primary, fallback) + if merged == nil { + t.Fatal("merged location returned nil") + } + if merged.ValidLatitude() { + t.Errorf("unpaired fallback latitude was mixed into primary: %#v", merged) + } + if !merged.ValidLongitude() || merged.Longitude != -78.3875 { + t.Errorf("primary longitude changed: %#v", merged) + } + }) +} diff --git a/defs/server.go b/defs/server.go index 40dc958..49fcff0 100644 --- a/defs/server.go +++ b/defs/server.go @@ -783,6 +783,7 @@ func (s *Server) GetIPInfo(distanceUnit string) (*GetIPResult, error) { var partial struct { ProcessedString string `json:"processedString"` RawISPInfo json.RawMessage `json:"rawIspInfo"` + Location json.RawMessage `json:"location"` } if err2 := json.Unmarshal(b, &partial); err2 == nil { if partial.ProcessedString != "" { @@ -791,6 +792,12 @@ func (s *Server) GetIPInfo(distanceUnit string) (*GetIPResult, error) { ipInfo.ProcessedString = string(b) } ipInfo.RawISPInfo = partial.RawISPInfo + if len(partial.Location) > 0 { + var location LocationInfo + if err := json.Unmarshal(partial.Location, &location); err == nil && location.HasData() { + ipInfo.Location = &location + } + } } else { ipInfo.ProcessedString = string(b) } diff --git a/defs/server_test.go b/defs/server_test.go index 90ffcf9..28689f7 100644 --- a/defs/server_test.go +++ b/defs/server_test.go @@ -90,6 +90,67 @@ func TestGetIPInfoAbsentRawIspInfo(t *testing.T) { } } +func TestGetIPInfoParsesStructuredLocation(t *testing.T) { + got := getIPResultFromPayload(t, `{ + "processedString":"128.94.2.134 - AS8075", + "rawIspInfo":{"ip":"128.94.2.134","org":"Microsoft"}, + "location":{"city":"Boydton","region":"Virginia","country":"US","countryName":"United States","latitude":"36.6676","longitude":"-78.3875"} + }`) + + location := got.Location + if location == nil { + t.Fatal("Location returned nil") + } + if location.City != "Boydton" || location.Region != "Virginia" || + location.Country != "US" || location.CountryName != "United States" { + t.Errorf("Location = %#v", location) + } + if !location.ValidCoordinates() || location.Latitude != 36.6676 || location.Longitude != -78.3875 { + t.Errorf("coordinates = (%v, %v), valid=%t", location.Latitude, location.Longitude, location.ValidCoordinates()) + } +} + +func TestGetIPInfoMalformedLocationIsNonFatal(t *testing.T) { + got := getIPResultFromPayload(t, `{ + "processedString":"192.0.2.1 - Example ISP", + "rawIspInfo":{"ip":"192.0.2.1","org":"Example"}, + "location":{"city":"Example City","latitude":"bad","longitude":181} + }`) + + if got.ProcessedString != "192.0.2.1 - Example ISP" { + t.Errorf("ProcessedString = %q", got.ProcessedString) + } + if got.IP() != "192.0.2.1" { + t.Errorf("IP() = %q, want 192.0.2.1", got.IP()) + } + if got.Location == nil || got.Location.City != "Example City" { + t.Errorf("valid location text was lost: %#v", got.Location) + } + if got.Location.ValidCoordinates() { + t.Errorf("malformed coordinates accepted: %#v", got.Location) + } +} + +func TestGetIPInfoCountryOnlyLocationKeepsPartialPlace(t *testing.T) { + got := getIPResultFromPayload(t, `{ + "processedString":"128.94.2.134 - AS8075", + "rawIspInfo":{"ip":"128.94.2.134","city":"Boydton","region":"Virginia","country":"US","loc":"36.6676,-78.3875","org":"Microsoft"}, + "location":{"country":"US","countryName":"United States"} + }`) + + location := got.EffectiveLocation() + if location == nil { + t.Fatal("EffectiveLocation returned nil") + } + if location.City != "Boydton" || location.Region != "Virginia" || + location.Country != "US" || location.CountryName != "United States" { + t.Errorf("country-only location lost partial place: %#v", location) + } + if !location.ValidCoordinates() || location.Latitude != 36.6676 || location.Longitude != -78.3875 { + t.Errorf("country-only location lost coordinates: %#v", location) + } +} + // --- Upload against a server with librespeed-rs body semantics --- // librespeedRSLikeServer mimics the hand-written HTTP body handling of diff --git a/go.mod b/go.mod index 7c622ca..e3f2773 100644 --- a/go.mod +++ b/go.mod @@ -9,6 +9,7 @@ require ( github.com/quic-go/quic-go v0.65.0 github.com/urfave/cli/v2 v2.27.7 golang.org/x/sys v0.50.0 + golang.org/x/text v0.44.0 ) require ( @@ -24,5 +25,4 @@ require ( golang.org/x/net v0.62.0 // indirect golang.org/x/sync v0.25.0 // indirect golang.org/x/term v0.48.0 // indirect - golang.org/x/text v0.44.0 // indirect ) diff --git a/main_test.go b/main_test.go index e5220d1..67eae97 100644 --- a/main_test.go +++ b/main_test.go @@ -110,6 +110,96 @@ func mockBackend(t *testing.T) *httptest.Server { return srv } +func TestLocationJSONAndJSONStreamParity(t *testing.T) { + payload := `{"processedString":"128.94.2.134 - AS8075","rawIspInfo":{"ip":"128.94.2.134","city":"Old City","region":"Old Region","country":"US","loc":"36.6676,-78.3875","org":"Microsoft"},"location":{"city":"Boydton","region":"Virginia","country":"US","countryName":"United States","latitude":"36.6676","longitude":"-78.3875"}}` + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/getIP.php": + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(payload)) + case "/empty.php": + default: + w.Header().Set("Content-Type", "text/plain") + } + })) + t.Cleanup(backend.Close) + + list := writeServerList(t, listedServer{1, "Location", backend.URL, "empty.php"}) + args := []string{"--local-json", list, "--server", "1", "--duration", "1", "--no-icmp", "--no-download", "--no-upload"} + + jsonRun := runCLI(t, append(append([]string{}, args...), "--json")...) + if jsonRun.code != 0 { + t.Fatalf("JSON run failed: %s", jsonRun.stderr) + } + streamRun := runCLI(t, append(append([]string{}, args...), "--json-stream")...) + if streamRun.code != 0 { + t.Fatalf("JSON-stream run failed: %s", streamRun.stderr) + } + + type locationReport struct { + Client struct { + Location *struct { + City string `json:"city"` + Region string `json:"region"` + Country string `json:"country"` + CountryName string `json:"countryName"` + Latitude float64 `json:"latitude"` + Longitude float64 `json:"longitude"` + } `json:"location"` + } `json:"client"` + } + + var jsonReports []locationReport + if err := json.Unmarshal([]byte(jsonRun.stdout), &jsonReports); err != nil { + t.Fatalf("JSON stdout is invalid: %v\n%s", err, jsonRun.stdout) + } + if len(jsonReports) != 1 || jsonReports[0].Client.Location == nil { + t.Fatalf("JSON location missing: %s", jsonRun.stdout) + } + + var streamLocation *struct { + City string `json:"city"` + Region string `json:"region"` + Country string `json:"country"` + CountryName string `json:"countryName"` + Latitude float64 `json:"latitude"` + Longitude float64 `json:"longitude"` + } + for _, line := range strings.Split(strings.TrimSpace(streamRun.stdout), "\n") { + if line == "" { + continue + } + var event struct { + Event string `json:"event"` + Reports []locationReport `json:"reports"` + } + if err := json.Unmarshal([]byte(line), &event); err != nil { + t.Fatalf("JSON-stream line is invalid: %v\n%s", err, line) + } + if event.Event == "result" && len(event.Reports) == 1 { + streamLocation = event.Reports[0].Client.Location + } + } + if streamLocation == nil { + t.Fatalf("JSON-stream location missing: %s", streamRun.stdout) + } + + jsonLocation := jsonReports[0].Client.Location + if jsonLocation.City != "Boydton" || jsonLocation.Region != "Virginia" || + jsonLocation.Country != "US" || jsonLocation.CountryName != "United States" || + jsonLocation.Latitude != 36.6676 || jsonLocation.Longitude != -78.3875 { + t.Errorf("unexpected JSON location: %#v", jsonLocation) + } + if jsonLocation.City != streamLocation.City || + jsonLocation.Region != streamLocation.Region || + jsonLocation.Country != streamLocation.Country || + jsonLocation.CountryName != streamLocation.CountryName || + jsonLocation.Latitude != streamLocation.Latitude || + jsonLocation.Longitude != streamLocation.Longitude { + t.Errorf("JSON and JSON-stream locations differ: JSON=%#v stream=%#v", jsonLocation, streamLocation) + } +} + // deadURL is a server URL nothing listens on. func deadURL(t *testing.T) string { t.Helper() diff --git a/report/csv.go b/report/csv.go index 946a275..feca25b 100644 --- a/report/csv.go +++ b/report/csv.go @@ -15,4 +15,11 @@ type CSVReport struct { Upload float64 `csv:"Upload"` Share string `csv:"Share"` IP string `csv:"IP"` + // Location columns are appended after IP to preserve existing CSV positions. + City string `csv:"City"` + Region string `csv:"Region"` + Country string `csv:"Country"` + CountryName string `csv:"Country Name"` + Latitude string `csv:"Latitude"` + Longitude string `csv:"Longitude"` } diff --git a/report/csv_test.go b/report/csv_test.go new file mode 100644 index 0000000..62b7f19 --- /dev/null +++ b/report/csv_test.go @@ -0,0 +1,35 @@ +package report + +import ( + "strings" + "testing" + + "github.com/gocarina/gocsv" +) + +func TestCSVLocationHeadersAndValues(t *testing.T) { + reports := []CSVReport{{ + City: "Boydton", + Region: "Virginia", + Country: "US", + CountryName: "United States", + Latitude: "36.6676", + Longitude: "-78.3875", + }} + + b, err := gocsv.MarshalBytes(&reports) + if err != nil { + t.Fatalf("MarshalBytes: %v", err) + } + csvText := string(b) + for _, header := range []string{"City", "Region", "Country", "Country Name", "Latitude", "Longitude"} { + if !strings.Contains(csvText, header) { + t.Errorf("CSV output lacks %q: %s", header, csvText) + } + } + for _, value := range []string{"Boydton", "Virginia", "US", "United States", "36.6676", "-78.3875"} { + if !strings.Contains(csvText, value) { + t.Errorf("CSV output lacks %q: %s", value, csvText) + } + } +} diff --git a/report/json.go b/report/json.go index 4b8d418..0ce8ffe 100644 --- a/report/json.go +++ b/report/json.go @@ -45,12 +45,29 @@ type Server struct { // Client represents the speed test client's information type Client struct { defs.IPInfoResponse + // Location is normalized approximate IP-derived metadata. It is separate + // from the legacy embedded IPInfoResponse.Location (the "loc" field). + Location *defs.LocationInfo `json:"location,omitempty"` } // NewClient builds a Client from the raw ISP info payload a backend returned. // The payload may be an object, an empty string, or absent; anything that does // not parse as an object yields an empty Client rather than an error. -func NewClient(raw json.RawMessage) Client { +func NewClient(raw json.RawMessage, structuredLocations ...*defs.LocationInfo) Client { + if len(structuredLocations) > 1 { + // A structured location argument is optional and singular. Reject extra + // arguments without applying the silently selected first value. + return NewClientWithLocation(raw, nil) + } + if len(structuredLocations) == 1 { + return NewClientWithLocation(raw, structuredLocations[0]) + } + return NewClientWithLocation(raw, nil) +} + +// NewClientWithLocation is the explicit form of NewClient for structured +// location metadata. Legacy rawIspInfo location fields remain a fallback. +func NewClientWithLocation(raw json.RawMessage, structuredLocation *defs.LocationInfo) Client { var data struct { defs.IPInfoResponse ASName string `json:"as_name"` @@ -61,11 +78,18 @@ func NewClient(raw json.RawMessage) Client { } c := Client{IPInfoResponse: data.IPInfoResponse} + c.City = defs.CleanLocationText(c.City) + c.Region = defs.CleanLocationText(c.Region) + c.Country = defs.CleanLocationText(c.Country) // Current backends use as_name, while older ones use org. if c.Organization == "" { c.Organization = data.ASName } + location := defs.LocationFromRawISPInfo(raw) + location = defs.MergeLocations(structuredLocation, location) + c.Location = location + return c } diff --git a/report/json_test.go b/report/json_test.go index 2bc90ed..5646796 100644 --- a/report/json_test.go +++ b/report/json_test.go @@ -4,6 +4,8 @@ import ( "encoding/json" "strings" "testing" + + "github.com/librespeed/speedtest-cli/defs" ) func TestNewClientOrganisation(t *testing.T) { @@ -42,3 +44,63 @@ func TestClientJSONDoesNotLeakASName(t *testing.T) { t.Errorf("org not filled from as_name: %s", b) } } + +func TestNewClientStructuredLocation(t *testing.T) { + raw := json.RawMessage(`{"ip":"128.94.2.134","city":"Old City","region":"Old Region","country":"US","loc":"36.6676,-78.3875","org":"Microsoft"}`) + structured := &defs.LocationInfo{ + City: "Boydton", + Region: "Virginia", + Country: "US", + CountryName: "United States", + Latitude: 36.6676, + Longitude: -78.3875, + } + + c := NewClientWithLocation(raw, structured) + if c.Location == nil { + t.Fatal("Location returned nil") + } + if c.Location.City != "Boydton" || c.Location.Region != "Virginia" || + c.Location.Country != "US" || c.Location.CountryName != "United States" { + t.Errorf("Location = %#v", c.Location) + } + if !c.Location.ValidCoordinates() { + t.Errorf("structured coordinates not valid: %#v", c.Location) + } + + b, err := json.Marshal(c) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + if !strings.Contains(string(b), `"location":{"latitude":36.6676,"longitude":-78.3875,"city":"Boydton","region":"Virginia","country":"US","countryName":"United States"}`) { + t.Errorf("location JSON missing or malformed: %s", b) + } +} + +func TestNewClientLegacyRawIspLocationFallback(t *testing.T) { + c := NewClient(json.RawMessage(`{"city":"Boydton","region":"Virginia","country":"US","loc":"36.6676,-78.3875","org":"Microsoft"}`)) + if c.Location == nil { + t.Fatal("legacy Location returned nil") + } + if c.Location.City != "Boydton" || c.Location.Region != "Virginia" || + c.Location.Country != "US" { + t.Errorf("legacy location text = %#v", c.Location) + } + if !c.Location.ValidCoordinates() { + t.Errorf("legacy coordinates not valid: %#v", c.Location) + } +} + +func TestNewClientRejectsMultipleStructuredLocations(t *testing.T) { + raw := json.RawMessage(`{"city":"Boydton","region":"Virginia","country":"US","loc":"36.6676,-78.3875","org":"Microsoft"}`) + first := &defs.LocationInfo{City: "Berlin", Country: "DE"} + second := &defs.LocationInfo{City: "Washington", Country: "US"} + + c := NewClient(raw, first, second) + if c.Location == nil { + t.Fatal("legacy Location returned nil") + } + if c.Location.Country != "US" || c.Location.City != "Boydton" { + t.Errorf("extra structured location arguments changed the result: %#v", c.Location) + } +} diff --git a/speedtest/helper.go b/speedtest/helper.go index c68a1bb..11373d3 100644 --- a/speedtest/helper.go +++ b/speedtest/helper.go @@ -28,6 +28,62 @@ const ( pingCount = 10 ) +func approximateLocationSummary(location *defs.LocationInfo) string { + if location == nil { + return "" + } + + var place []string + appendPlace := func(value string) { + value = defs.CleanLocationText(value) + if value == "" { + return + } + for _, existing := range place { + if existing == value { + return + } + } + place = append(place, value) + } + appendPlace(location.City) + appendPlace(location.Region) + countryName := defs.CleanLocationText(location.CountryName) + country := defs.CleanLocationText(location.Country) + if countryName != "" { + appendPlace(countryName) + } else { + appendPlace(country) + } + + summary := strings.Join(place, ", ") + if location.ValidCoordinates() { + latitude := strconv.FormatFloat(location.Latitude, 'f', -1, 64) + longitude := strconv.FormatFloat(location.Longitude, 'f', -1, 64) + coordinates := "(" + latitude + ", " + longitude + ")" + if summary == "" { + summary = coordinates + } else { + summary += " " + coordinates + } + } else if location.ValidLatitude() { + latitude := strconv.FormatFloat(location.Latitude, 'f', -1, 64) + if summary == "" { + summary = "Latitude " + latitude + } else { + summary += " (Latitude " + latitude + ")" + } + } else if location.ValidLongitude() { + longitude := strconv.FormatFloat(location.Longitude, 'f', -1, 64) + if summary == "" { + summary = "Longitude " + longitude + } else { + summary += " (Longitude " + longitude + ")" + } + } + return summary +} + // activeTransport routes the test servers' requests; nil until SpeedTest // sets it up. telemetryClient sends results over TCP only, even when the // telemetry server is also a test server reached over HTTP/3. @@ -81,6 +137,9 @@ func doSpeedTest(c *cli.Context, servers []defs.Server, telemetryServer defs.Tel return err } output.WriteUI("You're testing from: %s\n", output.Sanitize(ispInfo.ProcessedString)) + if locationSummary := approximateLocationSummary(ispInfo.EffectiveLocation()); locationSummary != "" { + output.WriteUI("Approximate location: %s\n", output.Sanitize(locationSummary)) + } output.WriteDebug("IP info: %s\n", output.Sanitize(ispInfo.ProcessedString)) // get ping and jitter value @@ -228,6 +287,18 @@ func doSpeedTest(c *cli.Context, servers []defs.Server, telemetryServer defs.Tel rep.Upload = math.Round(uploadValue*100) / 100 rep.Share = shareLink rep.IP = ispInfo.IP() + if location := ispInfo.EffectiveLocation(); location != nil { + rep.City = defs.CleanLocationText(location.City) + rep.Region = defs.CleanLocationText(location.Region) + rep.Country = defs.CleanLocationText(location.Country) + rep.CountryName = defs.CleanLocationText(location.CountryName) + if location.ValidLatitude() { + rep.Latitude = strconv.FormatFloat(location.Latitude, 'f', -1, 64) + } + if location.ValidLongitude() { + rep.Longitude = strconv.FormatFloat(location.Longitude, 'f', -1, 64) + } + } reps_csv = append(reps_csv, rep) } else if c.Bool(defs.OptionJSON) || c.Bool(defs.OptionJSONStream) { @@ -255,7 +326,7 @@ func doSpeedTest(c *cli.Context, servers []defs.Server, telemetryServer defs.Tel } } - rep.Client = report.NewClient(ispInfo.RawISPInfo) + rep.Client = report.NewClientWithLocation(ispInfo.RawISPInfo, ispInfo.EffectiveLocation()) rep.Client.Readme = "" // IP() falls back to processedString, so the report carries an // address even when the backend keeps rawIspInfo empty. @@ -326,7 +397,9 @@ func noneResponding(down []downServer) error { return fmt.Errorf("None of the %d selected servers is responding: %s", len(down), strings.Join(causes, "; ")) } -// sendTelemetry sends the telemetry result to server, if --share is given +// sendTelemetry sends the telemetry result to server, if --share is given. +// The ispinfo multipart field preserves legacy processedString/rawIspInfo and +// also carries the optional normalized location object when available. func sendTelemetry(telemetryServer defs.TelemetryServer, ispInfo *defs.GetIPResult, download, upload, pingVal, jitter float64, logs string, extra defs.TelemetryExtra) (string, error) { var buf bytes.Buffer wr := multipart.NewWriter(&buf) diff --git a/speedtest/speedtest_test.go b/speedtest/speedtest_test.go index 503f6f0..cb9f96e 100644 --- a/speedtest/speedtest_test.go +++ b/speedtest/speedtest_test.go @@ -1,10 +1,125 @@ package speedtest import ( + "net/http" + "net/http/httptest" + "strings" "sync" "testing" + + "github.com/librespeed/speedtest-cli/defs" ) +func TestApproximateLocationSummary(t *testing.T) { + location := &defs.LocationInfo{ + City: "Boydton", + Region: "Virginia", + Country: "US", + CountryName: "United States", + Latitude: 36.6676, + Longitude: -78.3875, + } + + if got, want := approximateLocationSummary(location), "Boydton, Virginia, United States (36.6676, -78.3875)"; got != want { + t.Errorf("approximateLocationSummary = %q, want %q", got, want) + } +} + +func TestApproximateLocationSummaryMalformedCoordinates(t *testing.T) { + location := &defs.LocationInfo{ + City: "Boydton", + Region: "Virginia", + Country: "US", + Latitude: 91, + Longitude: -181, + } + + if got, want := approximateLocationSummary(location), "Boydton, Virginia, US"; got != want { + t.Errorf("approximateLocationSummary = %q, want %q", got, want) + } +} + +func TestApproximateLocationSummarySingleValidCoordinate(t *testing.T) { + location := &defs.LocationInfo{ + City: "Boydton", + Latitude: 36.6676, + } + + if got, want := approximateLocationSummary(location), "Boydton (Latitude 36.6676)"; got != want { + t.Errorf("approximateLocationSummary = %q, want %q", got, want) + } +} + +func TestApproximateLocationSummaryCleansWhitespaceAndInvisibleText(t *testing.T) { + location := &defs.LocationInfo{ + City: " ", + Region: "\u200b", + Country: "US", + CountryName: "\n", + } + + if got, want := approximateLocationSummary(location), "US"; got != want { + t.Errorf("approximateLocationSummary = %q, want %q", got, want) + } +} + +func TestSendTelemetryPreservesLocationMetadata(t *testing.T) { + ispInfoPayload := make(chan string, 1) + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if err := r.ParseMultipartForm(1 << 20); err != nil { + t.Errorf("ParseMultipartForm: %v", err) + http.Error(w, "bad multipart", http.StatusBadRequest) + return + } + ispInfoPayload <- r.FormValue("ispinfo") + w.WriteHeader(http.StatusOK) + w.Write([]byte("1 abc")) + })) + t.Cleanup(ts.Close) + + oldClient := telemetryClient + telemetryClient = ts.Client() + t.Cleanup(func() { telemetryClient = oldClient }) + + telemetryServer := defs.TelemetryServer{ + Level: defs.TelemetryLevelFull, + Server: ts.URL, + Path: "telemetry", + Share: "share", + } + ispInfo := &defs.GetIPResult{ + ProcessedString: "128.94.2.134 - AS8075", + RawISPInfo: []byte(`{"ip":"128.94.2.134","city":"Boydton","org":"Microsoft"}`), + Location: &defs.LocationInfo{ + City: "Boydton", + Region: "Virginia", + Country: "US", + CountryName: "United States", + Latitude: 36.6676, + Longitude: -78.3875, + }, + } + + link, err := sendTelemetry(telemetryServer, ispInfo, 100, 50, 10, 1, "", defs.TelemetryExtra{}) + if err != nil { + t.Fatalf("sendTelemetry: %v", err) + } + if !strings.Contains(link, "id=abc") { + t.Errorf("share link = %q, want id=abc", link) + } + + payload := <-ispInfoPayload + for _, want := range []string{ + `"processedString":"128.94.2.134 - AS8075"`, + `"rawIspInfo":{"ip":"128.94.2.134","city":"Boydton","org":"Microsoft"}`, + `"location":{"latitude":36.6676,"longitude":-78.3875,"city":"Boydton","region":"Virginia","country":"US","countryName":"United States"}`, + } { + if !strings.Contains(payload, want) { + t.Errorf("telemetry ispinfo lacks %s: %s", want, payload) + } + } +} + func TestWellKnownServerURL(t *testing.T) { cases := []struct { name string