-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
server.go
112 lines (89 loc) · 2.09 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
package dns
import (
stdContext "context"
"errors"
"net"
"github.com/metacubex/mihomo/common/sockopt"
"github.com/metacubex/mihomo/constant/features"
"github.com/metacubex/mihomo/context"
"github.com/metacubex/mihomo/log"
D "github.com/miekg/dns"
)
var (
address string
server = &Server{}
dnsDefaultTTL uint32 = 600
)
type Server struct {
*D.Server
handler handler
}
// ServeDNS implement D.Handler ServeDNS
func (s *Server) ServeDNS(w D.ResponseWriter, r *D.Msg) {
msg, err := handlerWithContext(stdContext.Background(), s.handler, r)
if err != nil {
D.HandleFailed(w, r)
return
}
msg.Compress = true
w.WriteMsg(msg)
}
func handlerWithContext(stdCtx stdContext.Context, handler handler, msg *D.Msg) (*D.Msg, error) {
if len(msg.Question) == 0 {
return nil, errors.New("at least one question is required")
}
ctx := context.NewDNSContext(stdCtx, msg)
return handler(ctx, msg)
}
func (s *Server) SetHandler(handler handler) {
s.handler = handler
}
func ReCreateServer(addr string, resolver *Resolver, mapper *ResolverEnhancer) {
if features.CMFA {
UpdateIsolateHandler(resolver, mapper)
}
if addr == address && resolver != nil {
handler := NewHandler(resolver, mapper)
server.SetHandler(handler)
return
}
if server.Server != nil {
server.Shutdown()
server = &Server{}
address = ""
}
if addr == "" {
return
}
var err error
defer func() {
if err != nil {
log.Errorln("Start DNS server error: %s", err.Error())
}
}()
_, port, err := net.SplitHostPort(addr)
if port == "0" || port == "" || err != nil {
return
}
udpAddr, err := net.ResolveUDPAddr("udp", addr)
if err != nil {
return
}
p, err := net.ListenUDP("udp", udpAddr)
if err != nil {
return
}
err = sockopt.UDPReuseaddr(p)
if err != nil {
log.Warnln("Failed to Reuse UDP Address: %s", err)
err = nil
}
address = addr
handler := NewHandler(resolver, mapper)
server = &Server{handler: handler}
server.Server = &D.Server{Addr: addr, PacketConn: p, Handler: server}
go func() {
server.ActivateAndServe()
}()
log.Infoln("DNS server listening at: %s", p.LocalAddr().String())
}