-
Notifications
You must be signed in to change notification settings - Fork 92
/
maxmind.go
73 lines (66 loc) · 1.8 KB
/
maxmind.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package maxmind
import (
"fmt"
"net"
"sync"
logger "github.com/ipfs/go-log/v2"
"github.com/multiformats/go-multiaddr"
geoip2 "github.com/oschwald/geoip2-golang"
"github.com/textileio/powergate/iplocation"
"github.com/textileio/powergate/util"
)
var (
log = logger.Logger("maxmind")
)
// MaxMind is an iplocation resolver using the MaxMind database.
type MaxMind struct {
lock sync.Mutex
db *geoip2.Reader
}
// New returns a new MaxMind iplocation resolver.
func New(db string) (*MaxMind, error) {
r, err := geoip2.Open(db)
if err != nil {
return nil, fmt.Errorf("opening geolite2 database: %s", err)
}
return &MaxMind{db: r}, nil
}
// Resolve returns Location information from multiaddrs.
func (mm *MaxMind) Resolve(mas []multiaddr.Multiaddr) (iplocation.Location, error) {
for _, ma := range mas {
ipport, err := util.TCPAddrFromMultiAddr(ma)
if err != nil {
log.Debugf("transforming %s to tcp addr: %s", ma, err)
continue
}
strIP, _, err := net.SplitHostPort(ipport)
if err != nil {
log.Debugf("parsing ip/port from %s: %s", ipport, err)
continue
}
ip := net.ParseIP(strIP)
city, err := mm.db.City(ip)
if err != nil {
log.Debugf("querying maxmind db for %s: %s", ipport, err)
continue
}
if city.Country.IsoCode != "" || (city.Location.Latitude != 0 && city.Location.Longitude != 0) {
return iplocation.Location{
Country: city.Country.IsoCode,
Latitude: city.Location.Latitude,
Longitude: city.Location.Longitude,
}, nil
}
log.Debugf("no info for addr %s", ip)
}
return iplocation.Location{}, iplocation.ErrCantResolve
}
// Close closes the iplocation resolver.
func (mm *MaxMind) Close() error {
mm.lock.Lock()
defer mm.lock.Unlock()
if err := mm.db.Close(); err != nil {
return fmt.Errorf("closing geolite2 database: %s", err)
}
return nil
}