Debian Codegraph @

serve_mux.go

raw
1 package dns
2
3 import (
4 "context"
5 "io"
6 "sync"
7 )
8
9 // Handler is implemented by any value that implements ServeDNS. The message r is minimally decoded, only up
10 // to the question section (mostly first 20-ish bytes) are decoded, see [Option]. The rest of the message is available in
11 // r.Data, so if a message is deemed worthwhile a:
12 //
13 // r.Unpack()
14 //
15 // to get the entire message.
16 //
17 // The context is cancelled when the server exits. The context carries the pattern of the handler (this is
18 // commonly the DNS zone) that was used to invoke it. You can retrieve that pattern with [Zone].
19 type Handler interface {
20 ServeDNS(ctx context.Context, w ResponseWriter, r *Msg)
21 }
22
23 // Zone gets the zone from the context. When the server calls a handler it sets the matched pattern in the
24 // context. If not found it returns the empty string.
25 func Zone(ctx context.Context) string {
26 zone, ok := ctx.Value(contextKeyZone).(string)
27 if !ok {
28 return ""
29 }
30 return zone
31 }
32
33 type contextKey string
34
35 var contextKeyZone = contextKey("zone")
36
37 // The HandlerFunc type is an adapter to allow the use of ordinary functions as DNS handlers. If f is a function
38 // with the appropriate signature, HandlerFunc(f) is a Handler object that calls f.
39 type HandlerFunc func(context.Context, ResponseWriter, *Msg)
40
41 // ServeDNS calls f(w, r).
42 func (f HandlerFunc) ServeDNS(ctx context.Context, w ResponseWriter, r *Msg) { f(ctx, w, r) }
43
44 // ServeMux is an DNS request multiplexer. It matches the zone name of each incoming request against a list of
45 // registered patterns add calls the handler for the pattern that most closely matches the zone name and
46 // class.
47 //
48 // ServeMux is DNSSEC aware, meaning that queries for the DS record are redirected to the parent zone (if that
49 // is also registered), otherwise the child gets the query.
50 //
51 // ServeMux is also safe for concurrent access from multiple goroutines. The zero ServeMux is empty and ready for use.
52 type ServeMux struct {
53 z map[uint16]map[string]Handler
54 sync.RWMutex
55 }
56
57 // NewServeMux allocates and returns a new ServeMux.
58 func NewServeMux() *ServeMux { return &ServeMux{z: map[uint16]map[string]Handler{}} }
59
60 // DefaultServeMux is the default ServeMux used by Serve.
61 var DefaultServeMux = NewServeMux()
62
63 func (mux *ServeMux) match(q string, t, c uint16) (Handler, string) {
64 q = dnsutilCanonical(q)
65
66 var handler Handler
67 var off, ds, end = 0, 0, false
68 mux.RLock()
69 m, ok := mux.z[c] // get the class map
70 if !ok {
71 // we don't know anything about the class.
72 mux.RUnlock()
73 return nil, ""
74 }
75 for ; !end; off, end = dnsutilNext(q, off) {
76 if h, ok := m[q[off:]]; ok {
77 if t != TypeDS {
78 mux.RUnlock()
79 return h, q[off:]
80 }
81 // Continue for DS to see if we have a parent too, if so delegate to the parent.
82 // If we already found a DS target we should return the current handler as that
83 // should be a parent.
84 if handler != nil { // Set in previous iteration, we return "this one" (= h).
85 mux.RUnlock()
86 return h, q[off:]
87 }
88 handler = h
89 ds = off
90 }
91 }
92 mux.RUnlock()
93 if handler != nil {
94 return handler, q[ds:]
95 }
96 return nil, ""
97 }
98
99 // Handle adds a handler to the ServeMux for pattern. Identical patterns silently overwrites earlier handlers.
100 // Optionally a class can be given, this defaults to [ClassINET].
101 func (mux *ServeMux) Handle(pattern string, handler Handler, class ...uint16) {
102 if dnsutilCanonical(pattern) != pattern || pattern == "" {
103 panic("dns: pattern should be in canonical form: " + pattern)
104 }
105 mux.Lock()
106 if mux.z == nil {
107 mux.z = make(map[uint16]map[string]Handler)
108 }
109 c := uint16(ClassINET)
110 if len(class) > 0 {
111 c = class[0]
112 }
113 if mux.z[c] == nil {
114 mux.z[c] = make(map[string]Handler)
115 }
116 mux.z[c][pattern] = handler
117 mux.Unlock()
118 }
119
120 // HandleFunc adds a handler function to the ServeMux for pattern.
121 func (mux *ServeMux) HandleFunc(pattern string, handler func(context.Context, ResponseWriter, *Msg), class ...uint16) {
122 mux.Handle(pattern, HandlerFunc(handler), class...)
123 }
124
125 // HandleRemove deregisters the handler specific for pattern from the ServeMux. Optionally a class can be
126 // given, this defaults to [ClassINET].
127 func (mux *ServeMux) HandleRemove(pattern string, class ...uint16) {
128 if dnsutilCanonical(pattern) != pattern || pattern == "" {
129 panic("dns: pattern should be in canonical form: " + pattern)
130 }
131 mux.Lock()
132 if len(class) > 0 {
133 delete(mux.z[class[0]], pattern)
134 } else {
135 delete(mux.z[ClassINET], pattern)
136 }
137 mux.Unlock()
138 }
139
140 // ServeDNS dispatches the request to the handler whose pattern most closely matches the request message.
141 //
142 // ServeDNS is DNSSEC aware, meaning that queries for the DS record are redirected to the parent zone (if
143 // that is also registered), otherwise the current zone gets the query.
144 //
145 // If no handler is found a standard REFUSED message is returned. No checks are made on the request message.
146 func (mux *ServeMux) ServeDNS(ctx context.Context, w ResponseWriter, req *Msg) {
147 if req.qtype == 0 { // this is an implicit check that we've at least seen something resembling a question
148 refuse(w, req)
149 return
150 }
151
152 if h, zone := mux.match(req.Question[0].Header().Name, req.qtype, req.qclass); h != nil {
153 h.ServeDNS(context.WithValue(ctx, contextKeyZone, zone), w, req)
154 return
155 }
156
157 refuse(w, req)
158 }
159
160 // Handle registers the handler with the given pattern in the [DefaultServeMux]. The documentation for
161 // [ServeMux] explains how patterns are matched.
162 func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }
163
164 // HandleRemove deregisters the handle with the given pattern in the [DefaultServeMux].
165 func HandleRemove(pattern string) { DefaultServeMux.HandleRemove(pattern) }
166
167 // HandleFunc registers the handler function with the given pattern in the [DefaultServeMux].
168 func HandleFunc(pattern string, handler func(context.Context, ResponseWriter, *Msg)) {
169 DefaultServeMux.HandleFunc(pattern, handler)
170 }
171
172 // refuse writes a REFUSED response to w.
173 func refuse(w ResponseWriter, r *Msg) {
174 m := new(Msg)
175 m.Data = r.Data
176
177 // dnsutil.SetReply was used here, but led to all kinds of cyclic imports, just use that very static code here.
178 m.ID, m.Rcode = r.ID, RcodeRefused
179 m.Response, m.Opcode = true, r.Opcode
180 m.RecursionDesired = r.RecursionDesired
181 m.CheckingDisabled = r.CheckingDisabled
182 m.Security = r.Security
183 m.Question = r.Question
184 m.Answer, m.Ns, m.Extra, m.Pseudo = nil, nil, nil, nil
185
186 if err := m.Pack(); err != nil {
187 msgPut(m)
188 return
189 }
190 io.Copy(w, m)
191 }