2013-07-23 11:10:38 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"github.com/miekg/dns"
|
2013-07-23 16:37:38 +00:00
|
|
|
"strings"
|
2013-07-23 11:10:38 +00:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2013-07-23 16:37:38 +00:00
|
|
|
type ResolvError struct {
|
|
|
|
qname string
|
|
|
|
nameservers []string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e ResolvError) Error() string {
|
|
|
|
errmsg := fmt.Sprintf("%s resolv failed on %s", e.qname, strings.Join(e.nameservers, "; "))
|
|
|
|
return errmsg
|
|
|
|
}
|
|
|
|
|
2013-07-23 11:10:38 +00:00
|
|
|
type Resolver struct {
|
|
|
|
config *dns.ClientConfig
|
|
|
|
}
|
|
|
|
|
2013-07-23 16:37:38 +00:00
|
|
|
func (r *Resolver) Lookup(net string, req *dns.Msg) (message *dns.Msg, err error) {
|
2013-07-23 11:10:38 +00:00
|
|
|
c := &dns.Client{
|
|
|
|
Net: net,
|
|
|
|
ReadTimeout: r.Timeout(),
|
|
|
|
WriteTimeout: r.Timeout(),
|
|
|
|
}
|
|
|
|
|
2013-07-23 16:37:38 +00:00
|
|
|
qname := req.Question[0].Name
|
2013-07-23 11:10:38 +00:00
|
|
|
|
2013-07-23 16:37:38 +00:00
|
|
|
for _, nameserver := range r.Nameservers() {
|
|
|
|
r, rtt, err := c.Exchange(req, nameserver)
|
|
|
|
if err != nil {
|
|
|
|
Debug("%s socket error on %s", qname, nameserver)
|
|
|
|
Debug("error:%s", err.Error())
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if r != nil && r.Rcode != dns.RcodeSuccess {
|
|
|
|
Debug("%s failed to get an valid answer on %s", qname, nameserver)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
Debug("%s resolv on %s ttl: %d", qname, nameserver, rtt)
|
|
|
|
return r, nil
|
2013-07-23 11:10:38 +00:00
|
|
|
}
|
2013-07-23 16:37:38 +00:00
|
|
|
return nil, ResolvError{qname, r.Nameservers()}
|
2013-07-23 11:10:38 +00:00
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Resolver) Nameservers() (ns []string) {
|
|
|
|
for _, server := range r.config.Servers {
|
|
|
|
nameserver := server + ":" + r.config.Port
|
|
|
|
ns = append(ns, nameserver)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Resolver) Timeout() time.Duration {
|
|
|
|
return time.Duration(r.config.Timeout) * time.Second
|
|
|
|
}
|