doggo/pkg/resolvers/classic.go

78 lines
1.5 KiB
Go
Raw Normal View History

2020-12-11 12:18:54 +01:00
package resolvers
2020-12-10 10:39:05 +01:00
import (
"time"
2020-12-10 10:39:05 +01:00
"github.com/miekg/dns"
)
2020-12-16 15:10:01 +01:00
// ClassicResolver represents the config options for setting up a Resolver.
type ClassicResolver struct {
2020-12-16 14:08:34 +01:00
client *dns.Client
server string
2020-12-10 10:39:05 +01:00
}
2020-12-16 15:10:01 +01:00
// ClassicResolverOpts holds options for setting up a Classic resolver.
type ClassicResolverOpts struct {
IPv4Only bool
IPv6Only bool
Timeout time.Duration
2020-12-16 15:10:01 +01:00
UseTLS bool
UseTCP bool
2020-12-12 07:46:54 +01:00
}
2020-12-16 15:10:01 +01:00
// NewClassicResolver accepts a list of nameservers and configures a DNS resolver.
func NewClassicResolver(server string, opts ClassicResolverOpts) (Resolver, error) {
net := "udp"
client := &dns.Client{
Timeout: opts.Timeout,
2020-12-16 15:10:01 +01:00
Net: "udp",
}
if opts.UseTCP {
net = "tcp"
}
2020-12-13 08:15:45 +01:00
if opts.IPv4Only {
2020-12-16 15:10:01 +01:00
net = net + "4"
2020-12-12 07:46:54 +01:00
}
if opts.IPv6Only {
2020-12-16 15:10:01 +01:00
net = net + "6"
}
if opts.UseTLS {
net = net + "-tls"
2020-12-12 07:46:54 +01:00
}
2020-12-16 15:10:01 +01:00
client.Net = net
return &ClassicResolver{
2020-12-16 14:08:34 +01:00
client: client,
server: server,
2020-12-12 07:16:13 +01:00
}, nil
2020-12-10 10:39:05 +01:00
}
2020-12-10 17:14:04 +01:00
// Lookup prepare a list of DNS messages to be sent to the server.
// It's possible to send multiple question in one message
// but some nameservers are not able to
2020-12-16 15:10:01 +01:00
func (r *ClassicResolver) Lookup(questions []dns.Question) ([]Response, error) {
2020-12-12 11:57:13 +01:00
var (
messages = prepareMessages(questions)
responses []Response
)
2020-12-12 07:46:54 +01:00
2020-12-10 10:39:05 +01:00
for _, msg := range messages {
2020-12-16 14:08:34 +01:00
in, rtt, err := r.client.Exchange(&msg, r.server)
if err != nil {
return nil, err
}
rsp := Response{
Message: *in,
RTT: rtt,
Nameserver: r.server,
2020-12-10 10:39:05 +01:00
}
2020-12-16 14:08:34 +01:00
responses = append(responses, rsp)
2020-12-10 10:39:05 +01:00
}
2020-12-12 11:57:13 +01:00
return responses, nil
2020-12-10 10:39:05 +01:00
}