You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
gdns/routers.go

129 lines
2.4 KiB
Go

8 years ago
package main
import (
8 years ago
"errors"
8 years ago
"github.com/miekg/dns"
8 years ago
//"log"
8 years ago
"strings"
"time"
)
type routers struct {
8 years ago
c *cfg
tcp *dns.Client
udp *dns.Client
cache *cache
8 years ago
}
8 years ago
func (r *routers) checkBlacklist(m *dns.Msg) bool {
8 years ago
if m.Rcode != dns.RcodeSuccess {
// not success, not in blacklist
return false
}
for _, rr := range m.Answer {
var ip = ""
if t, ok := rr.(*dns.A); ok {
ip = t.A.String()
} else if t, ok := rr.(*dns.AAAA); ok {
ip = t.AAAA.String()
}
if ip != "" && r.c.blacklistIps.has(ip) {
8 years ago
//log.Printf("%s is in blacklist.\n", ip)
8 years ago
return true
}
}
return false
}
type dnsClient interface {
Exchange(*dns.Msg, string) (*dns.Msg, time.Duration, error)
}
8 years ago
func (r *routers) query(m *dns.Msg, servers []addr) (*dns.Msg, error) {
var up dnsClient
8 years ago
var lastErr error
8 years ago
// query cache
m2 := r.cache.get(m)
if m2 != nil {
8 years ago
//log.Printf("query %s, reply from cache\n", m.Question[0].Name)
8 years ago
m2.Id = m.Id
return m2, nil
}
8 years ago
for _, srv := range servers {
switch srv.network {
case "tcp":
up = r.tcp
case "udp":
up = r.udp
case "https":
up = DefaultHTTPDnsClient
8 years ago
default:
up = r.udp
}
8 years ago
//log.Printf("query %s use %s:%s\n", m.Question[0].Name, srv.network, srv.addr)
8 years ago
8 years ago
m1, _, err := up.Exchange(m, srv.addr)
8 years ago
if err == nil && !r.checkBlacklist(m) {
8 years ago
if m1.Rcode == dns.RcodeSuccess {
// store to cache
r.cache.set(m1)
}
return m1, err
8 years ago
}
8 years ago
//log.Println(err)
8 years ago
lastErr = err
}
8 years ago
if lastErr == nil {
// this happens when ip in blacklist
lastErr = errors.New("timeout")
}
8 years ago
// return last error
return nil, lastErr
}
// ServeDNS implements dns.Handler interface
8 years ago
func (r *routers) ServeDNS(w dns.ResponseWriter, m *dns.Msg) {
8 years ago
domain := m.Question[0].Name
d := strings.Trim(domain, ".")
for _, rule := range r.c.Rules {
if rule.domains.match(d) {
m1, err := r.query(m, rule.servers)
if err == nil {
w.WriteMsg(m1)
return
}
8 years ago
8 years ago
//log.Println(err)
8 years ago
8 years ago
}
}
// no match or failed, fallback to default
m1, err := r.query(m, r.c.servers)
if err != nil {
8 years ago
//log.Println(err)
8 years ago
dns.HandleFailed(w, m)
} else {
w.WriteMsg(m1)
}
}
func initRouters(c *cfg) {
router := &routers{
c,
&dns.Client{Net: "tcp", Timeout: time.Duration(c.Timeout) * time.Second},
&dns.Client{Net: "udp", Timeout: time.Duration(c.Timeout) * time.Second},
newCache(1000, int64(c.TTL)), // cache 5 hours
8 years ago
}
dns.Handle(".", router)
}