-
Notifications
You must be signed in to change notification settings - Fork 0
/
picker.go
70 lines (61 loc) · 1.39 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
package dot
import (
"math/rand"
"net"
"github.com/shplack/dns/pkg/provider"
"github.com/qdm12/golibs/crypto/random/sources/maphash"
)
type picker struct {
rand *rand.Rand
}
func newPicker() *picker {
source := maphash.New()
return &picker{
rand: rand.New(source), //nolint:gosec
}
}
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) IP(ips []net.IP) net.IP {
switch len(ips) {
case 0:
return nil
case 1:
return ips[0]
default:
index := p.rand.Intn(len(ips))
return ips[index]
}
}
func (p *picker) DoTIP(server provider.DoTServer, ipv6 bool) net.IP {
if ipv6 {
if ip := p.IP(server.IPv6); ip != nil {
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) 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) DNSIP(server provider.DNSServer, ipv6 bool) net.IP {
if ipv6 {
if ip := p.IP(server.IPv6); ip != nil {
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)
}