mihomo/dns/server.go

71 lines
1.1 KiB
Go
Raw Normal View History

2018-12-05 21:13:29 +08:00
package dns
import (
"net"
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 {
2018-12-05 21:13:29 +08:00
if addr == address {
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
}
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
}