forked from ginuerzh/gost
-
Notifications
You must be signed in to change notification settings - Fork 1
/
resolver.go
477 lines (413 loc) · 9.42 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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
package gost
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/go-log/log"
"github.com/miekg/dns"
"golang.org/x/net/http2"
)
var (
// DefaultResolverTimeout is the default timeout for name resolution.
DefaultResolverTimeout = 5 * time.Second
)
// Resolver is a name resolver for domain name.
// It contains a list of name servers.
type Resolver interface {
// Resolve returns a slice of that host's IPv4 and IPv6 addresses.
Resolve(host string) ([]net.IP, error)
}
// ReloadResolver is resolover that support live reloading.
type ReloadResolver interface {
Resolver
Reloader
Stoppable
}
// NameServer is a name server.
// Currently supported protocol: TCP, UDP and TLS.
type NameServer struct {
Addr string
Protocol string
Hostname string // for TLS handshake verification
Timeout time.Duration
exchanger Exchanger
}
// Init initializes the name server.
func (ns *NameServer) Init() error {
timeout := ns.Timeout
if timeout <= 0 {
timeout = DefaultResolverTimeout
}
switch strings.ToLower(ns.Protocol) {
case "tcp":
ns.exchanger = &dnsExchanger{
endpoint: ns.Addr,
client: &dns.Client{
Net: "tcp",
Timeout: timeout,
},
}
case "tls":
cfg := &tls.Config{
ServerName: ns.Hostname,
}
if cfg.ServerName == "" {
cfg.InsecureSkipVerify = true
}
ns.exchanger = &dnsExchanger{
endpoint: ns.Addr,
client: &dns.Client{
Net: "tcp-tls",
Timeout: timeout,
TLSConfig: cfg,
},
}
case "https":
u, err := url.Parse(ns.Addr)
if err != nil {
return err
}
cfg := &tls.Config{ServerName: u.Hostname()}
transport := &http.Transport{
TLSClientConfig: cfg,
DisableCompression: true,
MaxIdleConns: 1,
}
http2.ConfigureTransport(transport)
ns.exchanger = &dohExchanger{
endpoint: u,
client: &http.Client{
Transport: transport,
Timeout: timeout,
},
}
case "udp":
fallthrough
default:
ns.exchanger = &dnsExchanger{
endpoint: ns.Addr,
client: &dns.Client{
Net: "udp",
Timeout: timeout,
},
}
}
return nil
}
func (ns NameServer) String() string {
addr := ns.Addr
prot := ns.Protocol
if _, port, _ := net.SplitHostPort(addr); port == "" {
addr = net.JoinHostPort(addr, "53")
}
if prot == "" {
prot = "udp"
}
return fmt.Sprintf("%s/%s", addr, prot)
}
type resolver struct {
Servers []NameServer
mCache *sync.Map
TTL time.Duration
period time.Duration
domain string
stopped chan struct{}
mux sync.RWMutex
}
// NewResolver create a new Resolver with the given name servers and resolution timeout.
func NewResolver(ttl time.Duration, servers ...NameServer) ReloadResolver {
r := newResolver(ttl, servers...)
return r
}
func newResolver(ttl time.Duration, servers ...NameServer) *resolver {
return &resolver{
Servers: servers,
TTL: ttl,
mCache: &sync.Map{},
stopped: make(chan struct{}),
}
}
func (r *resolver) copyServers() []NameServer {
var servers []NameServer
for i := range r.Servers {
servers = append(servers, r.Servers[i])
}
return servers
}
func (r *resolver) Resolve(host string) (ips []net.IP, err error) {
if r == nil {
return
}
var domain string
var ttl time.Duration
var servers []NameServer
r.mux.RLock()
domain = r.domain
ttl = r.TTL
servers = r.copyServers()
r.mux.RUnlock()
if ip := net.ParseIP(host); ip != nil {
return []net.IP{ip}, nil
}
if !strings.Contains(host, ".") && domain != "" {
host = host + "." + domain
}
ips = r.loadCache(host, ttl)
if len(ips) > 0 {
if Debug {
log.Logf("[resolver] cache hit %s: %v", host, ips)
}
return
}
for _, ns := range servers {
ips, ttl, err = r.resolve(ns.exchanger, host)
if err != nil {
log.Logf("[resolver] %s via %s : %s", host, ns, err)
continue
}
if Debug {
log.Logf("[resolver] %s via %s %v(ttl: %v)", host, ns, ips, ttl)
}
if len(ips) > 0 {
break
}
}
r.storeCache(host, ips, ttl)
return
}
func (*resolver) resolve(ex Exchanger, host string) (ips []net.IP, ttl time.Duration, err error) {
if ex == nil {
return
}
query := dns.Msg{}
query.SetQuestion(dns.Fqdn(host), dns.TypeA)
mr, err := ex.Exchange(context.Background(), &query)
if err != nil {
return
}
for _, ans := range mr.Answer {
if ar, _ := ans.(*dns.A); ar != nil {
ips = append(ips, ar.A)
ttl = time.Duration(ar.Header().Ttl) * time.Second
}
}
return
}
type resolverCacheItem struct {
IPs []net.IP
ts int64
ttl time.Duration
}
func (r *resolver) loadCache(name string, ttl time.Duration) []net.IP {
if name == "" || ttl < 0 {
return nil
}
if v, ok := r.mCache.Load(name); ok {
item, _ := v.(*resolverCacheItem)
if ttl == 0 {
ttl = item.ttl
}
if time.Since(time.Unix(item.ts, 0)) > ttl {
r.mCache.Delete(name)
return nil
}
return item.IPs
}
return nil
}
func (r *resolver) storeCache(name string, ips []net.IP, ttl time.Duration) {
if name == "" || len(ips) == 0 || ttl < 0 {
return
}
r.mCache.Store(name, &resolverCacheItem{
IPs: ips,
ts: time.Now().Unix(),
ttl: ttl,
})
}
func (r *resolver) Reload(rd io.Reader) error {
var ttl, timeout, period time.Duration
var domain string
var nss []NameServer
if rd == nil || r.Stopped() {
return nil
}
scanner := bufio.NewScanner(rd)
for scanner.Scan() {
line := scanner.Text()
ss := splitLine(line)
if len(ss) == 0 {
continue
}
switch ss[0] {
case "timeout": // timeout option
if len(ss) > 1 {
timeout, _ = time.ParseDuration(ss[1])
}
case "ttl": // ttl option
if len(ss) > 1 {
ttl, _ = time.ParseDuration(ss[1])
}
case "reload": // reload option
if len(ss) > 1 {
period, _ = time.ParseDuration(ss[1])
}
case "domain":
if len(ss) > 1 {
domain = ss[1]
}
case "search", "sortlist", "options": // we don't support these features in /etc/resolv.conf
case "nameserver": // nameserver option, compatible with /etc/resolv.conf
if len(ss) <= 1 {
break
}
ss = ss[1:]
fallthrough
default:
var ns NameServer
switch len(ss) {
case 0:
break
case 1:
ns.Addr = ss[0]
case 2:
ns.Addr = ss[0]
ns.Protocol = ss[1]
default:
ns.Addr = ss[0]
ns.Protocol = ss[1]
ns.Hostname = ss[2]
}
if strings.HasPrefix(ns.Addr, "https") {
ns.Protocol = "https"
}
ns.Timeout = timeout
if err := ns.Init(); err == nil {
nss = append(nss, ns)
}
}
}
if err := scanner.Err(); err != nil {
return err
}
r.mux.Lock()
r.TTL = ttl
r.domain = domain
r.period = period
r.Servers = nss
r.mux.Unlock()
return nil
}
func (r *resolver) Period() time.Duration {
if r.Stopped() {
return -1
}
r.mux.RLock()
defer r.mux.RUnlock()
return r.period
}
// Stop stops reloading.
func (r *resolver) Stop() {
select {
case <-r.stopped:
default:
close(r.stopped)
}
}
// Stopped checks whether the reloader is stopped.
func (r *resolver) Stopped() bool {
select {
case <-r.stopped:
return true
default:
return false
}
}
func (r *resolver) String() string {
if r == nil {
return ""
}
r.mux.RLock()
defer r.mux.RUnlock()
b := &bytes.Buffer{}
fmt.Fprintf(b, "TTL %v\n", r.TTL)
fmt.Fprintf(b, "Reload %v\n", r.period)
fmt.Fprintf(b, "Domain %v\n", r.domain)
for i := range r.Servers {
fmt.Fprintln(b, r.Servers[i])
}
return b.String()
}
// Exchanger is an interface for DNS synchronous query.
type Exchanger interface {
Exchange(ctx context.Context, query *dns.Msg) (*dns.Msg, error)
}
type dnsExchanger struct {
endpoint string
client *dns.Client
}
func (ex *dnsExchanger) Exchange(ctx context.Context, query *dns.Msg) (*dns.Msg, error) {
ep := ex.endpoint
if _, port, _ := net.SplitHostPort(ep); port == "" {
ep = net.JoinHostPort(ep, "53")
}
mr, _, err := ex.client.Exchange(query, ep)
return mr, err
}
type dohExchanger struct {
endpoint *url.URL
client *http.Client
}
// reference: https://github.com/cloudflare/cloudflared/blob/master/tunneldns/https_upstream.go#L54
func (ex *dohExchanger) Exchange(ctx context.Context, query *dns.Msg) (*dns.Msg, error) {
queryBuf, err := query.Pack()
if err != nil {
return nil, fmt.Errorf("failed to pack DNS query: %s", err)
}
// No content negotiation for now, use DNS wire format
buf, backendErr := ex.exchangeWireformat(queryBuf)
if backendErr == nil {
response := &dns.Msg{}
if err := response.Unpack(buf); err != nil {
return nil, fmt.Errorf("failed to unpack DNS response from body: %s", err)
}
response.Id = query.Id
return response, nil
}
return nil, backendErr
}
// Perform message exchange with the default UDP wireformat defined in current draft
// https://datatracker.ietf.org/doc/draft-ietf-doh-dns-over-https
func (ex *dohExchanger) exchangeWireformat(msg []byte) ([]byte, error) {
req, err := http.NewRequest("POST", ex.endpoint.String(), bytes.NewBuffer(msg))
if err != nil {
return nil, fmt.Errorf("failed to create an HTTPS request: %s", err)
}
req.Header.Add("Content-Type", "application/dns-udpwireformat")
req.Host = ex.endpoint.Hostname()
resp, err := ex.client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to perform an HTTPS request: %s", err)
}
// Check response status code
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("returned status code %d", resp.StatusCode)
}
// Read wireformat response from the body
buf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read the response body: %s", err)
}
return buf, nil
}