forked from folbricht/routedns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blocklistdb-regexp.go
57 lines (48 loc) · 1.2 KB
/
blocklistdb-regexp.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
package rdns
import (
"net"
"regexp"
"strings"
"github.com/miekg/dns"
)
// RegexpDB holds a list of regular expressions against which it evaluates DNS queries.
type RegexpDB struct {
name string
rules []*regexp.Regexp
loader BlocklistLoader
}
var _ BlocklistDB = &RegexpDB{}
// NewRegexpDB returns a new instance of a matcher for a list of regular expressions.
func NewRegexpDB(name string, loader BlocklistLoader) (*RegexpDB, error) {
rules, err := loader.Load()
if err != nil {
return nil, err
}
var filters []*regexp.Regexp
for _, r := range rules {
r = strings.TrimSpace(r)
if r == "" || strings.HasPrefix(r, "#") {
continue
}
re, err := regexp.Compile(r)
if err != nil {
return nil, err
}
filters = append(filters, re)
}
return &RegexpDB{name, filters, loader}, nil
}
func (m *RegexpDB) Reload() (BlocklistDB, error) {
return NewRegexpDB(m.name, m.loader)
}
func (m *RegexpDB) Match(q dns.Question) (net.IP, string, *BlocklistMatch, bool) {
for _, rule := range m.rules {
if rule.MatchString(q.Name) {
return nil, "", &BlocklistMatch{List: m.name, Rule: rule.String()}, true
}
}
return nil, "", nil, false
}
func (m *RegexpDB) String() string {
return "Regexp"
}