Implement basic handlers (coredns / servicebackend)

This commit is contained in:
David Arnold 2020-06-03 11:25:04 -05:00
parent 501f1dbc75
commit fcaf7f1f81
No known key found for this signature in database
GPG Key ID: 6D6A936E69C59D08
3 changed files with 125 additions and 39 deletions

83
handler.go Normal file
View File

@ -0,0 +1,83 @@
package ldap
import (
"context"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
)
// ServeDNS implements the plugin.Handler interface.
func (l Ldap) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
opt := plugin.Options{}
state := request.Request{W: w, Req: r}
zone := plugin.Zones(l.Zones).Matches(state.Name())
if zone == "" {
return plugin.NextOrFailure(l.Name(), l.Next, ctx, w, r)
}
var (
records []dns.RR
extra []dns.RR
err error
)
switch state.QType() {
case dns.TypeA:
records, err = plugin.A(ctx, l, zone, state, nil, opt)
case dns.TypeAAAA:
records, err = plugin.AAAA(ctx, l, zone, state, nil, opt)
case dns.TypeTXT:
records, err = plugin.TXT(ctx, l, zone, state, nil, opt)
case dns.TypeCNAME:
records, err = plugin.CNAME(ctx, l, zone, state, opt)
case dns.TypePTR:
records, err = plugin.PTR(ctx, l, zone, state, opt)
case dns.TypeMX:
records, extra, err = plugin.MX(ctx, l, zone, state, opt)
case dns.TypeSRV:
records, extra, err = plugin.SRV(ctx, l, zone, state, opt)
case dns.TypeSOA:
records, err = plugin.SOA(ctx, l, zone, state, opt)
case dns.TypeNS:
if state.Name() == zone {
records, extra, err = plugin.NS(ctx, l, zone, state, opt)
break
}
fallthrough
default:
// Do a fake A lookup, so we can distinguish between NODATA and NXDOMAIN
_, err = plugin.A(ctx, l, zone, state, nil, opt)
}
if l.IsNameError(err) {
if l.Fall.Through(state.Name()) {
return plugin.NextOrFailure(l.Name(), l.Next, ctx, w, r)
}
// Make err nil when returning here, so we don't log spam for NXDOMAIN.
return plugin.BackendError(ctx, &l, zone, dns.RcodeNameError, state, nil /* err */, opt)
}
if err != nil {
return plugin.BackendError(ctx, &l, zone, dns.RcodeServerFailure, state, err, opt)
}
if len(records) == 0 {
return plugin.BackendError(ctx, &l, zone, dns.RcodeSuccess, state, err, opt)
}
m := new(dns.Msg)
m.SetReply(r)
m.Authoritative = true
m.Answer = append(m.Answer, records...)
m.Extra = append(m.Extra, extra...)
w.WriteMsg(m)
return dns.RcodeSuccess, nil
}
// Name implements the Handler interface.
func (l Ldap) Name() string { return "ldap" }

79
ldap.go
View File

@ -10,66 +10,71 @@ package ldap
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"net"
"io" "io"
"os" "os"
"github.com/coredns/coredns/plugin" "github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/metrics" "github.com/coredns/coredns/plugin/metrics"
clog "github.com/coredns/coredns/plugin/pkg/log" "github.com/coredns/coredns/plugin/pkg/fall"
"github.com/miekg/dns" "github.com/miekg/dns"
"gopkg.in/ldap.v2" "gopkg.in/ldap.v2"
) )
// Define log to be a logger with the plugin name in it. This way we can just use log.Info and
// friends to log.
var log = clog.NewWithPlugin("ldap")
// Ldap is an ldap plugin to serve zone entries from a ldap backend. // Ldap is an ldap plugin to serve zone entries from a ldap backend.
type Ldap struct { type Ldap struct {
Next plugin.Handler Next plugin.Handler
Fall fall.F
Zones []string
Client *ldap.Client
} }
// ServeDNS implements the plugin.Handler interface. This method gets called when ldap is used var (
// in a Server. errNoItems = errors.New("no items found")
func (l Ldap) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) { errNsNotExposed = errors.New("namespace is not exposed")
// This function could be simpler. I.e. just fmt.Println("ldap") here, but we want to show errInvalidRequest = errors.New("invalid query name")
// a slightly more complex ldap as to make this more interesting. )
// Here we wrap the dns.ResponseWriter in a new ResponseWriter and call the next plugin, when the
// answer comes back, it will print "ldap".
// Debug log that we've have seen the query. This will only be shown when the debug plugin is loaded. // Services implements the ServiceBackend interface.
log.Debug("Received response") func (l *Ldap) Services(ctx context.Context, state request.Request, exact bool, opt plugin.Options) (services []msg.Service, err error) {
services, err = l.Records(ctx, state, exact)
if err != nil {
return
}
// Wrap. services = msg.Group(services)
pw := NewResponsePrinter(w) return
// Export metric with the server label set to the current server handling the request.
requestCount.WithLabelValues(metrics.WithServer(ctx)).Inc()
// Call next plugin (if any).
return plugin.NextOrFailure(e.Name(), e.Next, ctx, pw, r)
} }
// Name implements the Handler interface. // Reverse implements the ServiceBackend interface.
func (l Ldap) Name() string { return "ldap" } func (l *Ldap) Reverse(ctx context.Context, state request.Request, exact bool, opt plugin.Options) (services []msg.Service, err error) {
return l.Services(ctx, state, exact, opt)
// ResponsePrinter wrap a dns.ResponseWriter and will write ldap to standard output when WriteMsg is called.
type ResponsePrinter struct {
dns.ResponseWriter
} }
// NewResponsePrinter returns ResponseWriter. // Lookup implements the ServiceBackend interface.
func NewResponsePrinter(w dns.ResponseWriter) *ResponsePrinter { func (l *Ldap) Lookup(ctx context.Context, state request.Request, name string, typ uint16) (*dns.Msg, error) {
return &ResponsePrinter{ResponseWriter: w} return l.Upstream.Lookup(ctx, state, name, typ)
} }
// WriteMsg calls the underlying ResponseWriter's WriteMsg method and prints "ldap" to standard output. // IsNameError implements the ServiceBackend interface.
func (r *ResponsePrinter) WriteMsg(res *dns.Msg) error { func (l *Ldap) IsNameError(err error) bool {
fmt.Fprintln(out, "ldap") return err == errNoItems || err == errNsNotExposed || err == errInvalidRequest
return r.ResponseWriter.WriteMsg(res)
} }
// Make out a reference to os.Stdout so we can easily overwrite it for testing. // Records looks up records in ldap. If exact is true, it will lookup just this
var out io.Writer = os.Stdout // name. This is used when find matches when completing SRV lookups for instance.
func (l *Ldap) Records(ctx context.Context, state request.Request, exact bool) ([]msg.Service, error) {
name := state.Name()
path, star := msg.PathWithWildcard(name, l.PathPrefix)
r, err := l.get(ctx, path, !exact)
if err != nil {
return nil, err
}
segments := strings.Split(msg.Path(name, l.PathPrefix), "/")
return l.loopNodes(r.Kvs, segments, star, state.QType())
}

View File

@ -1,7 +1,6 @@
package ldap package ldap
import ( import (
"sync"
"github.com/coredns/coredns/plugin" "github.com/coredns/coredns/plugin"
@ -16,4 +15,3 @@ var requestCount = prometheus.NewCounterVec(prometheus.CounterOpts{
Help: "Counter of requests made.", Help: "Counter of requests made.",
}, []string{"server"}) }, []string{"server"})
var once sync.Once