-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
picker.go
80 lines (70 loc) · 1.72 KB
/
picker.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
package picker
import (
"math/rand"
"net/netip"
"github.com/qdm12/dns/v2/pkg/provider"
"github.com/qdm12/golibs/crypto/random/sources/maphash"
)
type Picker struct {
rand *rand.Rand
}
// New returns a new fast thread safe random picker
// to use for DNS servers and their IP addresses.
func New() *Picker {
source := maphash.New()
return &Picker{
rand: rand.New(source), //nolint:gosec
}
}
func (p *Picker) DoHServer(servers []provider.DoHServer) provider.DoHServer {
index := 0
if nServers := len(servers); nServers > 1 {
index = p.rand.Intn(nServers)
}
return servers[index]
}
func (p *Picker) DoTServer(servers []provider.DoTServer) provider.DoTServer {
index := 0
if nServers := len(servers); nServers > 1 {
index = p.rand.Intn(nServers)
}
return servers[index]
}
func (p *Picker) DNSServer(servers []provider.DNSServer) provider.DNSServer {
index := 0
if nServers := len(servers); nServers > 1 {
index = p.rand.Intn(nServers)
}
return servers[index]
}
func (p *Picker) DoTIP(server provider.DoTServer, ipv6 bool) netip.Addr {
if ipv6 {
if ip := p.IP(server.IPv6); ip.IsValid() {
return ip
}
// if there is no IPv6, fall back to an IPv4 address
// as all provider have at least an IPv4 address.
}
return p.IP(server.IPv4)
}
func (p *Picker) DNSIP(server provider.DNSServer, ipv6 bool) netip.Addr {
if ipv6 {
if ip := p.IP(server.IPv6); ip.IsValid() {
return ip
}
// if there is no IPv6, fall back to an IPv4 address
// as all provider have at least an IPv4 address.
}
return p.IP(server.IPv4)
}
func (p *Picker) IP(ips []netip.Addr) netip.Addr {
switch len(ips) {
case 0:
return netip.Addr{}
case 1:
return ips[0]
default:
index := p.rand.Intn(len(ips))
return ips[index]
}
}