-
Notifications
You must be signed in to change notification settings - Fork 240
/
bootstrap.go
executable file
·251 lines (210 loc) · 7.4 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
242
243
244
245
246
247
248
249
250
251
package upstream
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"net"
"net/url"
"sync"
"time"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"golang.org/x/net/http2"
)
// NextProtoDQ is the ALPN token for DoQ. During connection establishment,
// DNS/QUIC support is indicated by selecting the ALPN token "dq" in the
// crypto handshake.
// Current draft version:
// https://datatracker.ietf.org/doc/html/draft-ietf-dprive-dnsoquic-02
const NextProtoDQ = "doq-i02"
// compatProtoDQ is a list of ALPN tokens used by a QUIC connection.
// NextProtoDQ is the latest draft version supported by dnsproxy, but it also
// includes previous drafts.
var compatProtoDQ = []string{NextProtoDQ, "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 {
var cancel func()
ctx, cancel = context.WithTimeout(context.Background(), n.options.Timeout)
defer cancel()
} else {
ctx = context.Background()
}
addrs, err := LookupParallel(ctx, n.resolvers, host)
if err != nil {
return nil, nil, fmt.Errorf("lookup %s: %w", host, err)
}
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,
}
// Depending on the URL scheme, we choose what ALPN will be advertised by
// the client.
switch n.URL.Scheme {
case "tls":
// Don't use the ALPN since some servers currently do not accept it.
//
// See https://github.com/ameshkov/dnslookup/issues/19.
case "https":
tlsConfig.NextProtos = []string{http2.NextProtoTLS, "http/1.1"}
case "quic":
tlsConfig.NextProtos = 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,
}
return func(ctx context.Context, network, _ string) (net.Conn, error) {
if len(addresses) == 0 {
return nil, errors.Error("no addresses")
}
var 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()
conn, 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 conn, nil
}
errs = append(errs, err)
log.Tracef("dialer failed to initialize connection to %s, in %s, cause: %s", resolverAddress, elapsed, err)
}
return nil, errors.List("all dialers failed", errs...)
}
}