-
Notifications
You must be signed in to change notification settings - Fork 18
/
dns.go
100 lines (78 loc) · 2.13 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
package proxy
import (
"context"
"net"
"time"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
)
type dnsEx struct {
Timeout time.Duration
Options
}
// Options define the options understood by dns.Exchange.
type Options struct {
ForceTCP bool // If true use TCP for upstream no matter what
}
func newDNSEx() *dnsEx {
return newDNSExWithOption(Options{})
}
func newDNSExWithOption(opt Options) *dnsEx {
return &dnsEx{Timeout: defaultTimeout * time.Second, Options: opt}
}
func (d *dnsEx) Transport() string {
if d.Options.ForceTCP {
return "tcp"
}
// The protocol will be determined by `state.Proto()` during Exchange.
return ""
}
func (d *dnsEx) Protocol() string { return "dns" }
func (d *dnsEx) OnShutdown(p *Proxy) error { return nil }
func (d *dnsEx) OnStartup(p *Proxy) error { return nil }
// Exchange implements the Exchanger interface.
func (d *dnsEx) Exchange(ctx context.Context, addr string, state request.Request) (*dns.Msg, error) {
proto := state.Proto()
if d.Options.ForceTCP {
proto = "tcp"
}
co, err := net.DialTimeout(proto, addr, d.Timeout)
if err != nil {
return nil, err
}
reply, _, err := d.ExchangeConn(state.Req, co)
co.Close()
if reply != nil && reply.Truncated {
// Suppress proxy error for truncated responses
err = nil
}
if err != nil {
return nil, err
}
reply.Id = state.Req.Id
return reply, nil
}
func (d *dnsEx) ExchangeConn(m *dns.Msg, co net.Conn) (*dns.Msg, time.Duration, error) {
start := time.Now()
r, err := exchange(m, co)
rtt := time.Since(start)
return r, rtt, err
}
func exchange(m *dns.Msg, co net.Conn) (*dns.Msg, error) {
opt := m.IsEdns0()
udpsize := uint16(dns.MinMsgSize)
// If EDNS0 is used use that for size.
if opt != nil && opt.UDPSize() >= dns.MinMsgSize {
udpsize = opt.UDPSize()
}
dnsco := &dns.Conn{Conn: co, UDPSize: udpsize}
writeDeadline := time.Now().Add(defaultTimeout)
dnsco.SetWriteDeadline(writeDeadline)
if err := dnsco.WriteMsg(m); err != nil {
log.Debugf("Failed to send message: %v", err)
return nil, err
}
readDeadline := time.Now().Add(defaultTimeout)
co.SetReadDeadline(readDeadline)
return dnsco.ReadMsg()
}