-
Notifications
You must be signed in to change notification settings - Fork 0
/
geolookup_rpc.go
324 lines (270 loc) · 7.84 KB
/
geolookup_rpc.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/*-
* Copyright (c) 2012-2016 Caoimhe Chaos <caoimhechaos@protonmail.com>,
* Ancient Solutions. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY ANCIENT SOLUTIONS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package geocolo
import (
"database/sql"
"errors"
"fmt"
"net"
"strings"
_ "github.com/lib/pq"
libgeo "github.com/nranchev/go-libGeoIP"
"golang.org/x/net/context"
)
var (
addr192 = net.IPv4(192, 168, 0, 0)
addr172 = net.IPv4(172, 16, 0, 0)
addr10 = net.IPv4(10, 0, 0, 0)
mask8 = net.IPv4Mask(255, 0, 0, 0)
mask16 = net.IPv4Mask(255, 255, 0, 0)
net192 = net.IPNet{
IP: addr192,
Mask: mask16,
}
net172 = net.IPNet{
IP: addr172,
Mask: mask16,
}
net10 = net.IPNet{
IP: addr10,
Mask: mask8,
}
)
type GeoProximityService struct {
conn *sql.DB
gi *libgeo.GeoIP
rfc1918_country string
}
func isRFC1918(addr string) bool {
var ip net.IP = net.ParseIP(addr)
if ip.To4() == nil {
return false
}
return net192.Contains(ip) || net172.Contains(ip) || net10.Contains(ip)
}
func NewGeoProximityService(
config *GeoProximityServiceConfig) (*GeoProximityService, error) {
var gi *libgeo.GeoIP
var dsn string
var rfc1918 string
var c *sql.DB
var err error
dsn = fmt.Sprintf("user=%s dbname=%s host=%s port=%d",
*config.User, *config.Dbname, *config.Host, *config.Port)
if config.Password != nil {
dsn += fmt.Sprintf(" password=%s", *config.Password)
}
if config.Sslmode != nil {
dsn += fmt.Sprintf(" sslmode=%s", *config.Sslmode)
}
c, err = sql.Open("postgres", dsn)
if err != nil {
return nil, err
}
if config.GeoipPath != nil {
gi, err = libgeo.Load(*config.GeoipPath)
if err != nil {
return nil, err
}
}
if config.Rfc1918Country != nil {
rfc1918 = strings.ToUpper(*config.Rfc1918Country)
}
if rfc1918 == "" {
rfc1918 = "CH"
}
return &GeoProximityService{
conn: c,
gi: gi,
rfc1918_country: rfc1918,
}, nil
}
func (self *GeoProximityService) GetProximity(
ctx context.Context,
req *GeoProximityRequest) (res *GeoProximityResponse, err error) {
var rows *sql.Rows
if req.Origin == nil {
return nil, errors.New("No origin specified")
}
if len(req.Candidates) > 0 {
var fullsql string
var valuecollection []string
var value string
for _, value = range req.Candidates {
value = strings.ToUpper(value)
if len(value) == 2 && value[0] >= 'A' &&
value[0] <= 'Z' && value[1] >= 'A' &&
value[1] <= 'Z' {
valuecollection = append(valuecollection,
"'"+value+"'")
}
}
fullsql = strings.Join(valuecollection, ",")
rows, err = self.conn.Query("SELECT s.iso_a2, st_distance("+
"s.geom, (SELECT g.geom FROM geoborders g "+
"WHERE g.iso_a2 = $1 ) ) AS dist FROM geoborders s "+
"WHERE s.iso_a2 IN ( "+fullsql+" ) ORDER BY "+
"dist ASC", strings.ToUpper(*req.Origin))
} else {
rows, err = self.conn.Query("SELECT s.iso_a2, st_distance("+
"s.geom, (SELECT g.geom FROM geoborders g "+
"WHERE g.iso_a2 = $1 ) ) AS dist FROM geoborders s "+
"ORDER BY dist ASC", strings.ToUpper(*req.Origin))
}
if err != nil {
return
}
res = new(GeoProximityResponse)
for rows.Next() {
var detail *GeoProximityDetail = new(GeoProximityDetail)
detail.Country = new(string)
detail.Distance = new(float64)
err = rows.Scan(detail.Country, detail.Distance)
if err != nil {
return
}
if *detail.Distance == 0 && *detail.Country != *req.Origin {
*detail.Distance += 0.01
}
if res.Closest == nil {
res.Closest = detail.Country
}
if req.DetailedResponse != nil && *req.DetailedResponse {
res.FullMap = append(res.FullMap, detail)
}
}
return
}
// Request which list of destination IPs are closest to a given source
// IP. Takes a radius around which results are returned but we always
// return at least one.
func (self *GeoProximityService) GetProximityByIP(
ctx context.Context,
req *GeoProximityByIPRequest) (res *GeoProximityByIPResponse, err error) {
var addrlocations = make(map[string][]*GeoProximityByIPDetail)
var locdata []string = make([]string, 0)
var maxdistance float64
var loc *libgeo.Location
var origin string
var fullsql string
var rows *sql.Rows
var initclosest int
if self.gi == nil {
return nil, errors.New("GeoIP not loaded")
}
if req.Origin == nil {
return nil, errors.New("No origin specified")
}
res = new(GeoProximityByIPResponse)
// First, determine the geodata for all of the given IPs and
// sort them into a map.
for _, addr := range req.Candidates {
loc = self.gi.GetLocationByIP(addr)
if loc == nil {
// No country data? Always return…
res.Closest = append(res.Closest, addr)
} else {
var cc string = strings.ToUpper(
loc.CountryCode)
var detail *GeoProximityByIPDetail = new(GeoProximityByIPDetail)
var ok bool
detail.Ip = new(string)
*detail.Ip = addr
_, ok = addrlocations[cc]
if !ok {
addrlocations[cc] =
make([]*GeoProximityByIPDetail,
0)
}
addrlocations[cc] =
append(addrlocations[cc], detail)
}
}
initclosest = len(res.Closest)
for cc, _ := range addrlocations {
locdata = append(locdata, "'"+cc+"'")
}
fullsql = strings.Join(locdata, ",")
if isRFC1918(*req.Origin) {
origin = self.rfc1918_country
} else {
// Now let's figure out where the request came from.
// TODO(caoimhe): Handle RFC1918 IPs.
loc = self.gi.GetLocationByIP(*req.Origin)
if loc == nil {
// Fail open: return all IPs.
// TODO(caoimhe): Filter out RFC1918 IPs.
res.Closest = req.Candidates
return
}
origin = strings.ToUpper(loc.CountryCode)
}
rows, err = self.conn.Query("SELECT s.iso_a2, st_distance("+
"s.geom, (SELECT g.geom FROM geoborders g "+
"WHERE g.iso_a2 = $1 ) ) AS dist FROM geoborders s "+
"WHERE s.iso_a2 IN ( "+fullsql+" ) ORDER BY "+
"dist ASC", origin)
if err != nil {
return
}
for rows.Next() {
var country string
var distance float64
var detail *GeoProximityByIPDetail
err = rows.Scan(&country, &distance)
if err != nil {
return
}
// Ensure neighbors of the country of origin always get a
// slight penalty so that same-country responses are
// preferred.
if country != origin {
distance += 0.01
}
for _, detail = range addrlocations[country] {
detail.Distance = new(float64)
*detail.Distance = distance
if len(res.Closest) == initclosest {
maxdistance = distance
if req.MaxDistance != nil {
maxdistance +=
*req.MaxDistance
}
}
if distance <= maxdistance {
res.Closest = append(res.Closest,
*detail.Ip)
}
if req.DetailedResponse != nil && *req.DetailedResponse {
res.FullMap = append(res.FullMap, detail)
}
}
}
return
}