-
Notifications
You must be signed in to change notification settings - Fork 248
/
upstream_dot.go
87 lines (74 loc) · 1.96 KB
/
upstream_dot.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
package upstream
import (
"net"
"sync"
"github.com/AdguardTeam/golibs/log"
"github.com/joomcode/errorx"
"github.com/miekg/dns"
)
//
// DNS-over-TLS
//
type dnsOverTLS struct {
boot *bootstrapper
pool *TLSPool
sync.RWMutex // protects pool
}
func (p *dnsOverTLS) Address() string { return p.boot.address }
func (p *dnsOverTLS) Exchange(m *dns.Msg) (*dns.Msg, error) {
var pool *TLSPool
p.RLock()
pool = p.pool
p.RUnlock()
if pool == nil {
p.Lock()
// lazy initialize it
p.pool = &TLSPool{boot: p.boot}
p.Unlock()
}
p.RLock()
poolConn, err := p.pool.Get()
p.RUnlock()
if err != nil {
return nil, errorx.Decorate(err, "Failed to get a connection from TLSPool to %s", p.Address())
}
reply, err := p.exchangeConn(poolConn, m)
if err != nil {
log.Tracef("The TLS connection is expired due to %s", err)
// The pooled connection might have been closed already (see https://github.com/AdguardTeam/dnsproxy/issues/3)
// So we're trying to re-connect right away here.
// We are forcing creation of a new connection instead of calling Get() again
// as there's no guarantee that other pooled connections are intact
p.RLock()
poolConn, err = p.pool.Create()
p.RUnlock()
if err != nil {
return nil, errorx.Decorate(err, "Failed to create a new connection from TLSPool to %s", p.Address())
}
// Retry sending the DNS request
reply, err = p.exchangeConn(poolConn, m)
}
if err == nil {
p.RLock()
p.pool.Put(poolConn)
p.RUnlock()
}
return reply, err
}
func (p *dnsOverTLS) exchangeConn(poolConn net.Conn, m *dns.Msg) (*dns.Msg, error) {
c := dns.Conn{Conn: poolConn}
err := c.WriteMsg(m)
if err != nil {
poolConn.Close()
return nil, errorx.Decorate(err, "Failed to send a request to %s", p.Address())
}
reply, err := c.ReadMsg()
if err != nil {
poolConn.Close()
return nil, errorx.Decorate(err, "Failed to read a request from %s", p.Address())
}
if err == nil && reply.Id != m.Id {
err = dns.ErrId
}
return reply, err
}