-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.go
83 lines (68 loc) · 1.97 KB
/
plugin.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
package epicmdns
import (
"context"
"strings"
"github.com/coredns/coredns/plugin"
"github.com/miekg/dns"
clog "github.com/coredns/coredns/plugin/pkg/log"
)
var log = clog.NewWithPlugin("epicmdns")
type mdnsclient interface {
Query(ctx context.Context, questions ...dns.Question) ([]dns.RR, error)
}
type mdnsPlugin struct {
mdns mdnsclient
Next plugin.Handler
domain string
}
func (p mdnsPlugin) Name() string { return "epicmdns" }
func (p mdnsPlugin) ToLocal(input string) string {
// Replace input domain with .local
return strings.TrimSuffix(input, p.domain) + "local."
}
func (p mdnsPlugin) FromLocal(local string) string {
// Replace .local to our domain
return strings.TrimSuffix(local, "local.") + p.domain
}
func (p mdnsPlugin) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
msg := new(dns.Msg)
msg.SetReply(r)
msg.Authoritative = true
msg.RecursionAvailable = true
name := r.Question[0].Name
log.Debugf("Looking for name: %s", name)
if !strings.HasSuffix(name, p.domain) {
log.Debugf("Ignoring %q not in configured domain %q", name, p.domain)
return plugin.NextOrFailure(p.Name(), p.Next, ctx, w, r)
}
// Translate questions to `.local` domain:
questions := make([]dns.Question, len(r.Question))
for i, q := range r.Question {
questions[i] = dns.Question{
Name: p.ToLocal(q.Name),
Qtype: q.Qtype,
Qclass: q.Qclass,
}
}
// query mDNS
answers, err := p.mdns.Query(ctx, questions...)
if err != nil {
log.Debugf("Error looking up %s: %s", name, err)
return plugin.NextOrFailure(p.Name(), p.Next, ctx, w, r)
}
// map responses to configured domain:
for _, ans := range answers {
ans.Header().Name = p.FromLocal(ans.Header().Name)
switch r := ans.(type) {
case *dns.CNAME:
r.Target = p.FromLocal(r.Target)
case *dns.PTR:
r.Ptr = p.FromLocal(r.Ptr)
case *dns.SRV:
r.Target = p.FromLocal(r.Target)
}
}
// return to CoreDNS
msg.Answer = answers
return dns.RcodeSuccess, w.WriteMsg(msg)
}