Debian Codegraph @

server.go

raw
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 once sync.Once
132
133 // Whether to set the SO_REUSEPORT socket option, allowing multiple listeners to be bound to a single address.
134 // It is only supported on certain GOOSes and when using ListenAndServe.
135 ReusePort bool
136 // Whether to set the SO_REUSEADDR socket option, allowing multiple listeners to be bound to a single address.
137 // Crucially this allows binding when an existing server is listening on `0.0.0.0` or `::`.
138 // It is only supported on certain GOOSes and when using ListenAndServe.
139 ReuseAddr bool
140 }
141
142 // NewServer return a new server initialized with some defaults
143 func NewServer() *Server {
144 srv := new(Server)
145 srv.init()
146 return srv
147 }
148
149 func (srv *Server) init() {
150 if srv.UDPSize == 0 {
151 srv.UDPSize = DefaultMsgSize
152 }
153 if srv.MsgInvalidFunc == nil {
154 srv.MsgInvalidFunc = DefaultMsgInvalidFunc
155 }
156 if srv.MsgAcceptFunc == nil {
157 srv.MsgAcceptFunc = DefaultMsgAcceptFunc
158 }
159 if srv.Handler == nil {
160 srv.Handler = DefaultServeMux
161 }
162 if srv.ReadTimeout == 0 {
163 srv.ReadTimeout = 2 * time.Second
164 }
165 if srv.IdleTimeout == 0 {
166 srv.IdleTimeout = 8 * time.Second
167 }
168 if srv.MsgPool == nil {
169 srv.MsgPool = pool.New(srv.UDPSize)
170 }
171
172 srv.ctx, srv.cancel = context.WithCancel(context.Background())
173 srv.exited = make(chan struct{})
174 srv.shutdown = make(chan bool)
175 }
176
177 // ListenAndServe starts a nameserver on the configured address in *Server. If TLS config is available a TLS
178 // listener will be started.
179 func (srv *Server) ListenAndServe() error {
180 addr := srv.Addr
181 if addr == "" {
182 addr = ":domain"
183 }
184 srv.init()
185
186 // some sanity checks
187 buf := srv.MsgPool.Get()
188 if len(buf) < srv.UDPSize {
189 return &Error{err: fmt.Sprintf("MsgPool size (%d) should be larger or equal to UDPSize (%d)", len(buf), srv.UDPSize)}
190 }
191 srv.MsgPool.Put(buf)
192
193 if srv.Listener != nil {
194 srv.listenTCP(srv.Listener)
195 return nil
196 }
197 if srv.PacketConn != nil {
198 srv.listenUDP(srv.PacketConn)
199 return nil
200 }
201
202 switch srv.Net {
203 case "tcp", "tcp4", "tcp6":
204 l, err := listenTCP(srv.Net, addr, srv.ReusePort, srv.ReuseAddr)
205 if err != nil {
206 return err
207 }
208 if srv.TLSConfig != nil {
209 l = tls.NewListener(l, srv.TLSConfig)
210 }
211 srv.Listener = l
212 if srv.ListenFunc != nil {
213 srv.ListenFunc(srv)
214 }
215 srv.listenTCP(srv.Listener)
216 return nil
217 case "udp", "udp4", "udp6":
218 l, err := listenUDP(srv.Net, addr, srv.ReusePort, srv.ReuseAddr)
219 if err != nil {
220 return err
221 }
222 u := l.(*net.UDPConn)
223 if err := setUDPSocketOptions(u); err != nil {
224 u.Close()
225 return err
226 }
227 srv.PacketConn = l
228 if srv.ListenFunc != nil {
229 srv.ListenFunc(srv)
230 }
231 srv.listenUDP(srv.PacketConn)
232 return nil
233 }
234 return &Error{err: "bad network"}
235 }
236
237 // Shutdown shuts down a server. After a call to Shutdown, ListenAndServe will return.
238 // A context.Context may be passed to limit how long to wait for connections to terminate. Not used at the moment.
239 func (srv *Server) Shutdown(ctx context.Context) {
240 srv.cancel()
241 if srv.Listener != nil {
242 srv.Listener.Close()
243 }
244 if srv.PacketConn != nil {
245 srv.PacketConn.Close()
246 }
247
248 if f := srv.NotifyShutdownFunc; f != nil {
249 f(srv.ctx)
250 }
251
252 close(srv.shutdown)
253 <-srv.exited
254 }
255
256 // listenTCP starts a TCP listener for the server.
257 func (srv *Server) listenTCP(ln net.Listener) {
258 if f := srv.NotifyStartedFunc; f != nil {
259 f(srv.ctx)
260 }
261 var wg sync.WaitGroup
262
263 for {
264 select {
265 default:
266 conn, err := ln.Accept()
267 if err != nil {
268 continue
269 }
270 go srv.serveTCP(&wg, conn)
271 case <-srv.shutdown:
272 ln.Close()
273 wg.Wait() // this has a data race because we slump &wg in the server... this _only_ this on shutdown though...
274 srv.once.Do(func() { close(srv.exited) })
275 return
276 }
277 }
278 }
279
280 // If this is a not a const, but var, or worse a field in [Server] it's about 10k qps *slower*.
281 // cd cmd/reflect; go test -v -count=1 # check the perf values, 15 does 360K on my M2 8-core with Asahi Linux
282
283 // BatchSize controls the maximum of packets we should read using recvmmsg(2), via ReadBatch, a tradeoff
284 // needs to be made with how much memory needs to be pre-allocated and how fast things should go. It is
285 // experimentally set to 20.
286 const BatchSize = 20
287
288 // Serve a new TCP connection. ServeUDP is split out in server_no_recvmmsg.go and server_recvmmsg.go.
289 func (srv *Server) serveTCP(wg *sync.WaitGroup, conn net.Conn) {
290 w := &response{conn: conn}
291
292 limit := srv.MaxTCPQueries
293 if limit == 0 {
294 limit = MaxTCPQueries
295 }
296
297 readtimeout := srv.ReadTimeout
298 hijacked := false
299
300 for q := 0; q < limit || limit == -1; q++ {
301 conn.SetReadDeadline(time.Now().Add(readtimeout))
302
303 r := &Msg{Data: srv.MsgPool.Get()}
304 if _, err := r.ReadFrom(conn); err != nil {
305 if isEOFOrClosedNetwork(err) {
306 srv.MsgPool.Put(r.Data)
307 break
308 }
309 srv.MsgInvalidFunc(r, err)
310 srv.MsgPool.Put(r.Data)
311 continue
312 }
313
314 wg.Add(1)
315 go func() {
316 srv.serveDNS(w, r)
317 wg.Done()
318 }()
319
320 hijacked = hijacked || w.hijacked.Load()
321 if hijacked {
322 limit = -1 // when hijacked disregard any limits
323 }
324 // The first read uses the read timeout, the rest use the idle timeout.
325 readtimeout = srv.IdleTimeout
326 }
327
328 if !hijacked {
329 w.Close()
330 }
331 }
332
333 // serveDNS serves the message it skip the message handling if the received message has the response bit set.
334 func (srv *Server) serveDNS(w *response, r *Msg) {
335 r.msgPool = srv.MsgPool
336 r.Options = MsgOptionUnpackQuestion
337
338 if err := r.Unpack(); err != nil {
339 srv.MsgInvalidFunc(r, err)
340 msgPut(r)
341 return
342 }
343
344 switch action := srv.MsgAcceptFunc(r); action {
345 case MsgIgnore:
346 msgPut(r)
347 return
348
349 case MsgReject, MsgRejectNotImplemented, MsgRejectRefused:
350 r.Rcode = RcodeFormatError
351 if action == MsgRejectNotImplemented {
352 r.Rcode = RcodeNotImplemented
353 }
354 if action == MsgRejectRefused {
355 r.Rcode = RcodeRefused
356 }
357 r.Authoritative = false
358 r.Response = true
359 r.Zero = false
360 r.Reset()
361 if err := r.Pack(); err != nil { // the message is such garbage that we should not reply
362 msgPut(r)
363 return
364 }
365
366 io.Copy(w, r)
367 return
368 }
369
370 r.Options = MsgOptionUnpack
371 srv.Handler.ServeDNS(srv.ctx, w, r)
372 }
373
374 // NextProtos is the configuration a tls.Config must carry to be compatible with DNS over TLS (DOT).
375 var NextProtos = []string{"dot"}