-
-
Notifications
You must be signed in to change notification settings - Fork 37
/
dialer.go
79 lines (67 loc) · 1.74 KB
/
dialer.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
package dot
import (
"context"
"crypto/tls"
"fmt"
"net"
"github.com/qdm12/dns/v2/internal/picker"
"github.com/qdm12/dns/v2/pkg/provider"
)
type Dialer struct {
picker *picker.Picker
servers []provider.DoTServer
ipv6 bool
netDialer *net.Dialer
warner Warner
metrics Metrics
}
func New(settings Settings) (dial *Dialer, err error) {
settings.SetDefaults()
err = settings.Validate()
if err != nil {
return nil, fmt.Errorf("validating settings: %w", err)
}
servers := make([]provider.DoTServer, len(settings.UpstreamResolvers))
for i, upstreamResolver := range settings.UpstreamResolvers {
servers[i] = upstreamResolver.DoT
}
return &Dialer{
picker: picker.New(),
servers: servers,
ipv6: settings.IPVersion == "ipv6",
netDialer: &net.Dialer{
Timeout: settings.Timeout,
},
warner: settings.Warner,
metrics: settings.Metrics,
}, nil
}
func (d *Dialer) String() string {
return "dns over tls"
}
func (d *Dialer) Dial(ctx context.Context, _, _ string) (
conn net.Conn, err error,
) {
serverName, serverAddress := pickNameAddress(d.picker,
d.servers, d.ipv6)
conn, err = d.netDialer.DialContext(ctx, "tcp", serverAddress)
if err != nil {
d.warner.Warn(err.Error())
d.metrics.DoTDialInc(serverName, serverAddress, "error")
return nil, err
}
d.metrics.DoTDialInc(serverName, serverAddress, "success")
tlsConf := &tls.Config{
MinVersion: tls.VersionTLS12,
ServerName: serverName,
}
// TODO handshake? See tls.DialWithDialer
return tls.Client(conn, tlsConf), nil
}
func pickNameAddress(picker *picker.Picker, servers []provider.DoTServer,
ipv6 bool,
) (name, address string) {
server := picker.DoTServer(servers)
addrPort := picker.DoTAddrPort(server, ipv6)
return server.Name, addrPort.String()
}