2019-10-08 11:04:13 +03:00
|
|
|
// Package dns resolves names to dns records
|
2019-07-28 14:14:40 +03:00
|
|
|
package dns
|
|
|
|
|
|
|
|
import (
|
2019-11-12 18:46:30 +03:00
|
|
|
"context"
|
2019-07-28 14:14:40 +03:00
|
|
|
"net"
|
|
|
|
|
2019-11-12 18:46:30 +03:00
|
|
|
"github.com/miekg/dns"
|
2020-08-20 15:23:41 +03:00
|
|
|
"github.com/unistack-org/micro/v3/resolver"
|
2019-07-28 14:14:40 +03:00
|
|
|
)
|
|
|
|
|
2019-08-20 14:48:51 +03:00
|
|
|
// Resolver is a DNS network resolve
|
2019-11-12 18:46:30 +03:00
|
|
|
type Resolver struct {
|
|
|
|
// The resolver address to use
|
|
|
|
Address string
|
|
|
|
}
|
2019-07-28 14:14:40 +03:00
|
|
|
|
|
|
|
// Resolve assumes ID is a domain name e.g micro.mu
|
2019-07-28 22:00:09 +03:00
|
|
|
func (r *Resolver) Resolve(name string) ([]*resolver.Record, error) {
|
2019-10-08 11:04:13 +03:00
|
|
|
host, port, err := net.SplitHostPort(name)
|
|
|
|
if err != nil {
|
|
|
|
host = name
|
|
|
|
port = "8085"
|
|
|
|
}
|
|
|
|
|
2019-10-13 20:36:22 +03:00
|
|
|
if len(host) == 0 {
|
|
|
|
host = "localhost"
|
|
|
|
}
|
|
|
|
|
2019-11-12 18:46:30 +03:00
|
|
|
if len(r.Address) == 0 {
|
|
|
|
r.Address = "1.0.0.1:53"
|
|
|
|
}
|
|
|
|
|
2019-12-08 02:28:39 +03:00
|
|
|
//nolint:prealloc
|
|
|
|
var records []*resolver.Record
|
|
|
|
|
|
|
|
// parsed an actual ip
|
|
|
|
if v := net.ParseIP(host); v != nil {
|
|
|
|
records = append(records, &resolver.Record{
|
|
|
|
Address: net.JoinHostPort(host, port),
|
|
|
|
})
|
|
|
|
return records, nil
|
|
|
|
}
|
|
|
|
|
2020-08-29 16:53:53 +03:00
|
|
|
for _, q := range []uint16{dns.TypeA, dns.TypeAAAA} {
|
|
|
|
m := new(dns.Msg)
|
|
|
|
m.SetQuestion(dns.Fqdn(host), q)
|
|
|
|
rec, err := dns.ExchangeContext(context.Background(), m, r.Address)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2019-11-12 18:46:30 +03:00
|
|
|
}
|
|
|
|
|
2020-08-29 16:53:53 +03:00
|
|
|
var addr string
|
|
|
|
for _, answer := range rec.Answer {
|
|
|
|
h := answer.Header()
|
|
|
|
// check record type matches
|
|
|
|
switch h.Rrtype {
|
|
|
|
case dns.TypeA:
|
|
|
|
arec, _ := answer.(*dns.A)
|
|
|
|
addr = arec.A.String()
|
|
|
|
case dns.TypeAAAA:
|
|
|
|
arec, _ := answer.(*dns.AAAA)
|
|
|
|
addr = arec.AAAA.String()
|
|
|
|
default:
|
|
|
|
continue
|
|
|
|
}
|
2019-10-08 11:04:13 +03:00
|
|
|
|
2020-08-29 16:53:53 +03:00
|
|
|
// join resolved record with port
|
|
|
|
address := net.JoinHostPort(addr, port)
|
|
|
|
// append to record set
|
|
|
|
records = append(records, &resolver.Record{
|
|
|
|
Address: address,
|
|
|
|
})
|
|
|
|
}
|
2019-07-28 14:14:40 +03:00
|
|
|
}
|
2019-10-08 11:04:13 +03:00
|
|
|
|
2019-12-08 02:28:39 +03:00
|
|
|
// no records returned so just best effort it
|
|
|
|
if len(records) == 0 {
|
|
|
|
records = append(records, &resolver.Record{
|
|
|
|
Address: net.JoinHostPort(host, port),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-07-28 14:14:40 +03:00
|
|
|
return records, nil
|
|
|
|
}
|