-
Notifications
You must be signed in to change notification settings - Fork 237
/
upstream_plain.go
76 lines (59 loc) · 1.71 KB
/
upstream_plain.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
package upstream
import (
"net/url"
"time"
"github.com/AdguardTeam/golibs/log"
"github.com/miekg/dns"
)
// plainDNS is a struct that implements the Upstream interface for the regular
// DNS protocol.
type plainDNS struct {
address string
timeout time.Duration
preferTCP bool
}
// type check
var _ Upstream = &plainDNS{}
// newPlain returns the plain DNS Upstream.
func newPlain(uu *url.URL, timeout time.Duration, preferTCP bool) (u *plainDNS) {
addPort(uu, defaultPortPlain)
return &plainDNS{
address: uu.Host,
timeout: timeout,
preferTCP: preferTCP,
}
}
// Address implements the Upstream interface for *plainDNS.
func (p *plainDNS) Address() string {
if p.preferTCP {
return "tcp://" + p.address
}
return p.address
}
// Exchange implements the Upstream interface for *plainDNS.
func (p *plainDNS) Exchange(m *dns.Msg) (*dns.Msg, error) {
if p.preferTCP {
tcpClient := dns.Client{Net: "tcp", Timeout: p.timeout}
logBegin(p.Address(), m)
reply, _, tcpErr := tcpClient.Exchange(m, p.address)
logFinish(p.Address(), tcpErr)
return reply, tcpErr
}
client := dns.Client{Timeout: p.timeout, UDPSize: dns.MaxMsgSize}
logBegin(p.Address(), m)
reply, _, err := client.Exchange(m, p.address)
logFinish(p.Address(), err)
if reply != nil && reply.Truncated {
log.Tracef("Truncated message was received, retrying over TCP, question: %s", m.Question[0].String())
tcpClient := dns.Client{Net: "tcp", Timeout: p.timeout}
logBegin(p.Address(), m)
reply, _, err = tcpClient.Exchange(m, p.address)
logFinish(p.Address(), err)
}
return reply, err
}
// Close implements the Upstream interface for *plainDNS.
func (p *plainDNS) Close() (err error) {
// Nothing to close here.
return nil
}