Debian Codegraph @

network/geoip.go

raw
1 // Copyright (c) 2014-2019 Ludovic Fauvet
2 // Licensed under the MIT license
3
4 package network
5
6 import (
7 "errors"
8 "net"
9 "os"
10 "strings"
11 "sync"
12 "time"
13
14 . "github.com/etix/mirrorbits/config"
15 "github.com/op/go-logging"
16 "github.com/oschwald/maxminddb-golang"
17 )
18
19 var (
20 // ErrMultipleAddresses is returned when the mirror has more than one address
21 ErrMultipleAddresses = errors.New("the mirror has more than one IP address")
22 log = logging.MustGetLogger("main")
23 )
24
25 const (
26 geoipUpdatedExt = ".updated"
27 )
28
29 // GeoIP contains methods to query the GeoIP database
30 type GeoIP struct {
31 sync.RWMutex
32
33 city *geoipDB
34 asn *geoipDB
35 }
36
37 // GeoIPRecord defines a GeoIP record for a given IP address
38 type GeoIPRecord struct {
39 // City DB
40 CountryCode string
41 ContinentCode string
42 City string
43 Country string
44 Latitude float32
45 Longitude float32
46
47 // ASN DB
48 ASName string
49 ASNum uint
50 }
51
52 // Geolocalizer is an interface representing a GeoIP library
53 type Geolocalizer interface {
54 Lookup(ipAddress net.IP, result any) error
55 }
56
57 // NewGeoIP instanciates a new instance of GeoIP
58 func NewGeoIP() *GeoIP {
59 return &GeoIP{}
60 }
61
62 // Open the GeoIP database
63 func (g *GeoIP) openDatabase(file string) (*maxminddb.Reader, error) {
64 dbpath := GetConfig().GeoipDatabasePath
65 if dbpath != "" && !strings.HasSuffix(dbpath, "/") {
66 dbpath += "/"
67 }
68
69 filename := dbpath + file
70
71 var err error
72
73 if _, err = os.Stat(filename + geoipUpdatedExt); !os.IsNotExist(err) {
74 filename += geoipUpdatedExt
75 }
76
77 return maxminddb.Open(filename)
78 }
79
80 type geoipDB struct {
81 filename string
82 modTime time.Time
83 db Geolocalizer
84 }
85
86 func (g *GeoIP) loadDB(filename string, geodb **geoipDB, geoiperror *GeoIPError) error {
87 // Increase the loaded counter
88 geoiperror.loaded++
89
90 if *geodb == nil {
91 *geodb = &geoipDB{
92 filename: filename,
93 }
94 }
95
96 db, err := g.openDatabase(filename)
97 if err != nil {
98 geoiperror.Errors = append(geoiperror.Errors, err)
99 return err
100 }
101
102 modTime := time.Unix(int64(db.Metadata.BuildEpoch), 0)
103
104 if (*geodb).modTime.Equal(modTime) {
105 return nil
106 }
107
108 (*geodb).db = db
109 (*geodb).modTime = modTime
110
111 log.Infof("Loading %s database (built on %s)", filename, (*geodb).modTime)
112 return nil
113 }
114
115 // GeoIPError holds errors while loading the different databases
116 type GeoIPError struct {
117 Errors []error
118 loaded int
119 }
120
121 func (e GeoIPError) Error() string {
122 return "One or more GeoIP database could not be loaded"
123 }
124
125 // IsFatal returns true if the error is fatal
126 func (e GeoIPError) IsFatal() bool {
127 return e.loaded == len(e.Errors)
128 }
129
130 // LoadGeoIP loads the GeoIP databases into memory
131 func (g *GeoIP) LoadGeoIP() error {
132 var ret GeoIPError
133
134 g.Lock()
135 g.loadDB("GeoLite2-City.mmdb", &g.city, &ret)
136 g.loadDB("GeoLite2-ASN.mmdb", &g.asn, &ret)
137 g.Unlock()
138
139 if len(ret.Errors) > 0 {
140 return ret
141 }
142 return nil
143 }
144
145 // GetRecord return informations about the given ip address
146 // (works in IPv4 and v6)
147 func (g *GeoIP) GetRecord(ip string) (ret GeoIPRecord) {
148 addr := net.ParseIP(ip)
149 if addr == nil {
150 return GeoIPRecord{}
151 }
152
153 type CityDb struct {
154 City struct {
155 Names struct {
156 English string `maxminddb:"en"`
157 } `maxminddb:"names"`
158 } `maxminddb:"city"`
159 Country struct {
160 IsoCode string `maxminddb:"iso_code"`
161 Names struct {
162 English string `maxminddb:"en"`
163 } `maxminddb:"names"`
164 } `maxminddb:"country"`
165 Continent struct {
166 Code string `maxminddb:"code"`
167 } `maxminddb:"continent"`
168 Location struct {
169 Latitude float64 `maxminddb:"latitude"`
170 Longitude float64 `maxminddb:"longitude"`
171 } `maxminddb:"location"`
172 }
173
174 type ASNDb struct {
175 AutonomousSystemNumber uint `maxminddb:"autonomous_system_number"`
176 AutonomousSystemOrg string `maxminddb:"autonomous_system_organization"`
177 }
178
179 var err error
180 var cityDb CityDb
181 var asnDb ASNDb
182
183 g.RLock()
184 defer g.RUnlock()
185
186 if g.city != nil && g.city.db != nil {
187 err = g.city.db.Lookup(addr, &cityDb)
188 if err != nil {
189 return GeoIPRecord{}
190 }
191 ret.CountryCode = cityDb.Country.IsoCode
192 ret.ContinentCode = cityDb.Continent.Code
193 ret.City = cityDb.City.Names.English
194 ret.Country = cityDb.Country.Names.English
195 ret.Latitude = float32(cityDb.Location.Latitude)
196 ret.Longitude = float32(cityDb.Location.Longitude)
197 }
198 if g.asn != nil && g.asn.db != nil {
199 err = g.asn.db.Lookup(addr, &asnDb)
200 if err != nil {
201 return GeoIPRecord{}
202 }
203 ret.ASName = asnDb.AutonomousSystemOrg
204 ret.ASNum = asnDb.AutonomousSystemNumber
205 }
206
207 return ret
208 }
209
210 // IsIPv6 returns true if the given address is of version 6
211 func (g *GeoIP) IsIPv6(ip string) bool {
212 return strings.Contains(ip, ":")
213 }
214
215 // IsValid returns true if the given address is valid
216 func (g *GeoIPRecord) IsValid() bool {
217 return len(g.CountryCode) > 0
218 }