-
Notifications
You must be signed in to change notification settings - Fork 2
/
db.go
97 lines (74 loc) · 1.89 KB
/
db.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
package main
import (
"os"
"strconv"
"strings"
"sync"
"github.com/sirupsen/logrus"
"github.com/pkg/errors"
"github.com/go-redis/redis"
)
type DB struct {
conn *redis.Client
}
func NewDB(uri string) *DB {
opt, err := redis.ParseURL(uri)
if err != nil {
panic("unable to parse redis uri: " + err.Error())
}
return &DB{conn: redis.NewClient(opt)}
}
func (db *DB) Close() error {
return db.conn.Close()
}
func (db *DB) UpdateForUrlMatch(m *urlMatch, addr string) {
if _, err := db.conn.SAdd(m.RedisKey(), addr).Result(); err != nil {
panic("unable to SAdd for url: " + err.Error())
}
if _, err := db.conn.SAdd(m.id, m.RedisKey()).Result(); err != nil {
panic("unable to SAdd for id: " + err.Error())
}
}
func (db *DB) GetResultsForId(id string) (*LookUpResults, error) {
client := NewIpInfoClient(os.Getenv("DNS_LEAK_IP_INFO_KEY"))
results := &LookUpResults{Id: id}
keys, err := db.conn.SMembers(id).Result()
if err != nil {
return nil, errors.Wrap(err, "unable to get results for id")
}
var wg sync.WaitGroup
var m sync.Mutex
for _, key := range keys {
wg.Add(1)
go func(k string) {
defer wg.Done()
num, _ := strconv.Atoi(strings.Split(k, ".")[0])
keyResult := LookUpResult{Number: num}
addrs, err := db.conn.SMembers(key).Result()
if err != nil {
panic("unable to SMembers for key: " + err.Error())
}
for _, addr := range addrs {
res, err := client.LookUpIp(addr)
if err != nil {
logrus.WithError(err).Errorf("unable to lookup ip %s", addr)
res = nil // make sure it's nil
}
if res != nil && res.Bogon {
logrus.Warningf("bogon ip: %s", addr)
res = nil
}
keyResult.IPs = append(keyResult.IPs, LookUpResultIp{
Address: addr,
Info: res,
})
}
m.Lock()
results.Results = append(results.Results, keyResult)
m.Unlock()
}(key)
}
wg.Wait()
results.SortResults()
return results, nil
}