-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdoh_service.go
199 lines (168 loc) · 4.54 KB
/
doh_service.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
package main
// https://developers.cloudflare.com/1.1.1.1/dns-over-https/wireformat/
import (
"bytes"
"crypto/tls"
"io/ioutil"
"log"
"net/http"
"strconv"
"time"
"github.com/miekg/dns"
"github.com/patrickmn/go-cache"
)
type DohError struct {
msg string
}
func (e *DohError) Error() string {
return e.msg
}
func newErr(msg string) error {
return &DohError{msg}
}
const CLOUDFLARE_DNS = "1.1.1.1:53"
const CLOUDFLARE_DOH_HOST = "cloudflare-dns.com."
const CLOUDFLARE_DOH_URL = "https://cloudflare-dns.com/dns-query"
// Create HTTPS request and POST.
func makeHttpsRequest(wire []byte) (respWire []byte, err error) {
// disable security check for client
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
buff := bytes.NewBuffer(wire)
resp, err := client.Post(CLOUDFLARE_DOH_URL,
"application/dns-udpwireformat", buff)
if err == nil {
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, newErr("HTTP error code " + resp.Status)
}
respBody, err := ioutil.ReadAll(resp.Body)
if err == nil {
return respBody, nil
} else {
// io: read error
return nil, err
}
} else {
// http error
return nil, err
}
}
type SecHandler struct {
ServiceType string
Host *dns.Msg
NameCache *cache.Cache
}
func (s SecHandler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
if len(r.Question) > 0 && r.Question[0].Qtype == dns.TypeA {
// TypeA request
if r.Question[0].Name == CLOUDFLARE_DOH_HOST {
// Cloudflare DNS over HTTPS server name
s.Host.SetReply(r)
w.WriteMsg(s.Host)
} else {
// Other TypeA request
requestedName := r.Question[0].Name
if x, found := s.NameCache.Get(requestedName); found {
// Cache hit:
cachedMsg := x.(*dns.Msg)
cachedMsg.SetReply(r)
w.WriteMsg(cachedMsg)
} else {
// Cache miss:
respMsg, err := s.QueryOverHTTPS(r)
if err == nil {
s.NameCache.SetDefault(requestedName, respMsg)
respMsg.SetReply(r)
w.WriteMsg(respMsg)
} else {
log.Printf("requested name = %s", requestedName)
WriteErrorLog(err)
dns.HandleFailed(w, r)
}
}
}
} else {
// all other request: just relay
respMsg, err := s.QueryOverHTTPS(r)
if err == nil {
respMsg.SetReply(r)
w.WriteMsg(respMsg)
} else {
dns.HandleFailed(w, r)
}
}
}
func (s SecHandler) QueryOverHTTPS(r *dns.Msg) (*dns.Msg, error) {
wire, err := r.Pack()
if err == nil {
resp, err := makeHttpsRequest(wire)
if err == nil {
// Good response then
m := new(dns.Msg)
err := m.Unpack(resp)
if err == nil {
return m, nil
}
return nil, newErr("Can't unpack message from wireformat.")
}
return nil, newErr("HTTPS Request failed.")
}
return nil, newErr("Can't pack message from wireformat.")
}
func getDohHostAddr() (*dns.Msg, error) {
m := new(dns.Msg)
m.SetQuestion(CLOUDFLARE_DOH_HOST, dns.TypeA)
client := new(dns.Client)
r, _, err := client.Exchange(m, CLOUDFLARE_DNS)
return r, err
}
type SvrStopFunc func() error
type SvrErrorHandlerFunc func(err error)
func RunDNS(port int, errHandler SvrErrorHandlerFunc) (SvrStopFunc, error) {
// get DOH host address
h, e := getDohHostAddr()
if e != nil {
WriteErrorLogMsg("Failed to obtain Cloudflare's DOH server address.", e)
// 2019.3.5. DOH 서버 주소를 가져오는데 실패하였을 경우 잠시 기다린 후
// 다시 시도한다. (5회까지)
// 부팅 후 서비스가 처음 시작될 때 "A socket operation was attempted to
// an unreachable host." 오류가 발생할 경우 서비스가 중단되는것을 방지.
for i := 1; i < 6; i++ {
// wait some seconds
time.Sleep(time.Second * 1)
log.Printf("retry %d...", i)
h, e = getDohHostAddr()
if e != nil {
WriteErrorLogMsg("Failed to obtain Cloudflare's DOH server address.", e)
} else {
break
}
}
if e != nil {
return nil, newErr("Failed to obtain Cloudflare's DOH server address. The DNS service could not be started.")
}
}
handler := SecHandler{
"UDP",
h,
cache.New(1*time.Hour, 10*time.Minute),
}
srv := new(dns.Server)
srv.Addr = ":" + strconv.Itoa(port)
srv.Net = "udp"
srv.Handler = handler
go func() {
if err := srv.ListenAndServe(); err != nil {
errHandler(err)
}
}()
return func() error {
if srv != nil {
return srv.Shutdown()
}
return newErr("No DNS server instance.")
}, nil
}