-
Notifications
You must be signed in to change notification settings - Fork 0
/
oneaddr.go
78 lines (64 loc) · 1.77 KB
/
oneaddr.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
// Package oneaddr is a plugin for rewriting responses to retain only single address
package oneaddr
import (
"strings"
"github.com/miekg/dns"
)
type dedupKey struct {
name string
rrtype uint16
class uint16
}
type dedupSet = map[dedupKey]struct{}
func makeDedupKey(rec dns.RR) dedupKey {
hdr := rec.Header()
return dedupKey{
name: strings.ToLower(hdr.Name),
rrtype: hdr.Rrtype,
class: hdr.Class,
}
}
// OneAddrResponseWriter is a response writer that shuffles A, AAAA and MX records.
type OneAddrResponseWriter struct {
dns.ResponseWriter
}
// WriteMsg implements the dns.ResponseWriter interface.
func (r *OneAddrResponseWriter) WriteMsg(res *dns.Msg) error {
if res.Rcode != dns.RcodeSuccess {
return r.ResponseWriter.WriteMsg(res)
}
if res.Question[0].Qtype == dns.TypeAXFR || res.Question[0].Qtype == dns.TypeIXFR {
return r.ResponseWriter.WriteMsg(res)
}
if res.Question[0].Qtype != dns.TypeA && res.Question[0].Qtype != dns.TypeAAAA {
return r.ResponseWriter.WriteMsg(res)
}
res.Answer = trimRecords(res.Answer)
res.Extra = trimRecords(res.Extra)
return r.ResponseWriter.WriteMsg(res)
}
func trimRecords(in []dns.RR) []dns.RR {
seen := make(dedupSet)
out := []dns.RR{}
for _, rec := range in {
switch rec.Header().Rrtype {
case dns.TypeA, dns.TypeAAAA:
key := makeDedupKey(rec)
if _, ok := seen[key]; ok {
continue
}
seen[key] = struct{}{}
fallthrough
default:
out = append(out, rec)
}
}
return out
}
// Write implements the dns.ResponseWriter interface.
func (r *OneAddrResponseWriter) Write(buf []byte) (int, error) {
// Should we pack and unpack here to fiddle with the packet... Not likely.
log.Warning("oneaddr plugin called with Write: not shuffling records")
n, err := r.ResponseWriter.Write(buf)
return n, err
}