2013-07-23 11:10:38 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2013-07-23 16:37:38 +00:00
|
|
|
"strings"
|
2013-07-23 11:10:38 +00:00
|
|
|
"time"
|
2015-02-10 09:00:59 +00:00
|
|
|
|
|
|
|
"github.com/miekg/dns"
|
2013-07-23 11:10:38 +00:00
|
|
|
)
|
|
|
|
|
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
|
|
|
|
}
|
2013-07-26 10:54:19 +00:00
|
|
|
Debug("%s resolv on %s ttl: %d", UnFqdn(qname), nameserver, rtt)
|
2013-07-23 16:37:38 +00:00
|
|
|
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
|
|
|
|
|
|
|
}
|
|
|
|
|
2015-02-11 15:57:25 +00:00
|
|
|
// Namservers return the array of nameservers, with port number appended.
|
|
|
|
// '#' in the name is treated as port separator, as with dnsmasq.
|
2013-07-23 11:10:38 +00:00
|
|
|
func (r *Resolver) Nameservers() (ns []string) {
|
|
|
|
for _, server := range r.config.Servers {
|
2015-02-11 15:57:25 +00:00
|
|
|
if i := strings.IndexByte(server, '#'); i > 0 {
|
|
|
|
server = server[:i] + ":" + server[i+1:]
|
|
|
|
} else {
|
|
|
|
server = server + ":" + r.config.Port
|
|
|
|
}
|
|
|
|
ns = append(ns, server)
|
2013-07-23 11:10:38 +00:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Resolver) Timeout() time.Duration {
|
|
|
|
return time.Duration(r.config.Timeout) * time.Second
|
|
|
|
}
|