-
Notifications
You must be signed in to change notification settings - Fork 457
/
dns.go
332 lines (262 loc) · 8.15 KB
/
dns.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// Package dns provides dns server implementation.
package dns
import (
"context"
"errors"
"fmt"
"math/rand"
"net"
"slices"
"strings"
"sync"
"syscall"
"time"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/cache"
"github.com/coredns/coredns/plugin/pkg/proxy"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
"go.uber.org/zap"
"golang.org/x/sys/unix"
"github.com/siderolabs/talos/internal/pkg/utils"
)
// NewRunner creates a new Runner.
func NewRunner(srv Server, logger *zap.Logger) *Runner {
r := utils.NewRunner(srv.ActivateAndServe, srv.Shutdown, func(err error) bool {
// There a possible scenario where `Run` reached `ListenAndServe` and then yielded CPU time to another
// goroutine and then `Stop` reached `Shutdown`. In that case `ListenAndServe` will actually start after
// `Shutdown` and `Stop` method will forever block if we do not try again.
return strings.Contains(err.Error(), "server not started")
})
return &Runner{r: r, logger: logger}
}
// Runner is a dns server handler.
type Runner struct {
r *utils.Runner
logger *zap.Logger
}
// Server is a dns server.
type Server interface {
ActivateAndServe() error
Shutdown() error
}
// Run runs dns server.
func (r *Runner) Run() error {
r.logger.Info("starting dns server")
err := r.r.Run()
r.logger.Info("dns server stopped", zap.Error(err))
return err
}
// Stop stops dns server. It's safe to call even if server is already stopped.
func (r *Runner) Stop() {
err := r.r.Stop()
if err != nil {
r.logger.Warn("error shutting down dns server", zap.Error(err))
}
}
// Cache is a [dns.Handler] to [plugin.Handler] adapter.
type Cache struct {
cache *cache.Cache
logger *zap.Logger
}
// NewCache creates a new Cache.
func NewCache(next plugin.Handler, l *zap.Logger) *Cache {
c := cache.NewCache("zones", "view")
c.Next = next
return &Cache{cache: c, logger: l}
}
// ServeDNS implements [dns.Handler].
func (c *Cache) ServeDNS(wr dns.ResponseWriter, msg *dns.Msg) {
_, err := c.cache.ServeDNS(context.Background(), wr, msg)
if err != nil {
// we should probably call newProxy.Healthcheck() if there are too many errors
c.logger.Warn("error serving dns request", zap.Error(err))
}
}
// Handler is a dns proxy selector.
type Handler struct {
mx sync.RWMutex
dests []*proxy.Proxy
logger *zap.Logger
}
// NewHandler creates a new Handler.
func NewHandler(logger *zap.Logger) *Handler {
return &Handler{
logger: logger,
}
}
// Name implements plugin.Handler.
func (h *Handler) Name() string {
return "Handler"
}
// ServeDNS implements plugin.Handler.
func (h *Handler) ServeDNS(ctx context.Context, wrt dns.ResponseWriter, msg *dns.Msg) (int, error) {
h.mx.RLock()
defer h.mx.RUnlock()
req := request.Request{W: wrt, Req: msg}
h.logger.Debug("dns request", zap.Stringer("data", msg))
upstreams := slices.Clone(h.dests)
if len(upstreams) == 0 {
emptyProxyErr := new(dns.Msg).SetRcode(req.Req, dns.RcodeServerFailure)
err := wrt.WriteMsg(emptyProxyErr)
if err != nil {
// We can't do much here, but at least log the error.
h.logger.Warn("failed to write 'no destination available' error dns response", zap.Error(err))
}
return dns.RcodeServerFailure, errors.New("no destination available")
}
rand.Shuffle(len(upstreams), func(i, j int) { upstreams[i], upstreams[j] = upstreams[j], upstreams[i] })
var (
resp *dns.Msg
err error
)
for _, ups := range upstreams {
resp, err = ups.Connect(ctx, req, proxy.Options{})
if errors.Is(err, proxy.ErrCachedClosed) { // Remote side closed conn, can only happen with TCP.
continue
}
if err == nil {
break
}
continue
}
if err != nil {
return dns.RcodeServerFailure, err
}
if !req.Match(resp) {
resp = new(dns.Msg).SetRcode(req.Req, dns.RcodeFormatError)
err = wrt.WriteMsg(resp)
if err != nil {
// We can't do much here, but at least log the error.
h.logger.Warn("failed to write non-matched response", zap.Error(err))
}
h.logger.Warn("dns response didn't match", zap.Stringer("data", resp))
return 0, nil
}
err = wrt.WriteMsg(resp)
if err != nil {
// We can't do much here, but at least log the error.
h.logger.Warn("error writing dns response", zap.Error(err))
}
h.logger.Debug("dns response", zap.Stringer("data", resp))
return 0, nil
}
// SetProxy sets destination dns proxy servers.
func (h *Handler) SetProxy(prxs []*proxy.Proxy) bool {
h.mx.Lock()
defer h.mx.Unlock()
if slices.Equal(h.dests, prxs) {
return false
}
h.dests = prxs
return true
}
// Stop stops and clears dns proxy selector.
func (h *Handler) Stop() { h.SetProxy(nil) }
// ServerOptins is a Server options.
type ServerOptins struct {
Listener net.Listener
PacketConn net.PacketConn
Handler dns.Handler
ReadTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout func() time.Duration
MaxTCPQueries int
}
// NewServer creates a new Server.
func NewServer(opts ServerOptins) Server {
return &server{&dns.Server{
Listener: opts.Listener,
PacketConn: opts.PacketConn,
Handler: opts.Handler,
ReadTimeout: opts.ReadTimeout,
WriteTimeout: opts.WriteTimeout,
IdleTimeout: opts.IdleTimeout,
MaxTCPQueries: opts.MaxTCPQueries,
}}
}
type server struct{ *dns.Server }
// NewTCPListener creates a new TCP listener.
func NewTCPListener(network, addr string) (net.Listener, error) {
var opts []controlOptions
switch network {
case "tcp", "tcp4":
network = "tcp4"
opts = tcpOptions
case "tcp6":
opts = tcpOptionsV6
default:
return nil, fmt.Errorf("unsupported network: %s", network)
}
lc := net.ListenConfig{Control: makeControl(opts)}
return lc.Listen(context.Background(), network, addr)
}
// NewUDPPacketConn creates a new UDP packet connection.
func NewUDPPacketConn(network, addr string) (net.PacketConn, error) {
var opts []controlOptions
switch network {
case "udp", "udp4":
network = "udp4"
opts = udpOptions
case "udp6":
opts = udpOptionsV6
default:
return nil, fmt.Errorf("unsupported network: %s", network)
}
lc := net.ListenConfig{
Control: makeControl(opts),
}
return lc.ListenPacket(context.Background(), network, addr)
}
var (
tcpOptions = []controlOptions{
{unix.IPPROTO_IP, unix.IP_RECVTTL, 1, "failed to set IP_RECVTTL"},
{unix.IPPROTO_TCP, unix.TCP_FASTOPEN, 5, "failed to set TCP_FASTOPEN"}, // tcp specific stuff from systemd
{unix.IPPROTO_TCP, unix.TCP_NODELAY, 1, "failed to set TCP_NODELAY"}, // tcp specific stuff from systemd
{unix.IPPROTO_IP, unix.IP_TTL, 1, "failed to set IP_TTL"},
}
tcpOptionsV6 = []controlOptions{
{unix.IPPROTO_IPV6, unix.IPV6_RECVHOPLIMIT, 1, "failed to set IPV6_RECVHOPLIMIT"},
{unix.IPPROTO_TCP, unix.TCP_FASTOPEN, 5, "failed to set TCP_FASTOPEN"}, // tcp specific stuff from systemd
{unix.IPPROTO_TCP, unix.TCP_NODELAY, 1, "failed to set TCP_NODELAY"}, // tcp specific stuff from systemd
{unix.IPPROTO_IPV6, unix.IPV6_UNICAST_HOPS, 1, "failed to set IPV6_UNICAST_HOPS"},
}
udpOptions = []controlOptions{
{unix.IPPROTO_IP, unix.IP_RECVTTL, 1, "failed to set IP_RECVTTL"},
{unix.IPPROTO_IP, unix.IP_TTL, 1, "failed to set IP_TTL"},
}
udpOptionsV6 = []controlOptions{
{unix.IPPROTO_IPV6, unix.IPV6_RECVHOPLIMIT, 1, "failed to set IPV6_RECVHOPLIMIT"},
{unix.IPPROTO_IPV6, unix.IPV6_UNICAST_HOPS, 1, "failed to set IPV6_UNICAST_HOPS"},
}
)
type controlOptions struct {
level int
opt int
val int
errorMessage string
}
func makeControl(opts []controlOptions) func(string, string, syscall.RawConn) error {
return func(_ string, _ string, c syscall.RawConn) error {
var resErr error
err := c.Control(func(fd uintptr) {
for _, opt := range opts {
opErr := unix.SetsockoptInt(int(fd), opt.level, opt.opt, opt.val)
if opErr != nil {
resErr = fmt.Errorf(opt.errorMessage+": %w", opErr)
return
}
}
})
if err != nil {
return fmt.Errorf("failed in control call: %w", err)
}
if resErr != nil {
return fmt.Errorf("failed to set socket options: %w", resErr)
}
return nil
}
}