-
Notifications
You must be signed in to change notification settings - Fork 241
/
resolver.go
332 lines (279 loc) · 8.76 KB
/
resolver.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
package upstream
import (
"context"
"fmt"
"math"
"net/netip"
"net/url"
"strings"
"sync"
"time"
"github.com/AdguardTeam/dnsproxy/internal/bootstrap"
"github.com/AdguardTeam/dnsproxy/proxyutil"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"github.com/miekg/dns"
)
// Resolver resolves the hostnames to IP addresses. Note, that [net.Resolver]
// from standard library also implements this interface.
type Resolver = bootstrap.Resolver
// StaticResolver is a resolver which always responds with an underlying slice
// of IP addresses.
type StaticResolver = bootstrap.StaticResolver
// ParallelResolver is a slice of resolvers that are queried concurrently until
// the first successful response is returned, as opposed to all resolvers being
// queried in order in [ConsequentResolver].
type ParallelResolver = bootstrap.ParallelResolver
// ConsequentResolver is a slice of resolvers that are queried in order until
// the first successful non-empty response, as opposed to just successful
// response requirement in [ParallelResolver].
type ConsequentResolver = bootstrap.ConsequentResolver
// UpstreamResolver is a wrapper around Upstream that implements the
// [bootstrap.Resolver] interface.
type UpstreamResolver struct {
// Upstream is used for lookups. It must not be nil.
Upstream
}
// NewUpstreamResolver creates an upstream that can be used as bootstrap
// [Resolver]. resolverAddress format is the same as in the
// [AddressToUpstream]. If the upstream can't be used as a bootstrap, the
// returned error will have the underlying type of [NotBootstrapError], and r
// itself will be fully usable. Closing r.Upstream is caller's responsibility.
func NewUpstreamResolver(resolverAddress string, opts *Options) (r *UpstreamResolver, err error) {
upsOpts := &Options{}
// TODO(ameshkov): Aren't other options needed here?
if opts != nil {
upsOpts.Timeout = opts.Timeout
upsOpts.VerifyServerCertificate = opts.VerifyServerCertificate
upsOpts.PreferIPv6 = opts.PreferIPv6
}
ups, err := AddressToUpstream(resolverAddress, upsOpts)
if err != nil {
err = fmt.Errorf("creating upstream: %w", err)
log.Error("upstream bootstrap: %s", err)
return nil, err
}
return &UpstreamResolver{Upstream: ups}, validateBootstrap(ups)
}
// NotBootstrapError is returned by [AddressToUpstream] when the parsed upstream
// can't be used as a bootstrap and wraps the actual reason.
type NotBootstrapError struct {
// err is the actual reason why the upstream can't be used as a bootstrap.
err error
}
// type check
var _ error = NotBootstrapError{}
// Error implements the [error] interface for NotBootstrapError.
func (e NotBootstrapError) Error() (msg string) {
return fmt.Sprintf("not a bootstrap: %s", e.err)
}
// type check
var _ errors.Wrapper = NotBootstrapError{}
// Unwrap implements the [errors.Wrapper] interface.
func (e NotBootstrapError) Unwrap() (reason error) {
return e.err
}
// validateBootstrap returns an error if u can't be used as a bootstrap.
func validateBootstrap(u Upstream) (err error) {
var upsURL *url.URL
switch u := u.(type) {
case *dnsCrypt:
return nil
case *plainDNS:
upsURL = u.addr
case *dnsOverTLS:
upsURL = u.addr
case *dnsOverHTTPS:
upsURL = u.addr
case *dnsOverQUIC:
upsURL = u.addr
default:
return fmt.Errorf("unknown upstream type: %T", u)
}
// Make sure the upstream doesn't need a bootstrap.
_, err = netip.ParseAddr(upsURL.Hostname())
if err != nil {
return NotBootstrapError{err: err}
}
return nil
}
// type check
var _ Resolver = &UpstreamResolver{}
// LookupNetIP implements the [Resolver] interface for *UpstreamResolver. It
// doesn't consider the TTL of the DNS records.
//
// TODO(e.burkov): Investigate why the empty slice is returned instead of nil.
func (r *UpstreamResolver) LookupNetIP(
ctx context.Context,
network bootstrap.Network,
host string,
) (ips []netip.Addr, err error) {
if host == "" {
return nil, nil
}
host = dns.Fqdn(strings.ToLower(host))
res, err := r.lookupNetIP(ctx, network, host)
if err != nil {
return []netip.Addr{}, err
}
return res.addrs, err
}
// ipResult reflects a single A/AAAA record from the DNS response. It's used
// to cache the results of lookups.
type ipResult struct {
expire time.Time
addrs []netip.Addr
}
// lookupNetIP performs a DNS lookup of host and returns the result. network
// must be either [bootstrap.NetworkIP4], [bootstrap.NetworkIP6], or
// [bootstrap.NetworkIP]. host must be in a lower-case FQDN form.
//
// TODO(e.burkov): Use context.
func (r *UpstreamResolver) lookupNetIP(
_ context.Context,
network bootstrap.Network,
host string,
) (result *ipResult, err error) {
switch network {
case bootstrap.NetworkIP4, bootstrap.NetworkIP6:
return r.request(host, network)
case bootstrap.NetworkIP:
// Go on.
default:
return result, fmt.Errorf("unsupported network %s", network)
}
resCh := make(chan any, 2)
go r.resolveAsync(resCh, host, bootstrap.NetworkIP4)
go r.resolveAsync(resCh, host, bootstrap.NetworkIP6)
var errs []error
result = &ipResult{}
for i := 0; i < 2; i++ {
switch res := <-resCh; res := res.(type) {
case error:
errs = append(errs, res)
case *ipResult:
if result.expire.Equal(time.Time{}) || res.expire.Before(result.expire) {
result.expire = res.expire
}
result.addrs = append(result.addrs, res.addrs...)
}
}
return result, errors.Join(errs...)
}
// request performs a single DNS lookup of host and returns all the valid
// addresses from the answer section of the response. network must be either
// [bootstrap.NetworkIP4], or [bootstrap.NetworkIP6]. host must be in a
// lower-case FQDN form.
//
// TODO(e.burkov): Consider NS and Extra sections when setting TTL. Check out
// what RFCs say about it.
func (r *UpstreamResolver) request(host string, n bootstrap.Network) (res *ipResult, err error) {
var qtype uint16
switch n {
case bootstrap.NetworkIP4:
qtype = dns.TypeA
case bootstrap.NetworkIP6:
qtype = dns.TypeAAAA
default:
panic(fmt.Sprintf("unsupported network %q", n))
}
req := &dns.Msg{
MsgHdr: dns.MsgHdr{
Id: dns.Id(),
RecursionDesired: true,
},
Question: []dns.Question{{
Name: host,
Qtype: qtype,
Qclass: dns.ClassINET,
}},
}
// As per [Upstream.Exchange] documentation, the response is always returned
// if no error occurred.
resp, err := r.Exchange(req)
if err != nil {
return res, err
}
res = &ipResult{
expire: time.Now(),
addrs: make([]netip.Addr, 0, len(resp.Answer)),
}
var minTTL uint32 = math.MaxUint32
for _, rr := range resp.Answer {
ip := proxyutil.IPFromRR(rr)
if !ip.IsValid() {
continue
}
res.addrs = append(res.addrs, ip)
minTTL = min(minTTL, rr.Header().Ttl)
}
res.expire = res.expire.Add(time.Duration(minTTL) * time.Second)
return res, nil
}
// resolveAsync performs a single DNS lookup and sends the result to ch. It's
// intended to be used as a goroutine.
func (r *UpstreamResolver) resolveAsync(resCh chan<- any, host, network string) {
res, err := r.request(host, network)
if err != nil {
resCh <- err
} else {
resCh <- res
}
}
// CachingResolver is a [Resolver] that caches the results of lookups. It's
// required to be created with [NewCachingResolver].
type CachingResolver struct {
// resolver is the underlying resolver to use for lookups.
resolver *UpstreamResolver
// mu protects cached and it's elements.
mu *sync.RWMutex
// cached is the set of cached results sorted by [resolveResult.name].
//
// TODO(e.burkov): Use expiration cache.
cached map[string]*ipResult
}
// NewCachingResolver creates a new caching resolver that uses r for lookups.
func NewCachingResolver(r *UpstreamResolver) (cr *CachingResolver) {
return &CachingResolver{
resolver: r,
mu: &sync.RWMutex{},
cached: map[string]*ipResult{},
}
}
// type check
var _ Resolver = (*CachingResolver)(nil)
// LookupNetIP implements the [Resolver] interface for *CachingResolver.
//
// TODO(e.burkov): It may appear that several concurrent lookup results rewrite
// each other in the cache.
func (r *CachingResolver) LookupNetIP(
ctx context.Context,
network bootstrap.Network,
host string,
) (addrs []netip.Addr, err error) {
now := time.Now()
host = dns.Fqdn(strings.ToLower(host))
addrs = r.findCached(host, now)
if addrs != nil {
return addrs, nil
}
newRes, err := r.resolver.lookupNetIP(ctx, network, host)
if err != nil {
return []netip.Addr{}, err
}
r.mu.Lock()
defer r.mu.Unlock()
r.cached[host] = newRes
return newRes.addrs, nil
}
// findCached returns the cached addresses for host if it's not expired yet, and
// the corresponding cached result, if any.
func (r *CachingResolver) findCached(host string, now time.Time) (addrs []netip.Addr) {
r.mu.RLock()
defer r.mu.RUnlock()
res, ok := r.cached[host]
if !ok || res.expire.Before(now) {
return nil
}
return res.addrs
}