forked from alkasir/alkasir
/
dns.go
97 lines (83 loc) · 2.09 KB
/
dns.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package measure
import (
"net"
"strings"
"time"
"github.com/alkasir/alkasir/pkg/measure/sampletypes"
"encoding/json"
"github.com/miekg/dns"
)
type DNSQuery struct {
Hostname string `json:"hostname"` // Hostnames to test against
Resolver string `json:"resolver"` // Resolver to use, an empty string means to use the default system resolver.
Timeout time.Duration `json:"-"` // Measurement timeout, defaults to 45 seconds unless specified
}
func (d DNSQueryResult) Type() sampletypes.SampleType {
return sampletypes.DNSQuery
}
func (d DNSQueryResult) Marshal() ([]byte, error) {
return json.Marshal(d)
}
func (d DNSQueryResult) Host() string {
return d.Hostname
}
// DNSQueryResult .
type DNSQueryResult struct {
// Resolver net.IP
Addrs []string `json:"addrs"`
Error string `json:"error"`
Hostname string `json:"hostname"`
Resolver string `json:"resolver"`
}
func lookup(lookupaddr, nameserveraddr string) ([]string, error) {
// if no nameserver addr is supplied, use the built in resolver config
if nameserveraddr == "" {
return net.LookupHost(lookupaddr)
}
var results []string
if !strings.HasSuffix(lookupaddr, ".") {
lookupaddr += "."
}
m := new(dns.Msg)
m.SetQuestion(lookupaddr, dns.TypeA)
ret, err := dns.Exchange(m, nameserveraddr)
if err != nil {
return nil, err
}
for _, a := range ret.Answer {
if t, ok := a.(*dns.A); ok {
results = append(results, t.A.String())
}
}
return results, nil
}
func (d DNSQuery) Measure() (Measurement, error) {
timeout := d.Timeout
if timeout == 0 {
timeout = 45 * time.Second
}
qr := DNSQueryResult{
Hostname: d.Hostname,
Addrs: []string{},
Resolver: d.Resolver,
}
lookupresult := make(chan []string, 0)
lookuperror := make(chan error, 0)
go func(d DNSQuery) {
addrs, err := lookup(d.Hostname, d.Resolver)
if err != nil {
lookuperror <- err
return
}
lookupresult <- addrs
}(d)
select {
case lr := <-lookupresult:
qr.Addrs = lr
case err := <-lookuperror:
qr.Error = err.Error()
case <-time.After(timeout):
qr.Error = "timeout: " + timeout.String()
}
return qr, nil
}