dns/server.go

426 lines
11 KiB
Go
Raw Normal View History

2011-02-08 20:25:01 +00:00
// Copyright 2011 Miek Gieben. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// DNS server implementation.
2011-02-08 20:25:01 +00:00
package dns
2011-02-08 20:25:01 +00:00
import (
2012-08-08 09:13:28 +00:00
"github.com/miekg/radix"
2011-04-03 09:49:23 +00:00
"io"
2011-02-08 20:25:01 +00:00
"net"
2012-01-20 11:16:32 +00:00
"time"
2011-02-08 20:25:01 +00:00
)
2011-04-01 11:15:36 +00:00
type Handler interface {
2011-04-03 09:49:23 +00:00
ServeDNS(w ResponseWriter, r *Msg)
2011-04-01 11:15:36 +00:00
}
2011-04-03 09:14:54 +00:00
// A ResponseWriter interface is used by an DNS handler to
// construct an DNS response.
2011-04-02 07:22:05 +00:00
type ResponseWriter interface {
2011-07-05 19:08:22 +00:00
// RemoteAddr returns the net.Addr of the client that sent the current request.
2011-07-05 17:17:29 +00:00
RemoteAddr() net.Addr
2012-08-21 15:36:58 +00:00
// TsigStatus returns the status of the Tsig.
TsigStatus() error
2012-02-26 19:09:03 +00:00
// Write writes a reply back to the client.
Write(*Msg) error
2012-08-05 19:15:15 +00:00
// WriteBuf writes a raw buffer back to the client.
WriteBuf([]byte) error
2011-04-02 07:22:05 +00:00
}
type conn struct {
2012-05-08 12:17:17 +00:00
remoteAddr net.Addr // address of the client
2012-02-26 21:02:55 +00:00
handler Handler // request handler
request []byte // bytes read
_UDP *net.UDPConn // i/o connection if UDP was used
_TCP *net.TCPConn // i/o connection if TCP was used
hijacked bool // connection has been hijacked by hander TODO(mg)
tsigSecret map[string]string // the tsig secrets
2011-04-02 07:22:05 +00:00
}
2011-04-01 08:53:31 +00:00
2011-04-02 07:22:05 +00:00
type response struct {
conn *conn
tsigStatus error
tsigTimersOnly bool
tsigRequestMAC string
2011-04-01 08:53:31 +00:00
}
2011-04-01 11:15:36 +00:00
// ServeMux is an DNS request multiplexer. It matches the
// zone name of each incoming request against a list of
// registered patterns add calls the handler for the pattern
2012-08-05 06:55:25 +00:00
// that most closely matches the zone name. ServeMux is DNSSEC aware, meaning
// that queries for the DS record are redirected to the parent zone (if that
2012-08-08 07:26:29 +00:00
// is also registered), otherwise the child gets the query.
2011-04-01 11:15:36 +00:00
type ServeMux struct {
2012-08-05 05:43:13 +00:00
m *radix.Radix
2011-04-01 11:15:36 +00:00
}
2011-04-02 07:22:05 +00:00
// NewServeMux allocates and returns a new ServeMux.
2012-08-05 05:43:13 +00:00
func NewServeMux() *ServeMux { return &ServeMux{m: radix.New()} }
2011-04-01 11:15:36 +00:00
2011-04-02 07:22:05 +00:00
// DefaultServeMux is the default ServeMux used by Serve.
var DefaultServeMux = NewServeMux()
2011-04-01 11:15:36 +00:00
2011-04-02 07:22:05 +00:00
// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as DNS handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler object that calls f.
type HandlerFunc func(ResponseWriter, *Msg)
2011-04-01 11:15:36 +00:00
2011-07-05 19:08:22 +00:00
// ServerDNS calls f(w, r)
2011-04-02 07:22:05 +00:00
func (f HandlerFunc) ServeDNS(w ResponseWriter, r *Msg) {
2011-04-03 09:49:23 +00:00
f(w, r)
2011-04-01 11:15:36 +00:00
}
// Failed is a helper handler that returns an answer with
// RCODE = servfail for every request.
func Failed(w ResponseWriter, r *Msg) {
2011-04-18 20:08:12 +00:00
m := new(Msg)
m.SetRcode(r, RcodeServerFailure)
w.Write(m)
2011-04-03 11:43:46 +00:00
}
2011-04-01 11:15:36 +00:00
// FailedHandler returns HandlerFunc with Failed.
func FailedHandler() Handler { return HandlerFunc(Failed) }
2011-04-01 08:53:31 +00:00
2012-02-12 10:37:52 +00:00
// Start a server on addresss and network speficied. Invoke handler
// for any incoming queries.
func ListenAndServe(addr string, network string, handler Handler) error {
server := &Server{Addr: addr, Net: network, Handler: handler}
2011-04-03 09:49:23 +00:00
return server.ListenAndServe()
2011-04-02 07:22:05 +00:00
}
2012-08-05 03:35:30 +00:00
func (mux *ServeMux) match(zone string, t uint16) Handler {
2012-08-05 06:13:09 +00:00
zone = toRadixName(zone)
if h := mux.m.Find(zone); h != nil && h.Value != nil {
2012-08-05 06:55:25 +00:00
// If we got queried for a DS record, we must see if we
// if we also serve the parent. We then redirect it.
if t == TypeDS {
if d := h.Up(); d != nil {
return d.Value.(Handler)
}
}
2012-08-05 05:43:13 +00:00
return h.Value.(Handler)
2011-04-03 09:49:23 +00:00
}
2012-08-05 07:10:07 +00:00
// Best matching one.
2012-08-05 06:13:09 +00:00
if h := mux.m.Predecessor(zone); h != nil && h.Value != nil {
2012-08-05 05:43:13 +00:00
return h.Value.(Handler)
2012-08-05 03:35:30 +00:00
}
2012-08-05 05:43:13 +00:00
return nil
2011-04-01 11:15:36 +00:00
}
2012-05-08 12:17:17 +00:00
// Handle adds a handler to the ServeMux for pattern.
2011-04-01 11:15:36 +00:00
func (mux *ServeMux) Handle(pattern string, handler Handler) {
2011-04-03 09:49:23 +00:00
if pattern == "" {
panic("dns: invalid pattern " + pattern)
}
2012-08-05 06:13:09 +00:00
mux.m.Insert(toRadixName(Fqdn(pattern)), handler)
2011-04-01 11:15:36 +00:00
}
2011-04-02 07:22:05 +00:00
2012-05-08 12:17:17 +00:00
// Handle adds a handler to the ServeMux for pattern.
2011-04-02 07:22:05 +00:00
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Msg)) {
2011-04-03 09:49:23 +00:00
mux.Handle(pattern, HandlerFunc(handler))
2011-04-02 07:22:05 +00:00
}
2012-05-08 12:17:17 +00:00
// HandleRemove deregistrars the handler specific for pattern from the ServeMux.
func (mux *ServeMux) HandleRemove(pattern string) {
if pattern == "" {
panic("dns: invalid pattern " + pattern)
}
// if its there, its gone
2012-08-05 06:13:09 +00:00
mux.m.Remove(toRadixName(Fqdn(pattern)))
}
2011-04-02 07:22:05 +00:00
// ServeDNS dispatches the request to the handler whose
2012-08-03 16:28:00 +00:00
// pattern most closely matches the request message. For DS queries
// a parent zone is sought.
// If no handler is found a standard SERVFAIL message is returned
2011-04-02 07:22:05 +00:00
func (mux *ServeMux) ServeDNS(w ResponseWriter, request *Msg) {
var h Handler
if len(request.Question) != 1 {
2012-08-28 11:30:59 +00:00
h = FailedHandler()
} else {
2012-08-28 11:30:59 +00:00
if h = mux.match(request.Question[0].Name, request.Question[0].Qtype); h == nil {
h = FailedHandler()
}
2011-04-03 09:49:23 +00:00
}
h.ServeDNS(w, request)
2011-04-02 07:22:05 +00:00
}
// Handle registers the handler with the given pattern
2011-04-02 07:22:05 +00:00
// in the DefaultServeMux. The documentation for
2012-08-24 13:20:20 +00:00
// ServeMux explains how patterns are matched.
2011-04-02 07:22:05 +00:00
func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }
// HandleRemove deregisters the handle with the given pattern
// in the DefaultServeMux.
func HandleRemove(pattern string) { DefaultServeMux.HandleRemove(pattern) }
2012-08-24 13:20:20 +00:00
// HandleFunc registers the handler function with the given pattern
// in the DefaultServeMux.
2011-04-02 07:22:05 +00:00
func HandleFunc(pattern string, handler func(ResponseWriter, *Msg)) {
2011-04-03 09:49:23 +00:00
DefaultServeMux.HandleFunc(pattern, handler)
2011-04-02 07:22:05 +00:00
}
2011-04-12 19:44:56 +00:00
// A Server defines parameters for running an DNS server.
type Server struct {
2011-07-23 21:43:43 +00:00
Addr string // address to listen on, ":dns" if empty
Net string // if "tcp" it will invoke a TCP listener, otherwise an UDP one
Handler Handler // handler to invoke, dns.DefaultServeMux if nil
2012-08-21 15:36:58 +00:00
UDPSize int // default buffer size to use to read incoming UDP messages
2012-01-20 11:24:20 +00:00
ReadTimeout time.Duration // the net.Conn.SetReadTimeout value for new connections
WriteTimeout time.Duration // the net.Conn.SetWriteTimeout value for new connections
2011-07-23 21:43:43 +00:00
TsigSecret map[string]string // secret(s) for Tsig map[<zonename>]<base64 secret>
2011-04-12 19:44:56 +00:00
}
2012-05-08 12:17:17 +00:00
// ListenAndServe starts a nameserver on the configured address in *Server.
2011-11-02 22:06:54 +00:00
func (srv *Server) ListenAndServe() error {
2011-04-03 09:49:23 +00:00
addr := srv.Addr
if addr == "" {
addr = ":domain"
}
2011-04-18 20:08:12 +00:00
switch srv.Net {
2011-07-05 17:44:46 +00:00
case "tcp", "tcp4", "tcp6":
a, e := net.ResolveTCPAddr(srv.Net, addr)
2011-04-03 09:49:23 +00:00
if e != nil {
return e
}
2011-07-05 17:44:46 +00:00
l, e := net.ListenTCP(srv.Net, a)
2011-04-03 09:49:23 +00:00
if e != nil {
return e
}
return srv.ServeTCP(l)
2011-07-05 17:44:46 +00:00
case "udp", "udp4", "udp6":
a, e := net.ResolveUDPAddr(srv.Net, addr)
2011-04-03 09:49:23 +00:00
if e != nil {
return e
}
2011-07-05 17:44:46 +00:00
l, e := net.ListenUDP(srv.Net, a)
2011-04-03 09:49:23 +00:00
if e != nil {
return e
}
return srv.ServeUDP(l)
}
2012-02-26 21:02:55 +00:00
return &Error{Err: "bad network"}
2011-04-02 07:22:05 +00:00
}
2012-02-15 12:16:09 +00:00
// ServeTCP starts a TCP listener for the server.
// Each request is handled in a seperate goroutine.
2011-11-02 22:06:54 +00:00
func (srv *Server) ServeTCP(l *net.TCPListener) error {
2011-04-03 09:49:23 +00:00
defer l.Close()
handler := srv.Handler
if handler == nil {
handler = DefaultServeMux
}
forever:
for {
rw, e := l.AcceptTCP()
if e != nil {
// don't bail out, but wait for a new request
continue
2011-04-03 09:49:23 +00:00
}
if srv.ReadTimeout != 0 {
2012-01-20 11:16:32 +00:00
rw.SetReadDeadline(time.Now().Add(srv.ReadTimeout))
2011-04-03 09:49:23 +00:00
}
if srv.WriteTimeout != 0 {
2012-01-20 11:16:32 +00:00
rw.SetWriteDeadline(time.Now().Add(srv.WriteTimeout))
2011-04-03 09:49:23 +00:00
}
l := make([]byte, 2)
n, err := rw.Read(l)
if err != nil || n != 2 {
continue
}
length, _ := unpackUint16(l, 0)
if length == 0 {
continue
}
m := make([]byte, int(length))
n, err = rw.Read(m[:int(length)])
if err != nil || n == 0 {
2011-04-03 09:49:23 +00:00
continue
}
i := n
for i < int(length) {
j, err := rw.Read(m[i:int(length)])
if err != nil {
continue forever
}
i += j
}
n = i
2012-02-26 21:02:55 +00:00
d, err := newConn(rw, nil, rw.RemoteAddr(), m, handler, srv.TsigSecret)
2011-04-03 09:49:23 +00:00
if err != nil {
continue
}
go d.serve()
}
panic("dns: not reached")
2011-04-02 07:22:05 +00:00
}
2012-02-15 12:16:09 +00:00
// ServeUDP starts a UDP listener for the server.
2012-08-21 14:52:36 +00:00
// Each request is handled in a seperate goroutine.
2011-11-02 22:06:54 +00:00
func (srv *Server) ServeUDP(l *net.UDPConn) error {
2011-04-03 09:49:23 +00:00
defer l.Close()
handler := srv.Handler
if handler == nil {
handler = DefaultServeMux
}
2012-01-12 21:47:36 +00:00
if srv.UDPSize == 0 {
2012-08-17 06:31:38 +00:00
srv.UDPSize = udpMsgSize
2012-01-12 21:47:36 +00:00
}
2011-04-03 09:49:23 +00:00
for {
2012-01-12 21:34:53 +00:00
m := make([]byte, srv.UDPSize)
2011-04-03 09:49:23 +00:00
n, a, e := l.ReadFromUDP(m)
if e != nil || n == 0 {
// don't bail out, but wait for a new request
continue
2011-04-03 09:49:23 +00:00
}
m = m[:n]
2011-04-02 07:22:05 +00:00
2011-04-03 09:49:23 +00:00
if srv.ReadTimeout != 0 {
2012-01-20 11:16:32 +00:00
l.SetReadDeadline(time.Now().Add(srv.ReadTimeout))
2011-04-03 09:49:23 +00:00
}
if srv.WriteTimeout != 0 {
2012-01-20 11:16:32 +00:00
l.SetWriteDeadline(time.Now().Add(srv.WriteTimeout))
2011-04-03 09:49:23 +00:00
}
2012-02-26 21:02:55 +00:00
d, err := newConn(nil, l, a, m, handler, srv.TsigSecret)
2011-04-03 09:49:23 +00:00
if err != nil {
continue
}
go d.serve()
}
panic("dns: not reached")
2011-04-02 07:22:05 +00:00
}
2012-02-26 21:02:55 +00:00
func newConn(t *net.TCPConn, u *net.UDPConn, a net.Addr, buf []byte, handler Handler, tsig map[string]string) (*conn, error) {
2011-04-03 11:16:33 +00:00
c := new(conn)
2011-04-03 09:49:23 +00:00
c.handler = handler
c._TCP = t
c._UDP = u
c.remoteAddr = a
c.request = buf
2012-02-26 21:02:55 +00:00
c.tsigSecret = tsig
2011-04-03 11:16:33 +00:00
return c, nil
2011-04-02 07:22:05 +00:00
}
2011-04-03 09:14:54 +00:00
// Close the connection.
func (c *conn) close() {
2011-04-03 09:49:23 +00:00
switch {
case c._UDP != nil:
c._UDP.Close()
c._UDP = nil
case c._TCP != nil:
c._TCP.Close()
c._TCP = nil
}
2011-04-03 09:14:54 +00:00
}
// Serve a new connection.
2011-04-02 07:22:05 +00:00
func (c *conn) serve() {
2012-08-24 03:21:33 +00:00
// for block to make it easy to break out to close the tcp connection
2011-04-18 20:08:12 +00:00
for {
// Request has been read in ServeUDP or ServeTCP
w := new(response)
w.conn = c
req := new(Msg)
if !req.Unpack(c.request) {
2011-11-02 22:06:54 +00:00
// Send a format error back
x := new(Msg)
x.SetRcodeFormatError(req)
w.Write(x)
2011-04-18 20:08:12 +00:00
break
}
w.tsigStatus = nil
if t := req.IsTsig(); t != nil {
secret := t.Hdr.Name
if _, ok := w.conn.tsigSecret[secret]; !ok {
w.tsigStatus = ErrKeyAlg
}
w.tsigStatus = TsigVerify(c.request, w.conn.tsigSecret[secret], "", false)
w.tsigTimersOnly = false // Will this ever be true?
w.tsigRequestMAC = req.Extra[len(req.Extra)-1].(*RR_TSIG).MAC
}
2012-08-30 07:34:40 +00:00
c.handler.ServeDNS(w, req) // this does the writing back to the client
2011-04-18 20:08:12 +00:00
if c.hijacked {
return
}
2012-08-24 03:21:33 +00:00
break
2011-04-18 20:08:12 +00:00
}
if c._TCP != nil {
c.close() // Listen and Serve is closed then
}
2011-04-02 07:22:05 +00:00
}
2012-08-08 07:26:29 +00:00
// Write implements the ResponseWriter.Write method.
func (w *response) Write(m *Msg) (err error) {
var (
data []byte
ok bool
)
2012-08-03 16:28:00 +00:00
if m == nil {
return &Error{Err: "nil message"}
}
if t := m.IsTsig(); t != nil {
data, w.tsigRequestMAC, err = TsigGenerate(m, w.conn.tsigSecret[t.Hdr.Name], w.tsigRequestMAC, w.tsigTimersOnly)
if err != nil {
return err
}
} else {
data, ok = m.Pack()
if !ok {
return ErrPack
}
}
2012-08-08 12:43:59 +00:00
return w.WriteBuf(data)
2011-04-03 09:49:23 +00:00
}
2011-04-03 09:14:54 +00:00
2012-08-08 07:26:29 +00:00
// WriteBuf implements the ResponseWriter.WriteBuf method.
2012-08-05 19:15:15 +00:00
func (w *response) WriteBuf(m []byte) (err error) {
if m == nil {
return &Error{Err: "nil message"}
}
switch {
case w.conn._UDP != nil:
_, err := w.conn._UDP.WriteTo(m, w.conn.remoteAddr)
if err != nil {
return err
}
case w.conn._TCP != nil:
if len(m) > MaxMsgSize {
return ErrBuf
}
l := make([]byte, 2)
l[0], l[1] = packUint16(uint16(len(m)))
n, err := w.conn._TCP.Write(l)
if err != nil {
return err
}
if n != 2 {
return io.ErrShortWrite
}
n, err = w.conn._TCP.Write(m)
if err != nil {
return err
}
i := n
if i < len(m) {
j, err := w.conn._TCP.Write(m[i:len(m)])
if err != nil {
return err
}
i += j
}
n = i
}
return nil
}
2012-08-08 07:26:29 +00:00
// RemoteAddr implements the ResponseWriter.RemoteAddr method.
2011-07-05 17:17:29 +00:00
func (w *response) RemoteAddr() net.Addr { return w.conn.remoteAddr }
2012-02-26 20:33:50 +00:00
2012-08-08 07:26:29 +00:00
// TsigStatus implements the ResponseWriter.TsigStatus method.
2012-05-04 21:18:29 +00:00
func (w *response) TsigStatus() error { return w.tsigStatus }