-
Notifications
You must be signed in to change notification settings - Fork 108
/
server.go
83 lines (69 loc) · 1.79 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
package main
import (
"time"
"github.com/miekg/dns"
)
// Server type
type Server struct {
host string
rTimeout time.Duration
wTimeout time.Duration
handler *DNSHandler
udpServer *dns.Server
tcpServer *dns.Server
}
// Run starts the server
func (s *Server) Run(config *Config,
blockCache *MemoryBlockCache,
questionCache *MemoryQuestionCache) {
s.handler = NewHandler(config, blockCache, questionCache)
tcpHandler := dns.NewServeMux()
tcpHandler.HandleFunc(".", s.handler.DoTCP)
udpHandler := dns.NewServeMux()
udpHandler.HandleFunc(".", s.handler.DoUDP)
for _, record := range NewCustomDNSRecordsFromText(config.CustomDNSRecords) {
handleFunc := record.serve(s.handler)
tcpHandler.HandleFunc(record.name, handleFunc)
udpHandler.HandleFunc(record.name, handleFunc)
}
s.tcpServer = &dns.Server{Addr: s.host,
Net: "tcp",
Handler: tcpHandler,
ReadTimeout: s.rTimeout,
WriteTimeout: s.wTimeout}
s.udpServer = &dns.Server{Addr: s.host,
Net: "udp",
Handler: udpHandler,
UDPSize: 65535,
ReadTimeout: s.rTimeout,
WriteTimeout: s.wTimeout}
go s.start(s.udpServer)
go s.start(s.tcpServer)
}
func (s *Server) start(ds *dns.Server) {
logger.Criticalf("start %s listener on %s\n", ds.Net, s.host)
if err := ds.ListenAndServe(); err != nil {
logger.Criticalf("start %s listener on %s failed: %s\n", ds.Net, s.host, err.Error())
}
}
// Stop stops the server
func (s *Server) Stop() {
if s.handler != nil {
s.handler.muActive.Lock()
s.handler.active = false
close(s.handler.requestChannel)
s.handler.muActive.Unlock()
}
if s.udpServer != nil {
err := s.udpServer.Shutdown()
if err != nil {
logger.Critical(err)
}
}
if s.tcpServer != nil {
err := s.tcpServer.Shutdown()
if err != nil {
logger.Critical(err)
}
}
}