-
Notifications
You must be signed in to change notification settings - Fork 65
/
ip-blocklist-trie.go
117 lines (108 loc) · 2.34 KB
/
ip-blocklist-trie.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
package rdns
import "net"
// Datastructure for efficient search of a list of CIDR addresses to see if
// an IP is contained in one of the CIDR ranges in the list. While it uses
// ideas from routing table implementations as described in
// https://vincent.bernat.ch/en/blog/2017-ipv4-route-lookup-linux, it differs
// in that it looks for the shortest prefix (biggest network match) since
// it's sufficient to know if an IP is covered by one of the networks
type ipBlocklistTrie struct {
root *ipBlocklistNode
}
type ipBlocklistNode struct {
left, right *ipBlocklistNode
leaf bool
}
// Add a network to the trie.
func (t *ipBlocklistTrie) add(n *net.IPNet) {
if t.root == nil {
t.root = new(ipBlocklistNode)
}
prefix, _ := n.Mask.Size()
p := t.root
for i := 0; i < prefix; i++ {
if p.leaf { // stop if we already have a shorter prefix than this
break
}
b := bit(n.IP, i)
if b == 1 {
if p.right == nil {
p.right = new(ipBlocklistNode)
}
p = p.right
} else {
if p.left == nil {
p.left = new(ipBlocklistNode)
}
p = p.left
}
}
// Mark this as the leaf-node. We care about the shortest prefix
// so nothing should go past this when building the trie
p.left = nil
p.right = nil
p.leaf = true
}
// Returns true and the string representation of the network covering
// the IP.
func (t *ipBlocklistTrie) hasIP(ip net.IP) (string, bool) {
if t.root == nil {
return "", false
}
p := t.root
size := 32
if addr := ip.To4(); addr == nil {
size = 128
} else {
ip = addr // make sure we use the 4-byte representation of an IPv4
}
for i := 0; i < size; i++ {
if p.leaf {
return ruleString(ip, i), true
}
b := bit(ip, i)
if b == 1 {
if p.right == nil {
return "", false
}
p = p.right
} else {
if p.left == nil {
return "", false
}
p = p.left
}
}
return ruleString(ip, size), true
}
func ruleString(ip net.IP, maskBits int) string {
size := 32
if addr := ip.To4(); addr == nil {
size = 128
}
mask := net.CIDRMask(maskBits, size)
ipNet := &net.IPNet{
IP: ip.Mask(mask),
Mask: mask,
}
return ipNet.String()
}
var bitMask = []byte{
128,
64,
32,
16,
8,
4,
2,
1,
}
// Returns n'th bit from an IP address from the left.
func bit(ip net.IP, n int) int {
byteIndex := n / 8
bitIndex := n % 8
if (ip[byteIndex] & bitMask[bitIndex]) == 0 {
return 0
}
return 1
}