/
deleg.go
74 lines (59 loc) · 2.04 KB
/
deleg.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
package deleg
import (
"context"
"github.com/coredns/coredns/plugin"
"github.com/miekg/dns"
)
// Deleg is a plugin that implements https://github.com/fl1ger/deleg/blob/main/draft-dnsop-deleg.md
type Deleg struct {
Next plugin.Handler
delegs map[string][]dns.RR
}
// ServeDNS implements the plugin.Handler interface.
func (d Deleg) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
pw := NewResponsePrinter(w, d)
return plugin.NextOrFailure(d.Name(), d.Next, ctx, pw, r)
}
// Name implements the Handler interface.
func (d Deleg) Name() string { return "deleg" }
// ResponsePrinter wrap a dns.ResponseWriter and will write example to standard output when WriteMsg is called.
type ResponsePrinter struct {
dns.ResponseWriter
d Deleg
}
// NewResponsePrinter returns ResponseWriter.
func NewResponsePrinter(w dns.ResponseWriter, d Deleg) *ResponsePrinter {
return &ResponsePrinter{w, d}
}
// matches returns the list of responses for the given owner name.
// If there is no match, an empty list is returned.
func (d Deleg) matches(owner string) []dns.RR {
return d.delegs[dns.CanonicalName(owner)]
}
// WriteMsg calls the underlying ResponseWriter's WriteMsg method and prints "example" to standard output.
func (r *ResponsePrinter) WriteMsg(res *dns.Msg) error {
// Nothing to be done here.
if len(res.Ns) == 0 {
return r.ResponseWriter.WriteMsg(res)
}
for _, auth := range res.Ns {
owner := auth.Header().Name
rtype := auth.Header().Rrtype
// not an NS record, tentatively try the next records
if rtype != dns.TypeNS {
continue
}
responses := r.d.matches(owner)
//Let's assume that if there is a NS record, then there are all for the same owner name
// if there is no match, we can return without doing anything.
if len(responses) == 0 {
return r.ResponseWriter.WriteMsg(res)
}
// We have a matching zone, adding the RRs to the Auth section
res.Ns = append(res.Ns, responses...)
// and we are done.
break
}
// Following back to writing the original response
return r.ResponseWriter.WriteMsg(res)
}