-
Notifications
You must be signed in to change notification settings - Fork 248
/
bootstrap.go
executable file
·241 lines (203 loc) · 7.21 KB
/
bootstrap.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
package upstream
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"net"
"net/url"
"sync"
"time"
"github.com/AdguardTeam/golibs/log"
"github.com/joomcode/errorx"
"golang.org/x/net/http2"
)
// NextProtoDQ - During connection establishment, DNS/QUIC support is indicated
// by selecting the ALPN token "dq" in the crypto handshake.
const NextProtoDQ = "doq-i02"
// compatProtoDQ - ALPNs for backwards compatibility
var compatProtoDQ = []string{"doq-i00", "dq", "doq"}
// RootCAs is the CertPool that must be used by all upstreams
// Redefining RootCAs makes sense on iOS to overcome the 15MB memory limit of the NEPacketTunnelProvider
// nolint
var RootCAs *x509.CertPool
// CipherSuites - custom list of TLSv1.2 ciphers
// nolint
var CipherSuites []uint16
// TODO: refactor bootstrapper, it's overcomplicated and hard to understand what it does
type bootstrapper struct {
URL *url.URL
resolvers []*Resolver // list of Resolvers to use to resolve hostname, if necessary
dialContext dialHandler // specifies the dial function for creating unencrypted TCP connections.
resolvedConfig *tls.Config
sync.RWMutex
// stores options for AddressToUpstream func:
// callbacks for checking certificates, timeout,
// the need to verify the server certificate,
// the addresses of upstream servers, etc
options *Options
}
// newBootstrapperResolved creates a new bootstrapper that already contains resolved config.
// This can be done only in the case when we already know the resolver IP address.
// options -- Upstream customization options
func newBootstrapperResolved(upsURL *url.URL, options *Options) (*bootstrapper, error) {
// get a host without port
host, port, err := net.SplitHostPort(upsURL.Host)
if err != nil {
return nil, fmt.Errorf("bootstrapper requires port in address %s", upsURL.String())
}
var resolverAddresses []string
for _, ip := range options.ServerIPAddrs {
addr := net.JoinHostPort(ip.String(), port)
resolverAddresses = append(resolverAddresses, addr)
}
b := &bootstrapper{
URL: upsURL,
options: options,
}
b.dialContext = b.createDialContext(resolverAddresses)
b.resolvedConfig = b.createTLSConfig(host)
return b, nil
}
// newBootstrapper initializes a new bootstrapper instance
// address -- original resolver address string (i.e. tls://one.one.one.one:853)
// options -- Upstream customization options
func newBootstrapper(address *url.URL, options *Options) (*bootstrapper, error) {
resolvers := []*Resolver{}
if len(options.Bootstrap) != 0 {
// Create a list of resolvers for parallel lookup
for _, boot := range options.Bootstrap {
r, err := NewResolver(boot, options)
if err != nil {
return nil, err
}
resolvers = append(resolvers, r)
}
} else {
r, _ := NewResolver("", options) // NewResolver("") always succeeds
// nil resolver if the default one
resolvers = append(resolvers, r)
}
return &bootstrapper{
URL: address,
resolvers: resolvers,
options: options,
}, nil
}
// dialHandler specifies the dial function for creating unencrypted TCP connections.
type dialHandler func(ctx context.Context, network, addr string) (net.Conn, error)
// will get usable IP address from Address field, and caches the result
func (n *bootstrapper) get() (*tls.Config, dialHandler, error) {
n.RLock()
if n.dialContext != nil && n.resolvedConfig != nil { // fast path
tlsConfig, dialContext := n.resolvedConfig, n.dialContext
n.RUnlock()
return tlsConfig.Clone(), dialContext, nil
}
//
// Slow path: resolve the IP address of the n.address's host
//
// get a host without port
addr := n.URL
host, port, err := net.SplitHostPort(addr.Host)
if err != nil {
n.RUnlock()
return nil, nil, fmt.Errorf("bootstrapper requires port in address %s", addr.String())
}
// if n.address's host is an IP, just use it right away
ip := net.ParseIP(host)
if ip != nil {
n.RUnlock()
// Upgrade lock to protect n.resolved
resolverAddress := net.JoinHostPort(host, port)
n.Lock()
defer n.Unlock()
n.dialContext = n.createDialContext([]string{resolverAddress})
n.resolvedConfig = n.createTLSConfig(host)
return n.resolvedConfig, n.dialContext, nil
}
// Don't lock anymore (we can launch multiple lookup requests at a time)
// Otherwise, it might mess with the timeout specified for the Upstream
// See here: https://github.com/AdguardTeam/dnsproxy/issues/15
n.RUnlock()
//
// if it's a hostname
//
var ctx context.Context
if n.options.Timeout > 0 {
ctxWithTimeout, cancel := context.WithTimeout(context.TODO(), n.options.Timeout)
defer cancel() // important to avoid a resource leak
ctx = ctxWithTimeout
} else {
ctx = context.Background()
}
addrs, err := LookupParallel(ctx, n.resolvers, host)
if err != nil {
return nil, nil, errorx.Decorate(err, "failed to lookup %s", host)
}
resolved := []string{}
for _, addr := range addrs {
if addr.IP.To4() == nil && addr.IP.To16() == nil {
continue
}
resolved = append(resolved, net.JoinHostPort(addr.String(), port))
}
if len(resolved) == 0 {
// couldn't find any suitable IP address
return nil, nil, fmt.Errorf("couldn't find any suitable IP address for host %s", host)
}
n.Lock()
defer n.Unlock()
n.dialContext = n.createDialContext(resolved)
n.resolvedConfig = n.createTLSConfig(host)
return n.resolvedConfig, n.dialContext, nil
}
// createTLSConfig creates a client TLS config
func (n *bootstrapper) createTLSConfig(host string) *tls.Config {
tlsConfig := &tls.Config{
ServerName: host,
RootCAs: RootCAs,
CipherSuites: CipherSuites,
MinVersion: tls.VersionTLS12,
InsecureSkipVerify: n.options.InsecureSkipVerify,
VerifyPeerCertificate: n.options.VerifyServerCertificate,
}
// The supported application level protocols should be specified only
// for DNS-over-HTTPS and DNS-over-QUIC connections.
//
// See https://github.com/AdguardTeam/AdGuardHome/issues/2681.
if n.URL.Scheme != "tls" {
tlsConfig.NextProtos = append([]string{
"http/1.1", http2.NextProtoTLS, NextProtoDQ,
}, compatProtoDQ...)
}
return tlsConfig
}
// createDialContext returns dialContext function that tries to establish connection with all given addresses one by one
func (n *bootstrapper) createDialContext(addresses []string) (dialContext dialHandler) {
dialer := &net.Dialer{
Timeout: n.options.Timeout,
}
dialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
errs := []error{}
// Return first connection without error
// Note that we're using bootstrapped resolverAddress instead of what's passed to the function
for _, resolverAddress := range addresses {
log.Tracef("Dialing to %s", resolverAddress)
start := time.Now()
con, err := dialer.DialContext(ctx, network, resolverAddress)
elapsed := time.Since(start)
if err == nil {
log.Tracef("dialer has successfully initialized connection to %s in %s", resolverAddress, elapsed)
return con, err
}
errs = append(errs, err)
log.Tracef("dialer failed to initialize connection to %s, in %s, cause: %s", resolverAddress, elapsed, err)
}
if len(errs) == 0 {
return nil, fmt.Errorf("all dialers failed to initialize connection")
}
return nil, errorx.DecorateMany("all dialers failed to initialize connection: ", errs...)
}
return
}