Improve location handling

This commit is contained in:
Daniel
2021-09-17 22:05:14 +02:00
parent a6ce021dbd
commit 28a3cf3f4d

View File

@@ -2,7 +2,9 @@ package netenv
import ( import (
"errors" "errors"
"fmt"
"net" "net"
"sort"
"sync" "sync"
"syscall" "syscall"
"time" "time"
@@ -22,9 +24,7 @@ var (
locationTestingIPv4 = "1.1.1.1" locationTestingIPv4 = "1.1.1.1"
locationTestingIPv4Addr *net.IPAddr locationTestingIPv4Addr *net.IPAddr
locations = &DeviceLocations{ locations = &DeviceLocations{}
All: make(map[string]*DeviceLocation),
}
locationsLock sync.Mutex locationsLock sync.Mutex
gettingLocationsLock sync.Mutex gettingLocationsLock sync.Mutex
locationNetworkChangedFlag = GetNetworkChangedFlag() locationNetworkChangedFlag = GetNetworkChangedFlag()
@@ -36,8 +36,32 @@ func prepLocation() (err error) {
} }
type DeviceLocations struct { type DeviceLocations struct {
Best *DeviceLocation All []*DeviceLocation
All map[string]*DeviceLocation }
func (dl *DeviceLocations) Best() *DeviceLocation {
if len(dl.All) > 0 {
return dl.All[0]
}
return nil
}
func (dl *DeviceLocations) BestV4() *DeviceLocation {
for _, loc := range dl.All {
if loc.IPVersion == packet.IPv4 {
return loc
}
}
return nil
}
func (dl *DeviceLocations) BestV6() *DeviceLocation {
for _, loc := range dl.All {
if loc.IPVersion == packet.IPv6 {
return loc
}
}
return nil
} }
func copyDeviceLocations() *DeviceLocations { func copyDeviceLocations() *DeviceLocations {
@@ -45,23 +69,20 @@ func copyDeviceLocations() *DeviceLocations {
defer locationsLock.Unlock() defer locationsLock.Unlock()
// Create a copy of the locations, but not the entries. // Create a copy of the locations, but not the entries.
cp := *locations cp := &DeviceLocations{
cp.All = make(map[string]*DeviceLocation, len(locations.All)) All: make([]*DeviceLocation, len(locations.All)),
for k, v := range locations.All {
cp.All[k] = v
} }
copy(cp.All, locations.All)
return &cp return cp
} }
// DeviceLocation represents a single IP and metadata. It must not be changed // DeviceLocation represents a single IP and metadata. It must not be changed
// once created. // once created.
type DeviceLocation struct { type DeviceLocation struct {
IP net.IP IP net.IP
Continent string IPVersion packet.IPVersion
Country string Location *geoip.Location
ASN uint
ASOrg string
Source DeviceLocationSource Source DeviceLocationSource
SourceAccuracy int SourceAccuracy int
} }
@@ -71,19 +92,47 @@ type DeviceLocation struct {
func (dl *DeviceLocation) IsMoreAccurateThan(other *DeviceLocation) bool { func (dl *DeviceLocation) IsMoreAccurateThan(other *DeviceLocation) bool {
switch { switch {
case dl.SourceAccuracy > other.SourceAccuracy: case dl.SourceAccuracy > other.SourceAccuracy:
// Higher accuracy is better. // Higher source accuracy is better.
return true return true
case dl.ASN != 0 && other.ASN == 0: case dl.Location.AutonomousSystemNumber != 0 && other.Location.AutonomousSystemNumber == 0:
// Having an ASN is better than having none. // Having an ASN is better than having none.
return true return true
case dl.Country == "" && other.Country != "": case dl.Location.Continent.Code != "" && other.Location.Continent.Code == "":
// Having a Continent is better than having none.
return true
case dl.Location.Country.ISOCode != "" && other.Location.Country.ISOCode == "":
// Having a Country is better than having none. // Having a Country is better than having none.
return true return true
case dl.Location.Coordinates.AccuracyRadius < other.Location.Coordinates.AccuracyRadius:
// Higher geo accuracy is better.
return true
} }
return false return false
} }
func (dl *DeviceLocation) LocationOrNil() *geoip.Location {
switch {
case dl == nil:
return nil
case dl.Location == nil:
return nil
default:
return dl.Location
}
}
func (dl *DeviceLocation) String() string {
switch {
case dl == nil:
return "<none>"
case dl.Location == nil:
return dl.IP.String()
default:
return fmt.Sprintf("%s (AS%d in %s)", dl.IP, dl.Location.AutonomousSystemNumber, dl.Location.Country.ISOCode)
}
}
type DeviceLocationSource string type DeviceLocationSource string
const ( const (
@@ -111,6 +160,12 @@ func (dls DeviceLocationSource) Accuracy() int {
} }
} }
type sortLocationsByAccuracy []*DeviceLocation
func (a sortLocationsByAccuracy) Len() int { return len(a) }
func (a sortLocationsByAccuracy) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a sortLocationsByAccuracy) Less(i, j int) bool { return a[j].IsMoreAccurateThan(a[i]) }
func SetInternetLocation(ip net.IP, source DeviceLocationSource) (ok bool) { func SetInternetLocation(ip net.IP, source DeviceLocationSource) (ok bool) {
// Check if IP is global. // Check if IP is global.
if netutils.GetIPScope(ip) != netutils.Global { if netutils.GetIPScope(ip) != netutils.Global {
@@ -123,39 +178,41 @@ func SetInternetLocation(ip net.IP, source DeviceLocationSource) (ok bool) {
Source: source, Source: source,
SourceAccuracy: source.Accuracy(), SourceAccuracy: source.Accuracy(),
} }
if v4 := ip.To4(); v4 != nil {
loc.IPVersion = packet.IPv4
} else {
loc.IPVersion = packet.IPv6
}
// Get geoip information, but continue if it fails. // Get geoip information, but continue if it fails.
geoLoc, err := geoip.GetLocation(ip) geoLoc, err := geoip.GetLocation(ip)
if err != nil { if err != nil {
log.Warningf("netenv: failed to get geolocation data of %s (from %s): %s", ip, source, err) log.Warningf("netenv: failed to get geolocation data of %s (from %s): %s", ip, source, err)
} else { } else {
loc.Continent = geoLoc.Continent.Code loc.Location = geoLoc
loc.Country = geoLoc.Country.ISOCode
loc.ASN = geoLoc.AutonomousSystemNumber
loc.ASOrg = geoLoc.AutonomousSystemOrganization
} }
locationsLock.Lock() locationsLock.Lock()
defer locationsLock.Unlock() defer locationsLock.Unlock()
// Add to locations, if better. // Add to locations, if better.
key := loc.IP.String() var exists bool
existing, ok := locations.All[key] for i, existing := range locations.All {
if ok && existing.IsMoreAccurateThan(loc) { if ip.Equal(existing.IP) {
// Existing entry is more accurate, abort adding. exists = true
// Return true, because the IP address is already part of the locations. if loc.IsMoreAccurateThan(existing) {
return true // Replace
} locations.All[i] = loc
locations.All[key] = loc break
}
// Find best location.
best := loc
for _, dl := range locations.All {
if dl.IsMoreAccurateThan(best) {
best = dl
} }
} }
locations.Best = best if !exists {
locations.All = append(locations.All, loc)
}
// Sort locations.
sort.Sort(sortLocationsByAccuracy(locations.All))
return true return true
} }
@@ -163,10 +220,10 @@ func SetInternetLocation(ip net.IP, source DeviceLocationSource) (ok bool) {
// DEPRECATED: Please use GetInternetLocation instead. // DEPRECATED: Please use GetInternetLocation instead.
func GetApproximateInternetLocation() (net.IP, error) { func GetApproximateInternetLocation() (net.IP, error) {
loc, ok := GetInternetLocation() loc, ok := GetInternetLocation()
if !ok { if !ok || loc.Best() == nil {
return nil, errors.New("no location data available") return nil, errors.New("no location data available")
} }
return loc.Best.IP, nil return loc.Best().IP, nil
} }
func GetInternetLocation() (deviceLocations *DeviceLocations, ok bool) { func GetInternetLocation() (deviceLocations *DeviceLocations, ok bool) {
@@ -179,38 +236,54 @@ func GetInternetLocation() (deviceLocations *DeviceLocations, ok bool) {
} }
locationNetworkChangedFlag.Refresh() locationNetworkChangedFlag.Refresh()
// Check different sources, return on first success. // Get all assigned addresses.
switch { v4s, v6s, err := GetAssignedAddresses()
case getLocationFromInterfaces(): if err != nil {
case getLocationFromTraceroute(): log.Warningf("netenv: failed to get assigned addresses: %s", err)
default: return nil, false
}
// Check interfaces for global addresses.
v4ok, v6ok := getLocationFromInterfaces()
// Try other methods for missing locations.
if len(v4s) > 0 && !v4ok {
v4ok = getLocationFromTraceroute()
}
if len(v6s) > 0 && !v6ok {
// TODO
log.Warningf("netenv: could not get IPv6 location")
}
// Check if we have any locations.
if !v4ok && !v6ok {
return nil, false return nil, false
} }
// Return gathered locations. // Return gathered locations.
cp := copyDeviceLocations() cp := copyDeviceLocations()
return cp, cp.Best != nil return cp, true
} }
func getLocationFromInterfaces() (ok bool) { func getLocationFromInterfaces() (v4ok, v6ok bool) {
globalIPv4, globalIPv6, err := GetAssignedGlobalAddresses() globalIPv4, globalIPv6, err := GetAssignedGlobalAddresses()
if err != nil { if err != nil {
log.Warningf("netenv: location: failed to get assigned global addresses: %s", err) log.Warningf("netenv: location: failed to get assigned global addresses: %s", err)
return false return false, false
} }
for _, ip := range globalIPv4 { for _, ip := range globalIPv4 {
if SetInternetLocation(ip, SourceInterface) { if SetInternetLocation(ip, SourceInterface) {
ok = true v4ok = true
} }
} }
for _, ip := range globalIPv6 { for _, ip := range globalIPv6 {
if SetInternetLocation(ip, SourceInterface) { if SetInternetLocation(ip, SourceInterface) {
ok = true v6ok = true
} }
} }
return ok return
} }
// TODO: Check feasibility of getting the external IP via UPnP. // TODO: Check feasibility of getting the external IP via UPnP.
@@ -223,7 +296,7 @@ func getLocationFromUPnP() (ok bool) {
} }
*/ */
func getLocationFromTraceroute() (ok bool) { func getLocationFromTraceroute() (v4ok bool) {
// Create connection. // Create connection.
conn, err := net.ListenPacket("ip4:icmp", "") conn, err := net.ListenPacket("ip4:icmp", "")
if err != nil { if err != nil {