-
Notifications
You must be signed in to change notification settings - Fork 23
/
server.go
107 lines (85 loc) · 1.8 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
package dnsheaven
import (
"sync"
"github.com/miekg/dns"
"github.com/sirupsen/logrus"
)
type Server struct {
config *Config
tcp *dns.Server
udp *dns.Server
}
func NewServer(config *Config, resolver Resolver) *Server {
resolve := func(net string) dns.HandlerFunc {
return func(r dns.ResponseWriter, msg *dns.Msg) {
result, err := resolver.Resolve(net, msg)
if err != nil {
logrus.WithError(err).WithField("req", msg).Error("error resolving request")
r.WriteMsg(&dns.Msg{
MsgHdr: dns.MsgHdr{
Id: msg.Id,
Response: true,
Opcode: msg.Opcode,
Authoritative: false,
Truncated: false,
RecursionDesired: false,
RecursionAvailable: false,
Zero: false,
AuthenticatedData: false,
CheckingDisabled: false,
Rcode: dns.RcodeServerFailure,
},
})
return
}
r.WriteMsg(result)
}
}
tcp := &dns.Server{
Addr: config.Address,
Net: "tcp",
Handler: resolve("tcp"),
}
udp := &dns.Server{
Addr: config.Address,
Net: "udp",
Handler: resolve("udp"),
}
return &Server{
config: config,
tcp: tcp,
udp: udp,
}
}
func (s *Server) Start() error {
wg := &sync.WaitGroup{}
errch := make(chan error)
wg.Add(2)
go s.runServer(wg, errch, s.tcp)
go s.runServer(wg, errch, s.udp)
go func() {
wg.Wait()
close(errch)
}()
for err := range errch {
if err != nil {
return err
}
}
return nil
}
func (s *Server) Shutdown() error {
err1 := s.tcp.Shutdown()
err2 := s.udp.Shutdown()
if err1 != nil {
return err1
}
if err2 != nil {
return err2
}
return nil
}
func (s *Server) runServer(wg *sync.WaitGroup, err chan<- error, server *dns.Server) {
err <- server.ListenAndServe()
wg.Done()
}