-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.go
97 lines (83 loc) · 2.04 KB
/
writer.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
package boost
import (
"github.com/coredns/coredns/plugin/pkg/response"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
"strings"
"time"
)
type ResponseWriter struct {
dns.ResponseWriter
state request.Request
*Boost
server string
}
func skip(m *dns.Msg) bool {
if m.Truncated || len(m.Question) > 1 {
return true
}
if mt, _ := response.Typify(m, time.Now().UTC()); mt != response.NoError {
return true
}
return false
}
func (w *ResponseWriter) Write(buf []byte) (int, error) {
log.Warning("boost called with Write(): not handling reply")
n, err := w.ResponseWriter.Write(buf)
return n, err
}
func (w *ResponseWriter) WriteMsg(res *dns.Msg) error {
skip := skip(res)
if skip {
return w.ResponseWriter.WriteMsg(res)
}
if w.Debug {
log.Debugf("original response:\n\t%s",strings.TrimSpace(strings.ReplaceAll(res.String(), "\n", "\n\t")))
}
answersMap := make(map[string]Ans)
for _, rr := range res.Answer {
switch rr.Header().Rrtype {
case dns.TypeA:
rr := rr.(*dns.A)
key := rr.A.String()
if ans, ok := answersMap[key]; !ok || ans.Header().Ttl < rr.Hdr.Ttl {
answersMap[key] = Ans{
IP: rr.A,
RR: rr,
}
}
case dns.TypeAAAA:
rr := rr.(*dns.AAAA)
key := rr.AAAA.String()
if ans, ok := answersMap[key]; !ok || ans.Header().Ttl < rr.Hdr.Ttl {
answersMap[key] = Ans{
IP: rr.AAAA,
RR: rr,
}
}
}
}
answers := make([]Ans, 0, len(answersMap))
for _, ans := range answersMap {
answers = append(answers, ans)
}
if w.Debug {
lines := make([]string, 0, len(answers))
for _, ans := range answers {
lines = append(lines, ans.RR.String())
}
log.Debug("collected answers:\n\t" + strings.Join(lines, "\n\t"))
}
if len(answers) > 0 {
var best Ans
ok := methods[w.Boost.Method](w.Boost, answers, &best)
if ok {
best.RR.Header().Name = res.Question[0].Name
res.Answer = []dns.RR{best.RR}
}
}
if w.Debug {
log.Debug("final response:\n\t" + strings.ReplaceAll(strings.TrimSpace(res.String()), "\n", "\n\t"))
}
return w.ResponseWriter.WriteMsg(res)
}