-
Notifications
You must be signed in to change notification settings - Fork 62
/
cidr-db.go
76 lines (68 loc) · 1.63 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
73
74
75
76
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 {
name string
ip4, ip6 *ipBlocklistTrie
loader BlocklistLoader
}
var _ IPBlocklistDB = &CidrDB{}
// NewCidrDB returns a new instance of a matcher for a list of networks.
func NewCidrDB(name string, loader BlocklistLoader) (*CidrDB, error) {
rules, err := loader.Load()
if err != nil {
return nil, err
}
db := &CidrDB{
name: name,
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.name, m.loader)
}
func (m *CidrDB) Match(ip net.IP) (*BlocklistMatch, bool) {
if addr := ip.To4(); addr == nil {
rule, ok := m.ip6.hasIP(ip)
return &BlocklistMatch{List: m.name, Rule: rule}, ok
}
rule, ok := m.ip4.hasIP(ip)
return &BlocklistMatch{List: m.name, Rule: rule}, ok
}
func (m *CidrDB) Close() error {
return nil
}
func (m *CidrDB) String() string {
return "CIDR-blocklist"
}