-
Notifications
You must be signed in to change notification settings - Fork 63
/
static.go
95 lines (82 loc) · 2.31 KB
/
static.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
package rdns
import (
"github.com/miekg/dns"
)
// StaticResolver is a resolver that always returns the same answer, to any question.
// Typically used in combination with a blocklist to define fixed block responses or
// with a router when building a walled garden.
type StaticResolver struct {
id string
answer []dns.RR
ns []dns.RR
extra []dns.RR
rcode int
truncate bool
opt StaticResolverOptions
}
var _ Resolver = &StaticResolver{}
type StaticResolverOptions struct {
// Records in zone-file format
Answer []string
NS []string
Extra []string
RCode int
Truncate bool
// Optional, allows specifying extended errors to be used in the
// response when blocking.
EDNS0EDETemplate *EDNS0EDETemplate
}
// NewStaticResolver returns a new instance of a StaticResolver resolver.
func NewStaticResolver(id string, opt StaticResolverOptions) (*StaticResolver, error) {
r := &StaticResolver{id: id, opt: opt}
for _, record := range opt.Answer {
rr, err := dns.NewRR(record)
if err != nil {
return nil, err
}
r.answer = append(r.answer, rr)
}
for _, record := range opt.NS {
rr, err := dns.NewRR(record)
if err != nil {
return nil, err
}
r.ns = append(r.ns, rr)
}
for _, record := range opt.Extra {
rr, err := dns.NewRR(record)
if err != nil {
return nil, err
}
r.extra = append(r.extra, rr)
}
r.rcode = opt.RCode
r.truncate = opt.Truncate
return r, nil
}
// Resolve a DNS query by returning a fixed response.
func (r *StaticResolver) Resolve(q *dns.Msg, ci ClientInfo) (*dns.Msg, error) {
answer := new(dns.Msg)
answer.SetReply(q)
answer.RecursionAvailable = q.RecursionDesired
log := logger(r.id, q, ci)
// Update the name of every answer record to match that of the query
answer.Answer = make([]dns.RR, 0, len(r.answer))
for _, rr := range r.answer {
r := dns.Copy(rr)
r.Header().Name = qName(q)
answer.Answer = append(answer.Answer, r)
}
answer.Ns = r.ns
answer.Extra = r.extra
answer.Rcode = r.rcode
answer.Truncated = r.truncate
if err := r.opt.EDNS0EDETemplate.Apply(answer, EDNS0EDEInput{q, nil}); err != nil {
log.WithError(err).Error("failed to apply edns0ede template")
}
logger(r.id, q, ci).WithField("truncated", r.truncate).Debug("responding")
return answer, nil
}
func (r *StaticResolver) String() string {
return r.id
}