-
Notifications
You must be signed in to change notification settings - Fork 164
/
dns.go
247 lines (217 loc) · 6.32 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
// Copyright (c) 2018 Zededa, Inc.
// SPDX-License-Identifier: Apache-2.0
package devicenetwork
import (
"fmt"
"math"
"net"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/lf-edge/eve/pkg/pillar/types"
"github.com/miekg/dns"
)
const (
// DhcpcdResolvConfDir : directory where dhcpcd stores resolv.conf
// files separately for every interface (named <interface>.dhcp).
DhcpcdResolvConfDir = "/run/dhcpcd/resolv.conf"
// WwanResolvConfDir : directory where wwan microservice stores resolv.conf
// files separately for every interface (named <interface>.dhcp).
WwanResolvConfDir = "/run/wwan/resolv.conf"
)
// ResolveConfDirs : directories where resolv.conf for an interface could be found.
var ResolveConfDirs = []string{DhcpcdResolvConfDir, WwanResolvConfDir}
const (
// DNSMaxParallelRequests is the maximum amount of parallel DNS requests
DNSMaxParallelRequests = 5
maxTTLSec int = 3600
dnsTimeout = 30 * time.Second
)
// DNSResponse represents a response from a DNS server (A Record)
type DNSResponse struct {
IP net.IP
TTL uint32
}
// IfnameToResolvConf : Look for a file created by dhcpcd
func IfnameToResolvConf(ifname string) string {
for _, d := range ResolveConfDirs {
filename := fmt.Sprintf("%s/%s.dhcp", d, ifname)
_, err := os.Stat(filename)
if err == nil {
return filename
}
}
return ""
}
// ResolvConfToIfname : Returns the name of the interface for which
// the given resolv.conf file was created.
func ResolvConfToIfname(resolvConf string) string {
ext := filepath.Ext(resolvConf)
if ext != ".dhcp" {
return ""
}
for _, d := range ResolveConfDirs {
if strings.HasPrefix(resolvConf, d) {
return strings.TrimSuffix(filepath.Base(resolvConf), ext)
}
}
return ""
}
// ResolveWithSrcIP resolves a domain with a given dns server and source Ip
func ResolveWithSrcIP(domain string, dnsServerIP net.IP, srcIP net.IP) ([]DNSResponse, error) {
var response []DNSResponse
sourceUDPAddr := net.UDPAddr{IP: srcIP}
dialer := net.Dialer{LocalAddr: &sourceUDPAddr}
dnsClient := dns.Client{Dialer: &dialer}
msg := dns.Msg{}
if domain[len(domain)-1] != '.' {
domain = domain + "."
}
msg.SetQuestion(domain, dns.TypeA)
dnsClient.Timeout = time.Duration(dnsTimeout)
reply, _, err := dnsClient.Exchange(&msg, net.JoinHostPort(dnsServerIP.String(), "53"))
if err != nil {
return response, fmt.Errorf("dns exchange failed: %v", err)
}
for _, answer := range reply.Answer {
if aRecord, ok := answer.(*dns.A); ok {
response = append(response, DNSResponse{
IP: aRecord.A,
TTL: aRecord.Header().Ttl,
})
}
}
return response, nil
}
type cachedDNSResponses struct {
dnsResponses []DNSResponse
validUntil time.Time
}
type cachedDNSResponseKey struct {
domain string
srcIP string
}
var resolveCache = map[cachedDNSResponseKey]cachedDNSResponses{}
// ResolveCacheWrap wraps around a resolve func (e.g. ResolveWithSrcIP) and caches DNS entries
func ResolveCacheWrap(resolve func(string, net.IP, net.IP) ([]DNSResponse, error)) func(domain string, dnsServerIP net.IP, srcIP net.IP) ([]DNSResponse, error) {
return func(domain string, dnsServerIP net.IP, srcIP net.IP) ([]DNSResponse, error) {
cacheKey := cachedDNSResponseKey{
domain: domain,
srcIP: srcIP.String(),
}
dnsResponses, found := resolveCache[cacheKey]
if !found || !dnsResponses.validUntil.After(time.Now()) {
dnsResponses, err := resolve(domain, dnsServerIP, srcIP)
if err == nil {
minValidUntil := uint32(math.MaxUint32)
for _, dnsResponse := range dnsResponses {
if dnsResponse.TTL < uint32(minValidUntil) {
minValidUntil = dnsResponse.TTL
}
}
validUntil := time.Now().Add(time.Duration(minValidUntil * uint32(time.Second)))
resolveCache[cacheKey] = cachedDNSResponses{
dnsResponses: dnsResponses,
validUntil: validUntil,
}
}
return dnsResponses, err
}
return dnsResponses.dnsResponses, nil
}
}
// ResolveWithPortsLambda resolves a domain by using source IPs and dns servers from DeviceNetworkStatus
// As a resolver func ResolveWithSrcIP can be used
func ResolveWithPortsLambda(domain string,
dns types.DeviceNetworkStatus,
resolve func(string, net.IP, net.IP) ([]DNSResponse, error)) ([]DNSResponse, []error) {
quit := make(chan struct{})
work := make(chan struct{}, DNSMaxParallelRequests)
defer close(work)
resolvedIPsChan := make(chan []DNSResponse, 1)
defer close(resolvedIPsChan)
countDNSRequests := 0
var errs []error
var errsMutex sync.Mutex
var wg sync.WaitGroup
for _, port := range dns.Ports {
if !port.IsL3Port || port.Cost > 0 {
continue
}
var srcIPs []net.IP
for _, addrInfo := range port.AddrInfoList {
if addrInfo.Addr.IsGlobalUnicast() {
srcIPs = append(srcIPs, addrInfo.Addr)
}
}
for _, dnsIP := range port.DNSServers {
for _, srcIP := range srcIPs {
wg.Add(1)
dnsIPCopy := make(net.IP, len(dnsIP))
copy(dnsIPCopy, dnsIP)
srcIPCopy := make(net.IP, len(srcIP))
copy(srcIPCopy, srcIP)
countDNSRequests++
go func(dnsIP, srcIP net.IP) {
defer func() {
wg.Done()
<-work
}()
// if writable, means less than dnsMaxParallelRequests goroutines are currently running
work <- struct{}{}
select {
case <-quit:
// will return in case the quit chan has been closed,
// meaning another dns server already resolved the IP
return
default:
// do not wait for receiving a quit
}
response, err := resolve(domain, dnsIP, srcIP)
if err != nil {
errsMutex.Lock()
defer errsMutex.Unlock()
errs = append(errs, err)
}
if response != nil && len(response) > 0 {
select {
case resolvedIPsChan <- response:
default:
}
}
}(dnsIPCopy, srcIPCopy)
}
}
}
wgChan := make(chan struct{})
go func() {
wg.Wait()
close(wgChan)
}()
defer func() {
close(quit)
<-wgChan
}()
select {
case <-wgChan:
var responses []DNSResponse
if countDNSRequests == 0 {
// fallback in case no resolver is configured
ips, err := net.LookupIP(domain)
if err != nil {
return nil, append(errs, fmt.Errorf("fallback resolver failed: %+v", err))
}
for _, ip := range ips {
responses = append(responses, DNSResponse{
IP: ip,
TTL: uint32(maxTTLSec),
})
}
}
return responses, errs
case ip := <-resolvedIPsChan:
return ip, nil
}
}