2019-07-14 11:29:58 +00:00
|
|
|
package dns
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/Dreamacro/clash/component/fakeip"
|
|
|
|
"github.com/Dreamacro/clash/log"
|
|
|
|
|
|
|
|
D "github.com/miekg/dns"
|
|
|
|
)
|
|
|
|
|
|
|
|
type handler func(w D.ResponseWriter, r *D.Msg)
|
2019-09-11 09:00:55 +00:00
|
|
|
type middleware func(next handler) handler
|
2019-07-14 11:29:58 +00:00
|
|
|
|
2019-09-11 09:00:55 +00:00
|
|
|
func withFakeIP(fakePool *fakeip.Pool) middleware {
|
|
|
|
return func(next handler) handler {
|
|
|
|
return func(w D.ResponseWriter, r *D.Msg) {
|
|
|
|
q := r.Question[0]
|
2019-09-21 02:30:43 +00:00
|
|
|
|
|
|
|
if q.Qtype == D.TypeAAAA {
|
|
|
|
D.HandleFailed(w, r)
|
|
|
|
return
|
|
|
|
} else if q.Qtype != D.TypeA {
|
2019-09-11 09:00:55 +00:00
|
|
|
next(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
host := strings.TrimRight(q.Name, ".")
|
2019-12-27 16:10:06 +00:00
|
|
|
if fakePool.LookupHost(host) {
|
|
|
|
next(w, r)
|
|
|
|
return
|
|
|
|
}
|
2019-09-11 09:00:55 +00:00
|
|
|
|
|
|
|
rr := &D.A{}
|
|
|
|
rr.Hdr = D.RR_Header{Name: q.Name, Rrtype: D.TypeA, Class: D.ClassINET, Ttl: dnsDefaultTTL}
|
|
|
|
ip := fakePool.Lookup(host)
|
|
|
|
rr.A = ip
|
|
|
|
msg := r.Copy()
|
|
|
|
msg.Answer = []D.RR{rr}
|
|
|
|
|
|
|
|
setMsgTTL(msg, 1)
|
|
|
|
msg.SetReply(r)
|
|
|
|
w.WriteMsg(msg)
|
|
|
|
return
|
|
|
|
}
|
2019-07-14 11:29:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func withResolver(resolver *Resolver) handler {
|
|
|
|
return func(w D.ResponseWriter, r *D.Msg) {
|
|
|
|
msg, err := resolver.Exchange(r)
|
|
|
|
if err != nil {
|
|
|
|
q := r.Question[0]
|
2019-09-11 09:00:55 +00:00
|
|
|
log.Debugln("[DNS Server] Exchange %s failed: %v", q.String(), err)
|
2019-07-14 11:29:58 +00:00
|
|
|
D.HandleFailed(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
msg.SetReply(r)
|
|
|
|
w.WriteMsg(msg)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-11 09:00:55 +00:00
|
|
|
func compose(middlewares []middleware, endpoint handler) handler {
|
|
|
|
length := len(middlewares)
|
|
|
|
h := endpoint
|
|
|
|
for i := length - 1; i >= 0; i-- {
|
|
|
|
middleware := middlewares[i]
|
|
|
|
h = middleware(h)
|
2019-07-14 11:29:58 +00:00
|
|
|
}
|
|
|
|
|
2019-09-11 09:00:55 +00:00
|
|
|
return h
|
2019-07-14 11:29:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func newHandler(resolver *Resolver) handler {
|
2019-09-11 09:00:55 +00:00
|
|
|
middlewares := []middleware{}
|
2019-07-14 11:29:58 +00:00
|
|
|
|
2019-09-11 09:00:55 +00:00
|
|
|
if resolver.IsFakeIP() {
|
|
|
|
middlewares = append(middlewares, withFakeIP(resolver.pool))
|
2019-07-14 11:29:58 +00:00
|
|
|
}
|
|
|
|
|
2019-09-11 09:00:55 +00:00
|
|
|
return compose(middlewares, withResolver(resolver))
|
2019-07-14 11:29:58 +00:00
|
|
|
}
|