-
Notifications
You must be signed in to change notification settings - Fork 17
/
fallback.go
84 lines (70 loc) · 2.54 KB
/
fallback.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
// Package fallback implements a fallback plugin for CoreDNS
package fallback
import (
"golang.org/x/net/context"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/pkg/nonwriter"
"github.com/coredns/proxy"
"fmt"
"github.com/miekg/dns"
)
// Fallback plugin allows an alternate set of upstreams be specified which will be used
// if the plugin chain returns specific error messages.
type Fallback struct {
Next plugin.Handler
trace plugin.Handler
rules map[int]rule
original bool // At least one rule has "original" flag
proxy proxyCreator
}
type rule struct {
original bool
proxyUpstream proxy.Upstream
}
// proxyCreator creates a proxy with the specified upstream.
type proxyCreator interface {
New(trace plugin.Handler, upstream proxy.Upstream) plugin.Handler
}
// fallbackProxyCreator implements the proxyCreator interface
// Used by the fallback plugin to create proxy using specified for upstream.
type fallbackProxyCreator struct{}
func (f fallbackProxyCreator) New(trace plugin.Handler, upstream proxy.Upstream) plugin.Handler {
return &proxy.Proxy{Trace: trace, Upstreams: &[]proxy.Upstream{upstream}}
}
func New(trace plugin.Handler) (f *Fallback) {
return &Fallback{trace: trace, rules: make(map[int]rule), proxy: fallbackProxyCreator{}}
}
// ServeDNS implements the plugin.Handler interface.
func (f Fallback) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
// If fallback has original option set for any code then copy original request to use it instead of changed
var originalRequest *dns.Msg
if f.original {
originalRequest = r.Copy()
}
nw := nonwriter.New(w)
rcode, err := plugin.NextOrFailure(f.Name(), f.Next, ctx, nw, r)
//By default the rules_index is equal rcode, so in such way we handle the case
//when rcode is SERVFAIL and nw.Msg is nil, otherwise we use nw.Msg.Rcode
//because, for example, for the following cases like NXDOMAIN, REFUSED the rcode is 0 (returned by proxy)
//A proxy doesn't return 0 only in case SERVFAIL
rules_index := rcode
if nw.Msg != nil {
rules_index = nw.Msg.Rcode
}
if u, ok := f.rules[rules_index]; ok {
p := f.proxy.New(f.trace, u.proxyUpstream)
if p == nil {
return dns.RcodeServerFailure, fmt.Errorf("cannot create fallback proxy")
}
if u.original && originalRequest != nil {
return p.ServeDNS(ctx, w, originalRequest)
}
return p.ServeDNS(ctx, w, r)
}
if nw.Msg != nil {
w.WriteMsg(nw.Msg)
}
return rcode, err
}
// Name implements the Handler interface.
func (f Fallback) Name() string { return "fallback" }