clash/dns/server.go

78 lines
1.2 KiB
Go
Raw Normal View History

2018-12-05 21:13:29 +08:00
package dns
import (
"net"
"github.com/Dreamacro/clash/common/sockopt"
2018-12-05 21:13:29 +08:00
D "github.com/miekg/dns"
)
var (
address string
server = &Server{}
2019-05-03 00:05:14 +08:00
dnsDefaultTTL uint32 = 600
2018-12-05 21:13:29 +08:00
)
type Server struct {
*D.Server
2019-07-14 19:29:58 +08:00
handler handler
2018-12-05 21:13:29 +08:00
}
func (s *Server) ServeDNS(w D.ResponseWriter, r *D.Msg) {
2019-05-03 00:05:14 +08:00
if len(r.Question) == 0 {
2019-07-14 19:29:58 +08:00
D.HandleFailed(w, r)
2019-05-03 00:05:14 +08:00
return
}
2019-07-14 19:29:58 +08:00
s.handler(w, r)
2019-05-03 00:05:14 +08:00
}
2019-07-14 19:29:58 +08:00
func (s *Server) setHandler(handler handler) {
s.handler = handler
2019-03-23 19:41:41 +08:00
}
2018-12-05 21:13:29 +08:00
2019-03-23 19:41:41 +08:00
func ReCreateServer(addr string, resolver *Resolver) error {
if addr == address && resolver != nil {
2019-07-14 19:29:58 +08:00
handler := newHandler(resolver)
server.setHandler(handler)
2018-12-05 21:13:29 +08:00
return nil
}
2019-03-23 19:41:41 +08:00
if server.Server != nil {
server.Shutdown()
address = ""
2019-03-23 19:41:41 +08:00
}
2018-12-05 21:13:29 +08:00
_, port, err := net.SplitHostPort(addr)
if port == "0" || port == "" || err != nil {
return nil
}
udpAddr, err := net.ResolveUDPAddr("udp", addr)
if err != nil {
return err
}
p, err := net.ListenUDP("udp", udpAddr)
if err != nil {
return err
}
err = sockopt.UDPReuseaddr(p)
if err != nil {
return err
}
2018-12-05 21:13:29 +08:00
address = addr
2019-07-14 19:29:58 +08:00
handler := newHandler(resolver)
server = &Server{handler: handler}
2018-12-05 21:13:29 +08:00
server.Server = &D.Server{Addr: addr, PacketConn: p, Handler: server}
go func() {
server.ActivateAndServe()
}()
return nil
}