Clash.Meta/dns/server.go

127 lines
2.2 KiB
Go
Raw Normal View History

2018-12-05 21:13:29 +08:00
package dns
import (
2019-05-03 00:05:14 +08:00
"errors"
"fmt"
2018-12-05 21:13:29 +08:00
"net"
"github.com/Dreamacro/clash/log"
2019-05-03 00:05:14 +08:00
"github.com/miekg/dns"
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
r *Resolver
}
func (s *Server) ServeDNS(w D.ResponseWriter, r *D.Msg) {
2019-05-03 00:05:14 +08:00
if s.r.IsFakeIP() {
msg, err := s.handleFakeIP(r)
if err != nil {
D.HandleFailed(w, r)
return
}
msg.SetReply(r)
w.WriteMsg(msg)
return
}
2018-12-05 21:13:29 +08:00
msg, err := s.r.Exchange(r)
if err != nil {
if len(r.Question) > 0 {
q := r.Question[0]
qString := fmt.Sprintf("%s %s %s", q.Name, D.Class(q.Qclass).String(), D.Type(q.Qtype).String())
log.Debugln("[DNS Server] Exchange %s failed: %v", qString, err)
}
2018-12-05 21:13:29 +08:00
D.HandleFailed(w, r)
return
}
msg.SetReply(r)
w.WriteMsg(msg)
}
2019-05-03 00:05:14 +08:00
func (s *Server) handleFakeIP(r *D.Msg) (msg *D.Msg, err error) {
if len(r.Question) == 0 {
err = errors.New("should have one question at least")
return
}
q := r.Question[0]
2019-05-14 21:35:34 +08:00
cache := s.r.cache.Get("fakeip:" + q.String())
2019-05-03 00:05:14 +08:00
if cache != nil {
msg = cache.(*D.Msg).Copy()
2019-05-18 17:44:12 +08:00
setMsgTTL(msg, 1)
2019-05-03 00:05:14 +08:00
return
}
var ip net.IP
defer func() {
if msg == nil {
return
}
putMsgToCache(s.r.cache, "fakeip:"+q.String(), msg)
putMsgToCache(s.r.cache, ip.String(), msg)
2019-05-14 21:35:34 +08:00
2019-05-12 10:48:07 +08:00
setMsgTTL(msg, 1)
2019-05-03 00:05:14 +08:00
}()
rr := &D.A{}
rr.Hdr = dns.RR_Header{Name: r.Question[0].Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: dnsDefaultTTL}
ip = s.r.pool.Get()
rr.A = ip
msg = r.Copy()
msg.Answer = []D.RR{rr}
return
}
2019-03-23 19:41:41 +08:00
func (s *Server) setReslover(r *Resolver) {
s.r = r
}
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-03-23 19:41:41 +08:00
server.setReslover(resolver)
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
server = &Server{r: resolver}
server.Server = &D.Server{Addr: addr, PacketConn: p, Handler: server}
go func() {
server.ActivateAndServe()
}()
return nil
}