-
Notifications
You must be signed in to change notification settings - Fork 0
/
dot.go
94 lines (87 loc) · 2.55 KB
/
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
88
89
90
91
92
93
94
// Package dot provides some known DNS-over-TLS (DOT) resolvers.
package dot
import (
"context"
"crypto/tls"
"errors"
"math/rand/v2"
"net"
"net/netip"
"time"
)
// Cloudflare returns Resolver that uses Cloudflare service on 1.1.1.1 and
// 1.0.0.1 on port 853.
//
// See https://developers.cloudflare.com/1.1.1.1/dns-over-tls/ for details.
func Cloudflare() *net.Resolver {
return newResolver("cloudflare-dns.com", "1.1.1.1:853", "1.0.0.1:853")
}
// Quad9 returns Resolver that uses Quad9 service on 9.9.9.9 and 149.112.112.112
// on port 853.
//
// See https://quad9.net/faq/ for details.
func Quad9() *net.Resolver {
return newResolver("dns.quad9.net", "9.9.9.9:853", "149.112.112.112:853")
}
// Google returns Resolver that uses Google Public DNS service on 8.8.8.8 and
// 8.8.4.4 on port 853.
//
// See https://developers.google.com/speed/public-dns/ for details.
func Google() *net.Resolver {
return newResolver("dns.google", "8.8.8.8:853", "8.8.4.4:853")
}
// LibreOps returns Resolver that uses LibreDNS service on 116.202.176.26 on
// port 853 operated by LibreOps.
//
// See https://libredns.gr/ for details.
func LibreOps() *net.Resolver {
return newResolver("dot.libredns.gr", "116.202.176.26:853")
}
// New creates and returns a new DNS-over-TLS (DoT) Resolver.
//
// It takes a server name for TLS verification and one or more IP:port
// addresses of DoT servers.
//
// The returned Resolver uses a random selection of the provided addresses
// for each DNS query.
//
// Example:
//
// googlePublic, err := dot.New("dns.google", "8.8.8.8:853", "8.8.4.4:853")
func New(serverName string, addrs ...string) (*net.Resolver, error) {
if serverName == "" {
return nil, errors.New("dot: server name cannot be empty")
}
if len(addrs) == 0 {
return nil, errors.New("dot: addrs cannot be empty")
}
for _, addr := range addrs {
if _, err := netip.ParseAddrPort(addr); err != nil {
return nil, err
}
}
var d net.Dialer
cfg := &tls.Config{
ServerName: serverName,
ClientSessionCache: tls.NewLRUClientSessionCache(0),
}
return &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
conn, err := d.DialContext(ctx, "tcp", addrs[rand.IntN(len(addrs))])
if err != nil {
return nil, err
}
conn.(*net.TCPConn).SetKeepAlive(true)
conn.(*net.TCPConn).SetKeepAlivePeriod(3 * time.Minute)
return tls.Client(conn, cfg), nil
},
}, nil
}
func newResolver(serverName string, addrs ...string) *net.Resolver {
r, err := New(serverName, addrs...)
if err != nil {
panic(err)
}
return r
}