forked from fiorix/freegeoip
/
freegeoip.go
385 lines (337 loc) · 8.2 KB
/
freegeoip.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
// Copyright 2013-2014 Alexandre Fiori
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Web server of freegeoip.net
package main
import (
"database/sql"
"encoding/binary"
"encoding/json"
"encoding/xml"
"expvar"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"os/signal"
"runtime"
"runtime/pprof"
"strings"
"sync"
"time"
"github.com/fiorix/go-web/httpxtra"
_ "github.com/mattn/go-sqlite3"
//_ "code.google.com/p/gosqlite/sqlite3"
)
var (
conf *ConfigFile
protoCount = expvar.NewMap("Protocol") // HTTP or HTTPS
outputCount = expvar.NewMap("Output") // json, xml, csv or other
statusCount = expvar.NewMap("Status") // 200, 403, 404, etc
)
func main() {
cf := flag.String("config", "freegeoip.conf", "set config file")
prof := flag.Bool("profile", false, "run cpu and mem profiling")
flag.Parse()
if buf, err := ioutil.ReadFile(*cf); err != nil {
log.Fatal(err)
} else {
conf = &ConfigFile{}
if err := xml.Unmarshal(buf, conf); err != nil {
log.Fatal(err)
}
}
if *prof {
profile()
}
runtime.GOMAXPROCS(runtime.NumCPU())
log.Printf("FreeGeoIP server starting. debug=%t", conf.Debug)
if conf.Debug && len(conf.DebugSrv) > 0 {
go func() {
// server for expvar's /debug/vars only
log.Printf("Starting DEBUG HTTP server on %s", conf.DebugSrv)
log.Fatal(http.ListenAndServe(conf.DebugSrv, nil))
}()
}
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.Dir(conf.DocumentRoot)))
h := LookupHandler()
mux.HandleFunc("/csv/", h)
mux.HandleFunc("/xml/", h)
mux.HandleFunc("/json/", h)
wg := new(sync.WaitGroup)
for _, l := range conf.Listen {
if l.Addr == "" {
continue
}
wg.Add(1)
h := httpxtra.Handler{Handler: mux, XHeaders: l.XHeaders}
if l.Log {
h.Logger = logger
}
s := http.Server{
Addr: l.Addr,
Handler: h,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
}
if l.KeyFile == "" && l.CertFile == "" {
log.Printf("Starting HTTP server on %s "+
"log=%t xheaders=%t",
l.Addr, l.Log, l.XHeaders)
go func() {
log.Fatal(httpxtra.ListenAndServe(s))
}()
} else {
log.Printf("Starting HTTPS server on %s "+
"log=%t xheaders=%t cert=%s key=%s",
l.Addr, l.Log, l.XHeaders,
l.CertFile, l.KeyFile)
go func() {
log.Fatal(s.ListenAndServeTLS(
l.CertFile,
l.KeyFile,
))
}()
}
}
wg.Wait()
}
// LookupHandler handles GET on /csv, /xml and /json.
func LookupHandler() http.HandlerFunc {
db, err := sql.Open("sqlite3", conf.IPDB.File)
if err != nil {
log.Fatal(err)
}
_, err = db.Exec("PRAGMA cache_size=" + conf.IPDB.CacheSize)
if err != nil {
log.Fatal(err)
}
stmt, err := db.Prepare(ipdb_query)
if err != nil {
log.Fatal(err)
}
log.Println("Caching database, please wait...")
cache := NewCache(db)
//defer stmt.Close()
var quota Quota
if len(conf.Redis) == 0 {
quota = new(MapQuota)
quota.Setup()
log.Printf("Using internal map to manage quota.")
} else {
quota = new(RedisQuota)
quota.Setup(conf.Redis...)
log.Printf("Using redis to manage quota: %s", conf.Redis)
}
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
w.Header().Set("Access-Control-Allow-Origin", "*")
case "OPTIONS":
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Methods", "GET")
w.Header().Set("Access-Control-Allow-Headers", "X-Requested-With")
w.WriteHeader(200)
return
default:
w.Header().Set("Allow", "GET, OPTIONS")
http.Error(w, http.StatusText(405), 405)
return
}
// GET continues...
var srcIP net.IP
// If xheaders is enabled, RemoteAddr might be a copy of
// the X-Real-IP or X-Forwarded-For HTTP headers, which
// can be a comma separated list of IPs. In this case,
// only the first IP in the list is used.
r.RemoteAddr = strings.SplitN(r.RemoteAddr, ",", 2)[0]
if ip, _, err := net.SplitHostPort(r.RemoteAddr); err != nil {
srcIP = net.ParseIP(r.RemoteAddr) // Use X-Real-IP
} else {
srcIP = net.ParseIP(ip)
}
if srcIP == nil {
http.Error(w, http.StatusText(400), 400)
return
}
nsrcIP, err := ip2int(srcIP)
if err != nil {
if conf.Debug {
log.Println(err)
}
http.Error(w, http.StatusText(400), 400)
return
}
// Check quota.
if conf.Limit.MaxRequests > 0 {
var ok bool
if ok, err = quota.Ok(nsrcIP); err != nil {
if conf.Debug {
log.Println(err) // redis error
}
http.Error(w, http.StatusText(503), 503)
return
} else if !ok {
// Over quota, soz :(
http.Error(w, http.StatusText(403), 403)
return
}
}
var (
queryIP net.IP
nqueryIP uint32
)
// Parse URL (e.g. /csv/ip, /xml/)
a := strings.SplitN(r.URL.Path, "/", 3)
if len(a) == 3 && a[2] != "" {
addrs, err := net.LookupHost(a[2])
if err != nil {
// DNS lookup failed, assume host not found.
http.Error(w, http.StatusText(404), 404)
return
}
if queryIP = net.ParseIP(addrs[0]); queryIP == nil {
http.Error(w, http.StatusText(400), 400)
return
}
nqueryIP, err = ip2int(net.ParseIP(addrs[0]))
if err != nil {
if conf.Debug {
log.Println(err)
}
http.Error(w, http.StatusText(400), 400)
return
}
} else {
queryIP = srcIP
nqueryIP = nsrcIP
}
// Query the db.
geoip, err := ipdb_lookup(stmt, cache, queryIP, nqueryIP)
if err != nil {
http.NotFound(w, r)
return
}
switch a[1][0] {
case 'j': // json
enc := json.NewEncoder(w)
if cb := r.FormValue("callback"); cb != "" {
w.Header().Set("Content-Type", "text/javascript")
fmt.Fprintf(w, "%s(", cb)
enc.Encode(geoip)
fmt.Fprintf(w, ");")
} else {
w.Header().Set("Content-Type", "application/json")
enc.Encode(geoip)
}
case 'x': // xml
w.Header().Set("Content-Type", "application/xml")
fmt.Fprintf(w, xml.Header)
enc := xml.NewEncoder(w)
enc.Indent("", " ")
enc.Encode(geoip)
fmt.Fprintf(w, "\n")
case 'c': // csv
w.Header().Set("Content-Type", "application/csv")
fmt.Fprintf(w, `"%s","%s","%s","%s","%s","%s",`+
`"%s","%0.4f","%0.4f","%s","%s"`+"\r\n",
geoip.Ip,
geoip.CountryCode, geoip.CountryName,
geoip.RegionCode, geoip.RegionName,
geoip.CityName, geoip.ZipCode,
geoip.Latitude, geoip.Longitude,
geoip.MetroCode, geoip.AreaCode)
}
}
}
func ip2int(ip net.IP) (uint32, error) {
ipv4 := ip.To4()
if ipv4 == nil {
return 0, fmt.Errorf("IP %s is not IPv4", ip.String())
}
return binary.BigEndian.Uint32(ipv4), nil
}
func profile() {
f, err := os.Create("freegeoip.cpu.prof")
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, os.Kill)
go func() {
<-sig
pprof.StopCPUProfile()
f.Close()
f, err = os.Create("freegeoip.mem.prof")
if err != nil {
log.Fatal(err)
}
pprof.WriteHeapProfile(f)
os.Exit(0)
}()
}
func logger(r *http.Request, created time.Time, status, bytes int) {
//fmt.Println(httpxtra.ApacheCommonLog(r, created, status, bytes))
var (
s, ip string
err error
)
if r.TLS == nil {
s = "HTTP"
} else {
s = "HTTPS"
}
if ip, _, err = net.SplitHostPort(r.RemoteAddr); err != nil {
ip = r.RemoteAddr
}
log.Printf("%s %d %s %q (%s) :: %s",
s,
status,
r.Method,
r.URL.Path,
ip,
time.Since(created),
)
if conf.Debug {
protoCount.Add(s, 1)
statusCount.Add(fmt.Sprintf("%d", status), 1)
switch strings.SplitN(r.URL.Path, "/", 2)[1] {
case "json/":
outputCount.Add("json", 1)
case "xml/":
outputCount.Add("xml", 1)
case "csv/":
outputCount.Add("csv", 1)
default:
outputCount.Add("other", 1)
}
}
}
type ConfigFile struct {
XMLName xml.Name `xml:"Server"`
Debug bool `xml:"debug,attr"`
DebugSrv string `xml:"debugsrv,attr"`
DocumentRoot string
Listen []*struct {
Log bool `xml:"log,attr"`
XHeaders bool `xml:"xheaders,attr"`
Addr string `xml:"addr,attr"`
CertFile string
KeyFile string
}
IPDB struct {
File string `xml:",attr"`
CacheSize string `xml:",attr"`
}
Limit struct {
MaxRequests int `xml:",attr"`
Expire int `xml:",attr"`
}
Redis []string `xml:"Redis>Addr"`
}