clash/dns/server.go

107 lines
1.9 KiB
Go
Raw Normal View History

2018-12-05 13:13:29 +00:00
package dns
import (
"errors"
2018-12-05 13:13:29 +00:00
"net"
"github.com/Dreamacro/clash/common/sockopt"
"github.com/Dreamacro/clash/context"
"github.com/Dreamacro/clash/log"
2018-12-05 13:13:29 +00:00
D "github.com/miekg/dns"
)
var (
address string
server = &Server{}
2019-05-02 16:05:14 +00:00
dnsDefaultTTL uint32 = 600
2018-12-05 13:13:29 +00:00
)
type Server struct {
*D.Server
2019-07-14 11:29:58 +00:00
handler handler
2018-12-05 13:13:29 +00:00
}
// ServeDNS implement D.Handler ServeDNS
2018-12-05 13:13:29 +00:00
func (s *Server) ServeDNS(w D.ResponseWriter, r *D.Msg) {
msg, err := handlerWithContext(s.handler, r)
if err != nil {
2019-07-14 11:29:58 +00:00
D.HandleFailed(w, r)
2019-05-02 16:05:14 +00:00
return
}
msg.Compress = true
w.WriteMsg(msg)
}
2019-05-02 16:05:14 +00:00
func handlerWithContext(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(msg)
return handler(ctx, msg)
2019-05-02 16:05:14 +00:00
}
2022-01-04 09:58:50 +00:00
func (s *Server) SetHandler(handler handler) {
2019-07-14 11:29:58 +00:00
s.handler = handler
2019-03-23 11:41:41 +00:00
}
2018-12-05 13:13:29 +00:00
func ReCreateServer(addr string, resolver *Resolver, mapper *ResolverEnhancer) {
if addr == address && resolver != nil {
2022-01-04 09:58:50 +00:00
handler := NewHandler(resolver, mapper)
server.SetHandler(handler)
return
2018-12-05 13:13:29 +00:00
}
2019-03-23 11:41:41 +00:00
if server.Server != nil {
server.Shutdown()
2020-06-18 10:11:02 +00:00
server = &Server{}
address = ""
2019-03-23 11:41:41 +00:00
}
2022-01-05 03:41:31 +00:00
if addr == "" {
return
}
var err error
defer func() {
if err != nil {
log.Errorln("Start DNS server error: %s", err.Error())
}
}()
2018-12-05 13:13:29 +00:00
_, port, err := net.SplitHostPort(addr)
if port == "0" || port == "" || err != nil {
return
2018-12-05 13:13:29 +00:00
}
udpAddr, err := net.ResolveUDPAddr("udp", addr)
if err != nil {
return
2018-12-05 13:13:29 +00:00
}
p, err := net.ListenUDP("udp", udpAddr)
if err != nil {
return
2018-12-05 13:13:29 +00:00
}
err = sockopt.UDPReuseaddr(p)
if err != nil {
log.Warnln("Failed to Reuse UDP Address: %s", err)
err = nil
}
2018-12-05 13:13:29 +00:00
address = addr
2022-01-04 09:58:50 +00:00
handler := NewHandler(resolver, mapper)
2019-07-14 11:29:58 +00:00
server = &Server{handler: handler}
2018-12-05 13:13:29 +00:00
server.Server = &D.Server{Addr: addr, PacketConn: p, Handler: server}
go func() {
server.ActivateAndServe()
}()
log.Infoln("DNS server listening at: %s", p.LocalAddr().String())
2018-12-05 13:13:29 +00:00
}