-
Notifications
You must be signed in to change notification settings - Fork 17
/
filter.go
71 lines (60 loc) · 1.61 KB
/
filter.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
package main
import (
"strings"
"github.com/miekg/dns"
)
type QueryFilter struct {
domain string
qTypes []string
}
type QueryFilterer struct {
acceptFilters []QueryFilter
rejectFilters []QueryFilter
}
// Matches returns true if the given DNS query matches the filter
func (f *QueryFilter) Matches(req *dns.Msg) bool {
queryDomain := req.Question[0].Name
queryQType := dns.TypeToString[req.Question[0].Qtype]
if len(queryDomain) > 0 && !strings.HasSuffix(queryDomain, f.domain) {
debugMsg("Domain match failed (" + queryDomain + ", " + f.domain + ")")
return false
}
matches := false
if len(f.qTypes) > 0 {
for _, qType := range f.qTypes {
if qType == queryQType {
matches = true
}
}
} else {
matches = true
}
return matches
}
// ShouldAcceptQuery returns true if the given DNS query matches the given
// accept/reject filters, and should be accepted.
func (f *QueryFilterer) ShouldAcceptQuery(req *dns.Msg) bool {
accepted := true
for _, filter := range f.rejectFilters {
filterDescription := "Filter " + filter.domain + ":" + strings.Join(filter.qTypes, ",")
if filter.Matches(req) {
debugMsg(filterDescription + " rejected")
accepted = false
break
}
debugMsg(filterDescription + " not rejected")
}
if accepted && len(f.acceptFilters) > 0 {
accepted = false
for _, filter := range f.acceptFilters {
filterDescription := "Filter " + filter.domain + ":" + strings.Join(filter.qTypes, ",")
if filter.Matches(req) {
debugMsg(filterDescription + " accepted")
accepted = true
break
}
debugMsg(filterDescription + " not accepted")
}
}
return accepted
}