| 1 |
package dns |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"crypto/tls" |
| 6 |
"fmt" |
| 7 |
"io" |
| 8 |
"net" |
| 9 |
"sync" |
| 10 |
"time" |
| 11 |
|
| 12 |
"codeberg.org/miekg/dns/pkg/pool" |
| 13 |
) |
| 14 |
|
| 15 |
// Default maximum number of TCP queries before we close the socket. |
| 16 |
const MaxTCPQueries = 1024 |
| 17 |
|
| 18 |
// ListenAndServe starts a server on address and network specified and invokes handler for incoming queries. |
| 19 |
func ListenAndServe(addr, network string, handler Handler) error { |
| 20 |
server := NewServer() |
| 21 |
server.Addr = addr |
| 22 |
server.Net = network |
| 23 |
server.Handler = handler |
| 24 |
return server.ListenAndServe() |
| 25 |
} |
| 26 |
|
| 27 |
// MsgAcceptAction represents the action to be taken. |
| 28 |
type MsgAcceptAction int |
| 29 |
|
| 30 |
// Allowed returned values from a MsgAcceptFunc. |
| 31 |
const ( |
| 32 |
MsgAccept MsgAcceptAction = iota // Accept the message. |
| 33 |
MsgReject // Reject the message with a [RcodeFormatError]. |
| 34 |
MsgRejectNotImplemented // Reject the message with a [RcodeNotImplemented]. |
| 35 |
MsgRejectRefused // Reject the message with a [RcodeRefused]. |
| 36 |
MsgIgnore // Ignore the message and send nothing back. |
| 37 |
) |
| 38 |
|
| 39 |
// MsgAcceptFunc is used early in the server code to accept or reject a message with RcodeFormatError or |
| 40 |
// other response code. |
| 41 |
// It returns a MsgAcceptAction to indicate what should happen with the message. Only the header of the |
| 42 |
// message is unpacked when this function is called. Note that this function must at least check if there |
| 43 |
// is a single question in the question section of the message. |
| 44 |
type MsgAcceptFunc func(m *Msg) MsgAcceptAction |
| 45 |
|
| 46 |
// DefaultMsgAcceptFunc checks the request and will reject if: |
| 47 |
// |
| 48 |
// - Isn't a request, returns [MsgIgnore]. |
| 49 |
// - Has an opcode that isn't recognized, returns [MsgIgnore]. |
| 50 |
// - Has more than a single "RR" in the question section, returns [MsgReject]. |
| 51 |
// - Is a query for RRSIGs, returns [MsgRejectRefused]. |
| 52 |
func DefaultMsgAcceptFunc(m *Msg) MsgAcceptAction { |
| 53 |
// see dnshttp.DefaultMsgAcceptFunc where this code is duplicated. |
| 54 |
if m.Response { |
| 55 |
return MsgIgnore |
| 56 |
} |
| 57 |
if _, ok := OpcodeToString[m.Opcode]; !ok { |
| 58 |
return MsgRejectNotImplemented |
| 59 |
} |
| 60 |
if len(m.Question) != 1 { |
| 61 |
return MsgReject |
| 62 |
} |
| 63 |
if _, ok := m.Question[0].(*RRSIG); ok { |
| 64 |
return MsgRejectRefused |
| 65 |
} |
| 66 |
return MsgAccept |
| 67 |
} |
| 68 |
|
| 69 |
// InvalidMsgFunc is a listener hook for observing incoming messages that were discarded |
| 70 |
// because they could not be parsed or an earlier error in the server. |
| 71 |
// Every message that is read by a Reader will eventually be provided to the [Handler], or passed to this function. |
| 72 |
type InvalidMsgFunc func(m *Msg, err error) |
| 73 |
|
| 74 |
// DefaultMsgInvalidFunc is the default function used in case no InvalidMsgFunc is set. It is defined to be a noop. |
| 75 |
func DefaultMsgInvalidFunc(m *Msg, err error) {} |
| 76 |
|
| 77 |
// A Server defines parameters for running an DNS server. |
| 78 |
type Server struct { |
| 79 |
// Address to listen on, ":domain" if empty. |
| 80 |
Addr string |
| 81 |
// If "tcp" it will invoke a TCP listener, otherwise an UDP one. If TLSConfig is not nil and Net is "tcp" a TLS server is |
| 82 |
// started. |
| 83 |
Net string |
| 84 |
// TCP Listener that is used. If Listener is set before Serve is called, its value will be used and no |
| 85 |
// new Listener will be created. Note in that case ListenFunc isn't ran either. |
| 86 |
Listener net.Listener |
| 87 |
// ListenFunc takes a *Server and modifies it. This function is called after the listener is set up, but |
| 88 |
// before it is used, as such this can be used to wrap the listeners. |
| 89 |
ListenFunc func(*Server) |
| 90 |
// TLS connection configuration. Use for DOT (DNS over TCP). Not NextProtos must have "dot", for this to |
| 91 |
// work with DOT clients. See [NextProtos]. |
| 92 |
TLSConfig *tls.Config |
| 93 |
// UDP "Listener" that is used. If PacketConn is set before Serve is called, its value will be used a no |
| 94 |
// new PacketConn will be created. Note in that case ListenFunc isn't ran either. |
| 95 |
PacketConn net.PacketConn |
| 96 |
// Handler to invoke, dns.DefaultServeMux if nil. |
| 97 |
Handler Handler |
| 98 |
// Default buffer size to use to read incoming UDP messages. If not set it defaults to DefaultMsgSize |
| 99 |
// (1400 B). |
| 100 |
UDPSize int |
| 101 |
// The read timeout vaule for new connections, defaults to 2 * time.Second. |
| 102 |
ReadTimeout time.Duration |
| 103 |
// TCP idle timeout for multiple queries, if nil, defaults to 8 * time.Second (RFC 5966). |
| 104 |
IdleTimeout time.Duration |
| 105 |
// Maximum number of TCP queries before we close the socket. Default is [MaxTCPQueries], unlimited if -1. |
| 106 |
// See [ResponseWriter.Hijack] on how a handler can bypass this. |
| 107 |
MaxTCPQueries int |
| 108 |
|
| 109 |
// AcceptMsgFunc will check the incoming message and will reject it early in the process. Defaults to |
| 110 |
// [DefaultMsgAcceptFunc]. If you use a custom MsgAcceptFunc it should at minimum check if there a single |
| 111 |
// question in the question section. |
| 112 |
MsgAcceptFunc MsgAcceptFunc |
| 113 |
// MsgInvalidFunc is optional, it will be called if a message is received but cannot be parsed. |
| 114 |
MsgInvalidFunc InvalidMsgFunc |
| 115 |
// If NotifyStartedFunc is set it is called once the server has started listening. Both NotifyStartedFunc |
| 116 |
// and NotifyStartedFunc get a copy of the server's context. |
| 117 |
NotifyStartedFunc func(context.Context) |
| 118 |
// If NotifyShutdownFunc is set is is called when a server shutdown is initiated. The server will wait for |
| 119 |
// this function to return before stopping the server. |
| 120 |
NotifyShutdownFunc func(context.Context) |
| 121 |
|
| 122 |
// MsgPool is the default [Pooler] used for allocations. When creating a non-default pool it must be at |
| 123 |
// least as large as the configured UDPSize. |
| 124 |
MsgPool pool.Pooler |
| 125 |
|
| 126 |
ctx context.Context // server wide context to signal shutdown to running handlers |
| 127 |
cancel context.CancelFunc |
| 128 |
exited chan struct{} |
| 129 |
shutdown chan bool |
| 130 |
|
| 131 |
// Whether to set the SO_REUSEPORT socket option, allowing multiple listeners to be bound to a single address. |
| 132 |
// It is only supported on certain GOOSes and when using ListenAndServe. |
| 133 |
ReusePort bool |
| 134 |
// Whether to set the SO_REUSEADDR socket option, allowing multiple listeners to be bound to a single address. |
| 135 |
// Crucially this allows binding when an existing server is listening on `0.0.0.0` or `::`. |
| 136 |
// It is only supported on certain GOOSes and when using ListenAndServe. |
| 137 |
ReuseAddr bool |
| 138 |
} |
| 139 |
|
| 140 |
// NewServer return a new server initialized with some defaults |
| 141 |
func NewServer() *Server { |
| 142 |
srv := new(Server) |
| 143 |
srv.init() |
| 144 |
return srv |
| 145 |
} |
| 146 |
|
| 147 |
func (srv *Server) init() { |
| 148 |
if srv.UDPSize == 0 { |
| 149 |
srv.UDPSize = DefaultMsgSize |
| 150 |
} |
| 151 |
if srv.MsgInvalidFunc == nil { |
| 152 |
srv.MsgInvalidFunc = DefaultMsgInvalidFunc |
| 153 |
} |
| 154 |
if srv.MsgAcceptFunc == nil { |
| 155 |
srv.MsgAcceptFunc = DefaultMsgAcceptFunc |
| 156 |
} |
| 157 |
if srv.Handler == nil { |
| 158 |
srv.Handler = DefaultServeMux |
| 159 |
} |
| 160 |
if srv.ReadTimeout == 0 { |
| 161 |
srv.ReadTimeout = 2 * time.Second |
| 162 |
} |
| 163 |
if srv.IdleTimeout == 0 { |
| 164 |
srv.IdleTimeout = 8 * time.Second |
| 165 |
} |
| 166 |
if srv.MsgPool == nil { |
| 167 |
srv.MsgPool = pool.New(srv.UDPSize) |
| 168 |
} |
| 169 |
|
| 170 |
srv.ctx, srv.cancel = context.WithCancel(context.Background()) |
| 171 |
srv.exited = make(chan struct{}) |
| 172 |
srv.shutdown = make(chan bool) |
| 173 |
} |
| 174 |
|
| 175 |
// ListenAndServe starts a nameserver on the configured address in *Server. If TLS config is available a TLS |
| 176 |
// listener will be started. |
| 177 |
func (srv *Server) ListenAndServe() (err error) { |
| 178 |
addr := srv.Addr |
| 179 |
if addr == "" { |
| 180 |
addr = ":domain" |
| 181 |
} |
| 182 |
srv.init() |
| 183 |
|
| 184 |
defer func() { |
| 185 |
if err != nil { |
| 186 |
close(srv.exited) |
| 187 |
} |
| 188 |
}() |
| 189 |
|
| 190 |
buf := srv.MsgPool.Get() |
| 191 |
if len(buf) < srv.UDPSize { |
| 192 |
err = &Error{err: fmt.Sprintf("MsgPool size (%d) should be larger or equal to UDPSize (%d)", len(buf), srv.UDPSize)} |
| 193 |
return err |
| 194 |
} |
| 195 |
srv.MsgPool.Put(buf) |
| 196 |
|
| 197 |
if srv.Listener != nil { |
| 198 |
srv.listenTCP(srv.Listener) |
| 199 |
return nil |
| 200 |
} |
| 201 |
if srv.PacketConn != nil { |
| 202 |
srv.listenUDP(srv.PacketConn) |
| 203 |
return nil |
| 204 |
} |
| 205 |
|
| 206 |
switch srv.Net { |
| 207 |
case "tcp", "tcp4", "tcp6": |
| 208 |
var l net.Listener |
| 209 |
if l, err = listenTCP(srv.Net, addr, srv.ReusePort, srv.ReuseAddr); err != nil { |
| 210 |
return err |
| 211 |
} |
| 212 |
if srv.TLSConfig != nil { |
| 213 |
l = tls.NewListener(l, srv.TLSConfig) |
| 214 |
} |
| 215 |
srv.Listener = l |
| 216 |
if srv.ListenFunc != nil { |
| 217 |
srv.ListenFunc(srv) |
| 218 |
} |
| 219 |
srv.listenTCP(srv.Listener) |
| 220 |
return nil |
| 221 |
case "udp", "udp4", "udp6": |
| 222 |
var l net.PacketConn |
| 223 |
if l, err = listenUDP(srv.Net, addr, srv.ReusePort, srv.ReuseAddr); err != nil { |
| 224 |
return err |
| 225 |
} |
| 226 |
u := l.(*net.UDPConn) |
| 227 |
if err = setUDPSocketOptions(u); err != nil { |
| 228 |
u.Close() |
| 229 |
return err |
| 230 |
} |
| 231 |
srv.PacketConn = l |
| 232 |
if srv.ListenFunc != nil { |
| 233 |
srv.ListenFunc(srv) |
| 234 |
} |
| 235 |
srv.listenUDP(srv.PacketConn) |
| 236 |
return nil |
| 237 |
} |
| 238 |
err = &Error{err: "bad network"} |
| 239 |
return err |
| 240 |
} |
| 241 |
|
| 242 |
// Shutdown shuts down a server. After a call to Shutdown, ListenAndServe will return. |
| 243 |
// A context.Context may be passed to limit how long to wait for connections to terminate. Not used at the moment. |
| 244 |
func (srv *Server) Shutdown(ctx context.Context) { |
| 245 |
srv.cancel() |
| 246 |
if srv.Listener != nil { |
| 247 |
srv.Listener.Close() |
| 248 |
} |
| 249 |
if srv.PacketConn != nil { |
| 250 |
srv.PacketConn.Close() |
| 251 |
} |
| 252 |
|
| 253 |
if f := srv.NotifyShutdownFunc; f != nil { |
| 254 |
f(srv.ctx) |
| 255 |
} |
| 256 |
|
| 257 |
close(srv.shutdown) |
| 258 |
<-srv.exited |
| 259 |
} |
| 260 |
|
| 261 |
// listenTCP starts a TCP listener for the server. |
| 262 |
func (srv *Server) listenTCP(ln net.Listener) { |
| 263 |
if f := srv.NotifyStartedFunc; f != nil { |
| 264 |
f(srv.ctx) |
| 265 |
} |
| 266 |
var wg sync.WaitGroup |
| 267 |
|
| 268 |
for { |
| 269 |
select { |
| 270 |
default: |
| 271 |
conn, err := ln.Accept() |
| 272 |
if err != nil { |
| 273 |
continue |
| 274 |
} |
| 275 |
go srv.serveTCP(&wg, conn) |
| 276 |
case <-srv.shutdown: |
| 277 |
ln.Close() |
| 278 |
wg.Wait() // this has a data race because we slump &wg in the server... this _only_ this on shutdown though... |
| 279 |
close(srv.exited) |
| 280 |
return |
| 281 |
} |
| 282 |
} |
| 283 |
} |
| 284 |
|
| 285 |
// If this is a not a const, but var, or worse a field in [Server] it's about 10k qps *slower*. |
| 286 |
// cd cmd/reflect; go test -v -count=1 # check the perf values, 15 does 360K on my M2 8-core with Asahi Linux |
| 287 |
|
| 288 |
// BatchSize controls the maximum of packets we should read using recvmmsg(2), via ReadBatch, a tradeoff |
| 289 |
// needs to be made with how much memory needs to be pre-allocated and how fast things should go. It is |
| 290 |
// experimentally set to 20. |
| 291 |
const BatchSize = 20 |
| 292 |
|
| 293 |
// Serve a new TCP connection. ServeUDP is split out in server_no_recvmmsg.go and server_recvmmsg.go. |
| 294 |
func (srv *Server) serveTCP(wg *sync.WaitGroup, conn net.Conn) { |
| 295 |
w := &response{conn: conn} |
| 296 |
|
| 297 |
limit := srv.MaxTCPQueries |
| 298 |
if limit == 0 { |
| 299 |
limit = MaxTCPQueries |
| 300 |
} |
| 301 |
|
| 302 |
readtimeout := srv.ReadTimeout |
| 303 |
hijacked := false |
| 304 |
|
| 305 |
for q := 0; q < limit || limit == -1; q++ { |
| 306 |
conn.SetReadDeadline(time.Now().Add(readtimeout)) |
| 307 |
|
| 308 |
r := &Msg{Data: srv.MsgPool.Get()} |
| 309 |
if _, err := r.ReadFrom(conn); err != nil { |
| 310 |
if isEOFOrClosedNetwork(err) { |
| 311 |
srv.MsgPool.Put(r.Data) |
| 312 |
break |
| 313 |
} |
| 314 |
srv.MsgInvalidFunc(r, err) |
| 315 |
srv.MsgPool.Put(r.Data) |
| 316 |
continue |
| 317 |
} |
| 318 |
|
| 319 |
wg.Add(1) |
| 320 |
go func() { |
| 321 |
srv.serveDNS(w, r) |
| 322 |
wg.Done() |
| 323 |
}() |
| 324 |
|
| 325 |
hijacked = hijacked || w.hijacked.Load() |
| 326 |
if hijacked { |
| 327 |
limit = -1 // when hijacked disregard any limits |
| 328 |
} |
| 329 |
// The first read uses the read timeout, the rest use the idle timeout. |
| 330 |
readtimeout = srv.IdleTimeout |
| 331 |
} |
| 332 |
|
| 333 |
hijacked = hijacked || w.hijacked.Load() |
| 334 |
if !hijacked { |
| 335 |
w.Close() |
| 336 |
} |
| 337 |
} |
| 338 |
|
| 339 |
// serveDNS serves the message it skip the message handling if the received message has the response bit set. |
| 340 |
func (srv *Server) serveDNS(w *response, r *Msg) { |
| 341 |
r.msgPool = srv.MsgPool |
| 342 |
r.Options = MsgOptionUnpackQuestion |
| 343 |
|
| 344 |
if err := r.Unpack(); err != nil { |
| 345 |
srv.MsgInvalidFunc(r, err) |
| 346 |
msgPut(r) |
| 347 |
return |
| 348 |
} |
| 349 |
|
| 350 |
switch action := srv.MsgAcceptFunc(r); action { |
| 351 |
case MsgIgnore: |
| 352 |
msgPut(r) |
| 353 |
return |
| 354 |
|
| 355 |
case MsgReject, MsgRejectNotImplemented, MsgRejectRefused: |
| 356 |
r.Rcode = RcodeFormatError |
| 357 |
if action == MsgRejectNotImplemented { |
| 358 |
r.Rcode = RcodeNotImplemented |
| 359 |
} |
| 360 |
if action == MsgRejectRefused { |
| 361 |
r.Rcode = RcodeRefused |
| 362 |
} |
| 363 |
r.Authoritative = false |
| 364 |
r.Response = true |
| 365 |
r.Zero = false |
| 366 |
r.Reset() |
| 367 |
if err := r.Pack(); err != nil { // the message is such garbage that we should not reply |
| 368 |
msgPut(r) |
| 369 |
return |
| 370 |
} |
| 371 |
|
| 372 |
io.Copy(w, r) |
| 373 |
return |
| 374 |
} |
| 375 |
|
| 376 |
r.Options = MsgOptionUnpack |
| 377 |
srv.Handler.ServeDNS(srv.ctx, w, r) |
| 378 |
} |
| 379 |
|
| 380 |
// NextProtos is the configuration a tls.Config must carry to be compatible with DNS over TLS (DOT). |
| 381 |
var NextProtos = []string{"dot"} |