2018-12-05 21:13:29 +08:00
|
|
|
package dns
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
|
2020-04-11 21:45:56 +08:00
|
|
|
"github.com/Dreamacro/clash/common/sockopt"
|
2020-06-15 10:34:15 +08:00
|
|
|
"github.com/Dreamacro/clash/log"
|
2020-04-11 21:45:56 +08:00
|
|
|
|
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 {
|
2019-07-15 10:18:42 +08:00
|
|
|
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()
|
2019-05-18 17:52:42 +08:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2020-04-11 21:45:56 +08:00
|
|
|
err = sockopt.UDPReuseaddr(p)
|
|
|
|
if err != nil {
|
2020-06-15 10:34:15 +08:00
|
|
|
log.Warnln("Failed to Reuse UDP Address: %s", err)
|
2020-04-11 21:45:56 +08:00
|
|
|
}
|
|
|
|
|
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
|
|
|
|
}
|