forked from miaokobot/miaospeed
/
dns.go
85 lines (73 loc) · 2 KB
/
dns.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
package utils
import (
"context"
"fmt"
"net"
"strings"
"time"
"github.com/moshaoli688/miaospeed/interfaces"
"github.com/moshaoli688/miaospeed/utils/structs/memutils"
"github.com/moshaoli688/miaospeed/utils/structs/obliviousmap"
)
var DnsCache *obliviousmap.ObliviousMap[*interfaces.IPStacks]
// queryServer = "8.8.8.8:53"
func DNSLookuper(addr string, queryServers []string) []net.IP {
if len(queryServers) == 0 {
result, _ := net.LookupIP(addr)
return result
}
ipSets := map[string]net.IP{}
for _, server := range queryServers {
r := &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
d := net.Dialer{
Timeout: time.Millisecond * time.Duration(3000),
}
return d.DialContext(ctx, network, server)
},
}
addrs, _ := r.LookupIPAddr(context.Background(), addr)
for _, ia := range addrs {
ipSets[ia.IP.String()] = ia.IP
}
}
ips := make([]net.IP, len(ipSets))
j := 0
for _, ia := range ipSets {
ips[j] = ia
j += 1
}
return ips
}
func LookupIPv46(addr string, retry int, queryServers []string) *interfaces.IPStacks {
token := fmt.Sprintf("%v|%v", addr, queryServers)
if r, ok := DnsCache.Get(token); ok && r != nil {
return r
}
netips := []net.IP{}
for i := 0; i < retry && len(netips) == 0; i += 1 {
netips = DNSLookuper(addr, queryServers)
}
DLogf("DNS Lookup | dns=%v result=%v", queryServers, netips)
ipstacks := (&interfaces.IPStacks{}).Init()
for _, ip := range netips {
ipStr := ip.String()
if !strings.Contains(ipStr, ":") {
ipstacks.IPv4 = append(ipstacks.IPv4, ipStr)
} else {
ipstacks.IPv6 = append(ipstacks.IPv6, ipStr)
}
}
if ipstacks.Count() > 0 {
DnsCache.Set(token, ipstacks)
} else {
DWarnf("DNS Resolver | fail to resolve domain=%s", addr)
}
return ipstacks
}
func init() {
memIPStacks := memutils.MemDriverMemory[*interfaces.IPStacks]{}
memIPStacks.Init()
DnsCache = obliviousmap.NewObliviousMap[*interfaces.IPStacks]("DnsCache/", time.Minute, true, &memIPStacks)
}