-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathserver.go
315 lines (261 loc) · 8.29 KB
/
server.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package dnscrypt
import (
"context"
"net"
"strings"
"sync"
"time"
"github.com/AdguardTeam/golibs/log"
"github.com/miekg/dns"
)
// default read timeout for all reads
const defaultReadTimeout = 2 * time.Second
// in case of TCP we only use defaultReadTimeout for the first read
// then we start using defaultTCPIdleTimeout
const defaultTCPIdleTimeout = 8 * time.Second
// defaultUDPSize is the default size of the UDP read buffer. The release notes
// for dnscrypt-proxy version 1.1.0-RC1 claim that this size was chosen as the
// maximum one "for compatibility with some scary network setups", and making it
// smaller seems to break things for some people.
//
// See also: https://github.com/AdguardTeam/AdGuardDNS/issues/188.
const defaultUDPSize = 1252
// helper struct that is used in several SetReadDeadline calls
var longTimeAgo = time.Unix(1, 0)
// ServerDNSCrypt is an interface for a DNSCrypt server
type ServerDNSCrypt interface {
// ServeTCP listens to TCP connections, queries are then processed by Server.Handler.
// It blocks the calling goroutine and to stop it you need to close the listener
// or call ServerDNSCrypt.Shutdown.
ServeTCP(l net.Listener) error
// ServeUDP listens to UDP connections, queries are then processed by Server.Handler.
// It blocks the calling goroutine and to stop it you need to close the listener
// or call ServerDNSCrypt.Shutdown.
ServeUDP(l *net.UDPConn) error
// Shutdown tries to gracefully shutdown the server. It waits until all
// connections are processed and only after that it leaves the method.
// If context deadline is specified, it will exit earlier
// or call ServerDNSCrypt.Shutdown.
Shutdown(ctx context.Context) error
}
// Server is a simple DNSCrypt server implementation
type Server struct {
// ProviderName is a DNSCrypt provider name
ProviderName string
// ResolverCert contains resolver certificate.
ResolverCert *Cert
// UDPSize is the default buffer size to use to read incoming UDP messages.
// If not set it defaults to defaultUDPSize (1252 B).
UDPSize int
// Handler to invoke. If nil, uses DefaultHandler.
Handler Handler
// make sure init is called only once
initOnce sync.Once
// Shutdown handling
// --
lock sync.RWMutex // protects access to all the fields below
started bool
wg sync.WaitGroup // active workers (servers)
tcpListeners map[net.Listener]struct{} // track active TCP listeners
udpListeners map[*net.UDPConn]struct{} // track active UDP listeners
tcpConns map[net.Conn]struct{} // track active connections
}
// type check
var _ ServerDNSCrypt = &Server{}
// prepareShutdown - prepares the server to shutdown:
// unblocks reads from all connections related to this server
// marks the server as stopped
// if the server is not started, returns ErrServerNotStarted
func (s *Server) prepareShutdown() error {
s.lock.Lock()
defer s.lock.Unlock()
if !s.started {
log.Info("Server is not started")
return ErrServerNotStarted
}
s.started = false
// These listeners were passed to us from the outside so we cannot close
// them here - this is up to the calling code to do that. Instead of that,
// we call Set(Read)Deadline to unblock goroutines that are currently
// blocked on reading from those listeners.
// For tcpConns we would like to avoid closing them to be able to process
// queries before shutting everything down.
// Unblock reads for all active tcpConns
for conn := range s.tcpConns {
_ = conn.SetReadDeadline(longTimeAgo)
}
// Unblock reads for all active TCP listeners
for l := range s.tcpListeners {
switch v := l.(type) {
case *net.TCPListener:
_ = v.SetDeadline(longTimeAgo)
}
}
// Unblock reads for all active UDP listeners
for l := range s.udpListeners {
_ = l.SetReadDeadline(longTimeAgo)
}
return nil
}
// Shutdown tries to gracefully shutdown the server. It waits until all
// connections are processed and only after that it leaves the method.
// If context deadline is specified, it will exit earlier.
func (s *Server) Shutdown(ctx context.Context) error {
log.Info("Shutting down the DNSCrypt server")
err := s.prepareShutdown()
if err != nil {
return err
}
// Using this channel to wait until all goroutines finish their work
closed := make(chan struct{})
go func() {
s.wg.Wait()
log.Info("Serve goroutines finished their work")
close(closed)
}()
// Wait for either all goroutines finish their work
// Or for the context deadline
select {
case <-closed:
log.Info("DNSCrypt server has been stopped")
case <-ctx.Done():
log.Info("DNSCrypt server shutdown has timed out")
err = ctx.Err()
}
return err
}
// init initializes (lazily) Server properties on startup
// this method is called from Server.ServeTCP and Server.ServeUDP
func (s *Server) init() {
s.tcpConns = map[net.Conn]struct{}{}
s.udpListeners = map[*net.UDPConn]struct{}{}
s.tcpListeners = map[net.Listener]struct{}{}
if s.UDPSize == 0 {
s.UDPSize = defaultUDPSize
}
}
// isStarted returns true if the server is processing queries right now
// it means that Server.ServeTCP and/or Server.ServeUDP have been called
func (s *Server) isStarted() bool {
s.lock.RLock()
started := s.started
s.lock.RUnlock()
return started
}
// serveDNS serves a DNS response
func (s *Server) serveDNS(rw ResponseWriter, r *dns.Msg) error {
if r == nil || len(r.Question) != 1 || r.Response {
return ErrInvalidQuery
}
log.Tracef("Handling a DNS query: %s", r.Question[0].Name)
handler := s.Handler
if handler == nil {
handler = DefaultHandler
}
err := handler.ServeDNS(rw, r)
if err != nil {
log.Tracef("Error while handing a DNS query: %v", err)
reply := &dns.Msg{}
reply.SetRcode(r, dns.RcodeServerFailure)
_ = rw.WriteMsg(reply)
}
return nil
}
// encrypt encrypts DNSCrypt response
func (s *Server) encrypt(m *dns.Msg, q EncryptedQuery) ([]byte, error) {
r := EncryptedResponse{
EsVersion: q.EsVersion,
Nonce: q.Nonce,
}
packet, err := m.Pack()
if err != nil {
return nil, err
}
sharedKey, err := computeSharedKey(q.EsVersion, &s.ResolverCert.ResolverSk, &q.ClientPk)
if err != nil {
return nil, err
}
return r.Encrypt(packet, sharedKey)
}
// decrypt decrypts the incoming message and returns a DNS message to process
func (s *Server) decrypt(b []byte) (*dns.Msg, EncryptedQuery, error) {
q := EncryptedQuery{
EsVersion: s.ResolverCert.EsVersion,
ClientMagic: s.ResolverCert.ClientMagic,
}
msg, err := q.Decrypt(b, s.ResolverCert.ResolverSk)
if err != nil {
// Failed to decrypt, dropping it
return nil, q, err
}
r := new(dns.Msg)
err = r.Unpack(msg)
if err != nil {
// Invalid DNS message, ignore
return nil, q, err
}
return r, q, nil
}
// handleHandshake handles a TXT request that requests certificate data
func (s *Server) handleHandshake(b []byte, certTxt string) ([]byte, error) {
m := new(dns.Msg)
err := m.Unpack(b)
if err != nil {
// Not a handshake, just ignore it
return nil, err
}
if len(m.Question) != 1 || m.Response {
// Invalid query
return nil, ErrInvalidQuery
}
q := m.Question[0]
providerName := dns.Fqdn(s.ProviderName)
qName := strings.ToLower(q.Name) // important, may be random case
if q.Qtype != dns.TypeTXT || qName != providerName {
// Invalid provider name or type, doing nothing
return nil, ErrInvalidQuery
}
reply := new(dns.Msg)
reply.SetReply(m)
txt := &dns.TXT{
Hdr: dns.RR_Header{
Name: q.Name,
Rrtype: dns.TypeTXT,
Ttl: 60, // use 60 seconds by default, but it shouldn't matter
Class: dns.ClassINET,
},
Txt: []string{
certTxt,
},
}
reply.Answer = append(reply.Answer, txt)
// These bits are important for the old dnscrypt-proxy versions
reply.Authoritative = true
reply.RecursionAvailable = true
return reply.Pack()
}
// validate checks if the Server config is properly set
func (s *Server) validate() bool {
if s.ResolverCert == nil {
log.Error("ResolverCert must be set")
return false
}
if !s.ResolverCert.VerifyDate() {
log.Error("ResolverCert date is not valid")
return false
}
if s.ProviderName == "" {
log.Error("ProviderName must be set")
return false
}
return true
}
// getCertTXT serializes the cert TXT record that are to be sent to the client
func (s *Server) getCertTXT() (string, error) {
certBuf, err := s.ResolverCert.Serialize()
if err != nil {
return "", err
}
certTxt := packTxtString(certBuf)
return certTxt, nil
}