-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathfinalize.go
More file actions
223 lines (191 loc) · 6 KB
/
finalize.go
File metadata and controls
223 lines (191 loc) · 6 KB
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package finalize
import (
"context"
"fmt"
"time"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/metrics"
clog "github.com/coredns/coredns/plugin/pkg/log"
"github.com/coredns/coredns/plugin/pkg/nonwriter"
"github.com/coredns/coredns/plugin/pkg/upstream"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
)
var log = clog.NewWithPlugin("finalize")
// Rewrite is plugin to rewrite requests internally before being handled.
type Finalize struct {
Next plugin.Handler
upstream *upstream.Upstream
maxDepth int
forceResolve bool
}
func New() *Finalize {
s := &Finalize{
upstream: upstream.New(),
maxDepth: 0,
}
return s
}
type FinalizeLoopKey struct{}
func minTTL(rrs []dns.RR, currentMin uint32) uint32 {
min := currentMin
for _, rr := range rrs {
ttl := rr.Header().Ttl
if min == 0 || ttl < min {
min = ttl
}
}
return min
}
// ServeDNS implements the plugin.Handler interface.
func (s *Finalize) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
qname := ""
qtype := uint16(0)
if r != nil && len(r.Question) > 0 {
qname = r.Question[0].Name
qtype = r.Question[0].Qtype
}
log.Debugf("ServeDNS query name=%s type=%s force_resolve=%t max_depth=%d", qname, dns.Type(qtype).String(), s.forceResolve, s.maxDepth)
req := r.Copy()
origName := ""
if len(req.Question) > 0 {
origName = req.Question[0].Name
}
nw := nonwriter.New(w)
rcode, err := plugin.NextOrFailure(s.Name(), s.Next, ctx, nw, r)
if err != nil {
return rcode, err
}
r = nw.Msg
if r == nil {
return 1, fmt.Errorf("no answer received")
}
log.Debugf("Upstream response rcode=%s answers=%d", dns.RcodeToString[r.Rcode], len(r.Answer))
if len(r.Question) > 0 && r.Question[0].Qtype == dns.TypeCNAME {
log.Debug("Request is a CNAME type question, skipping")
if err := w.WriteMsg(r); err != nil {
return 1, err
}
return 0, nil
}
if len(r.Answer) > 0 && r.Answer[0].Header().Rrtype == dns.TypeCNAME {
log.Debugf("Finalizing CNAME for request: %+v", r)
requestCount.WithLabelValues(metrics.WithServer(ctx)).Inc()
defer recordDuration(ctx, time.Now())
state := request.Request{W: w, Req: req}
// emulate hashset in go; https://emersion.fr/blog/2017/sets-in-go/
cnameVisited := make(map[string]struct{})
cnt := 0
rr := r.Answer[0]
answers := []dns.RR{}
success := true
minTTLSeen := minTTL(r.Answer, 0)
resolveCname:
target := rr.(*dns.CNAME).Target
cnameTTL := rr.Header().Ttl
if cnameTTL < minTTLSeen {
minTTLSeen = cnameTTL
}
if origName == "" {
origName = target
}
log.Debugf("Trying to resolve CNAME target=%s type=%s", target, dns.Type(state.QType()).String())
if s.maxDepth > 0 && cnt >= s.maxDepth {
maxDepthReachedCount.WithLabelValues(metrics.WithServer(ctx)).Inc()
log.Errorf("Max depth %d reached for resolving CNAME records", s.maxDepth)
} else if _, ok := cnameVisited[target]; ok {
circularReferenceCount.WithLabelValues(metrics.WithServer(ctx)).Inc()
log.Errorf("Detected circular reference in CNAME chain. CNAME [%s] already processed", target)
} else {
terminal := terminalAnswers(r.Answer)
if len(terminal) > 0 && !s.forceResolve {
log.Debugf("Using terminal A/AAAA from original answer count=%d", len(terminal))
minTTLSeen = minTTL(r.Answer, minTTLSeen)
answers = append(answers, flattenAnswers(terminal, origName, minTTLSeen)...)
} else {
if len(terminal) > 0 && s.forceResolve {
log.Debugf("force_resolve enabled; ignoring terminal A/AAAA in original answer count=%d", len(terminal))
}
up, err := s.upstream.Lookup(ctx, state, target, state.QType())
if err != nil {
upstreamErrorCount.WithLabelValues(metrics.WithServer(ctx)).Inc()
success = false
log.Errorf("Failed to lookup CNAME [%+v] from upstream: [%+v]", rr, err)
} else {
ansCount := 0
if up.Answer != nil {
ansCount = len(up.Answer)
}
log.Debugf("Lookup response rcode=%s answers=%d", dns.RcodeToString[up.Rcode], ansCount)
if len(up.Answer) == 0 {
danglingCNameCount.WithLabelValues(metrics.WithServer(ctx)).Inc()
success = false
log.Errorf("Received no answer from upstream: [%+v]", up)
} else {
rr = up.Answer[0]
minTTLSeen = minTTL(up.Answer, minTTLSeen)
switch rr.Header().Rrtype {
case dns.TypeCNAME:
cnt++
cnameVisited[target] = struct{}{}
goto resolveCname
case dns.TypeA:
fallthrough
case dns.TypeAAAA:
answers = append(answers, flattenAnswers(up.Answer, origName, minTTLSeen)...)
default:
log.Errorf("Upstream server returned unsupported type [%+v] for CNAME question [%+v]", rr, up.Question[0])
success = false
}
}
}
}
}
if success && len(answers) > 0 {
log.Debugf("Finalized answer count=%d name=%s", len(answers), origName)
r.Answer = answers
} else if !success {
log.Debugf("Finalization failed; returning original answer")
} else {
log.Debugf("Finalization produced no answers; returning original answer")
}
} else {
log.Debug("Request didn't contain any answer or no CNAME")
}
err = w.WriteMsg(r)
if err != nil {
return 1, err
}
return 0, nil
}
// Name implements the Handler interface.
func (al *Finalize) Name() string { return "finalize" }
func terminalAnswers(rrs []dns.RR) []dns.RR {
terminal := make([]dns.RR, 0, len(rrs))
for _, rr := range rrs {
switch rr.Header().Rrtype {
case dns.TypeA, dns.TypeAAAA:
terminal = append(terminal, rr)
}
}
return terminal
}
func flattenAnswers(rrs []dns.RR, name string, ttl uint32) []dns.RR {
flattened := make([]dns.RR, 0, len(rrs))
for _, rr := range rrs {
switch rr.Header().Rrtype {
case dns.TypeA, dns.TypeAAAA:
copied := dns.Copy(rr)
copied.Header().Name = name
if ttl > 0 {
copied.Header().Ttl = ttl
}
flattened = append(flattened, copied)
}
}
return flattened
}
func recordDuration(ctx context.Context, start time.Time) {
requestDuration.WithLabelValues(metrics.WithServer(ctx)).
Observe(time.Since(start).Seconds())
}