forked from folbricht/routedns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cidr-db.go
72 lines (64 loc) · 1.45 KB
/
cidr-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
package rdns
import (
"net"
"strings"
)
// CidrDB holds a list of IP networks that are used to block matching DNS responses.
// Network ranges are stored in a trie (one for IP4 and one for IP6) to allow for
// efficient matching
type CidrDB struct {
ip4, ip6 *ipBlocklistTrie
loader BlocklistLoader
}
var _ IPBlocklistDB = &CidrDB{}
// NewCidrDB returns a new instance of a matcher for a list of networks.
func NewCidrDB(loader BlocklistLoader) (*CidrDB, error) {
rules, err := loader.Load()
if err != nil {
return nil, err
}
db := &CidrDB{
ip4: new(ipBlocklistTrie),
ip6: new(ipBlocklistTrie),
loader: loader,
}
for _, r := range rules {
r = strings.TrimSpace(r)
if strings.HasPrefix(r, "#") || r == "" {
continue
}
// Append a mask suffix if there isn't one already
if !strings.Contains(r, "/") {
if strings.Contains(r, ".") { // ip4
r += "/32"
} else if strings.Contains(r, ":") { // ip6
r += "/128"
}
}
ip, n, err := net.ParseCIDR(r)
if err != nil {
return nil, err
}
if addr := ip.To4(); addr == nil {
db.ip6.add(n)
} else {
db.ip4.add(n)
}
}
return db, nil
}
func (m *CidrDB) Reload() (IPBlocklistDB, error) {
return NewCidrDB(m.loader)
}
func (m *CidrDB) Match(ip net.IP) (string, bool) {
if addr := ip.To4(); addr == nil {
return m.ip6.hasIP(ip)
}
return m.ip4.hasIP(ip)
}
func (m *CidrDB) Close() error {
return nil
}
func (m *CidrDB) String() string {
return "CIDR-blocklist"
}