-
Notifications
You must be signed in to change notification settings - Fork 2
/
doh.go
95 lines (90 loc) · 2.25 KB
/
doh.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
95
package main
import (
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"strings"
"sync"
"time"
)
// Doh 找不到对应的主机记录
var DohNotFoundErr = errors.New("Doh cannot find matching record")
// Doh JSON 报文
type DohData struct {
Status int `json:"Status"`
Tc bool `json:"TC"`
Rd bool `json:"RD"`
Ra bool `json:"RA"`
Ad bool `json:"AD"`
Cd bool `json:"CD"`
Question []struct {
Name string `json:"name"`
Type int `json:"type"`
} `json:"Question"`
Answer []struct {
Name string `json:"name"`
Type int `json:"type"`
TTL int `json:"TTL"`
Expires string `json:"Expires"`
Data string `json:"data"`
} `json:"Answer"`
EdnsClientSubnet string `json:"edns_client_subnet"`
}
func doh(query string, host string) (*DohData, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("%s?name=%s&type=A", query, host), nil)
req.Header.Set("Accept", "application/dns-json")
if err != nil {
return nil, err
}
resp, err := (&http.Client{Timeout: time.Second * 30}).Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var data DohData
var dec = json.NewDecoder(resp.Body)
if err := dec.Decode(&data); err != nil {
return nil, err
}
return &data, nil
}
func lookup(dohs []string, cache *sync.Map, host string) (net.Conn, error) {
// 读取 DNS 缓存
host = strings.TrimPrefix(host, "www.")
if ip, ok := cache.Load(host); ok {
conn, err := net.Dial("tcp", ip.(string)+":443")
if err == nil {
return conn, nil
}
}
// 通过 DOH 获取正确的 IP
for i := range dohs {
data, err := doh(dohs[i], host)
if err != nil {
continue
}
for _, answer := range data.Answer {
if answer.Data == "" || answer.Data == "127.0.0.1" ||
len(answer.Data) < 7 || len(answer.Data) > 15 ||
strings.Contains(answer.Name, "cdn") {
continue
}
conn, err := net.Dial("tcp", answer.Data+":443")
if err != nil {
continue
}
DnsCache.Store(host, answer.Data)
DnsCache.Range(func(key, value any) bool {
return true
})
return conn, nil
}
}
// 可能被套上了CDN,因此尝试找上级域名的IP试试
if n := strings.Split(host, "."); len(n) >= 3 {
return lookup(dohs, cache, strings.Join(n[1:], "."))
}
return nil, DohNotFoundErr
}