-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdnsd.go
568 lines (502 loc) · 13 KB
/
dnsd.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
package dnsd
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"strings"
"time"
"github.com/rs/zerolog/log"
)
const (
// DefaultEndpoint where the CloudFlare API can be reached.
DefaultEndpoint = "https://api.cloudflare.com/client/v4"
// DefaultTTL for all DNS record updates.
DefaultTTL = 3600 * time.Second
// DefaultResolution is to check for update.
DefaultResolution = 10 * time.Minute
// DefaultLogLevel for the package. Use SetLogLevel to change.
DefaultLogLevel = LogDebug
)
// Syncer of a single DNS domain's A and AAAA records.
type Syncer struct {
Zone string // Zone. eg example.com (required)
Record string // Record to update. eg www.example.com (required)
Token string // Token for accessing the remote API (required)
Endpoint string // API endpoint (defaults to DefaultEndpoint)
TTL time.Duration // TTL to set for DNS records on update (defaults to DefaultTTL)
Resolution time.Duration // How often to check for changes (defaults to DefaultResolution)
UpdateCh chan error // Channel to notify of each update with any errors (optional)
Reporter Reporter // Optionally override the reporter which fetches IPs.
NoProxy bool // Disable CloudFlare proxy (exposes source IP)
// Cache
lastipv4 string
lastipv6 string
zoneID string
}
// Start the syncer.
func (s *Syncer) Start(ctx context.Context) error {
log.Debug().Str("record", s.Record).Msg("starting")
// Preconditions
if s.Token == "" {
return errors.New("dnsd syncer requires a token")
}
if s.Record == "" {
return errors.New("dnsd syncer requires a record name to sync")
}
// Defaults
if s.TTL == time.Duration(0) {
s.TTL = DefaultTTL
}
if s.Reporter == nil {
s.Reporter = defaultReporter
}
if s.Endpoint == "" {
s.Endpoint = DefaultEndpoint
}
if s.Resolution == time.Duration(0) {
s.Resolution = DefaultResolution
}
// In a separate goroutine, syncrhonize at the given resolution, notifying
// the update channel with either a nil or any errors encountered during
// the sync. Run forever unless the context is canceled, in which case
// the message sent to the update channel is the context error or nil.
// If no update channel is defined, simply print any errors to log.
go func() {
for {
// Sync, notifying when complete, with the error (if any)
s.onUpdate(s.sync())
// Wait for either a context cancellation or for the resolution
// timeout. Context cancellation reports on the update channel
// (with nil or error). The resolution ticker releases the loop
// to the next iteration.
select {
case <-ctx.Done():
log.Info().Str("record", s.Record).Msg("syncer canceled")
s.onUpdate(ctx.Err())
case <-time.After(s.Resolution):
// continue
}
}
}()
return nil
}
func (s *Syncer) sync() (err error) {
// Get the current IP addresses
ipv4, ipv6, err := s.Reporter()
if err != nil {
return
}
log.Debug().Str("record", s.Record).Str("ipv4", ipv4).Str("ipv6", ipv6).Msg("fetched")
// Return if they have not changed.
if ipv4 == s.lastipv4 && ipv6 == s.lastipv6 {
log.Debug().Str("record", s.Record).Msg("current")
return nil
}
// log we're commencing update
log.Debug().
Str("record", s.Record).
Str("zone", s.Zone).
Str("ipv4", ipv4).
Str("ipv6", ipv6).
Int("ttl", int(s.TTL.Seconds())).
Msg("syncing")
// Update the ipv4 address
if err = s.put("A", ipv4); err != nil {
return
}
// Update the ipv6 address if found
if ipv6 != "" {
if err = s.put("AAAA", ipv6); err != nil {
return
}
}
s.lastipv4 = ipv4
s.lastipv6 = ipv6
log.Info().
Str("record", s.Record).
Str("zone", s.Zone).
Str("ipv4", ipv4).
Str("ipv6", ipv6).
Int("ttl", int(s.TTL.Seconds())).
Msg("synced")
return
}
// put a record (A|AAAA) with value (IPv4 or IPv6 address, respectively)
func (s *Syncer) put(key, value string) (err error) {
// API Endpoint
zoneID, err := s.ZoneID()
if err != nil {
return
}
recordIDA, err := s.RecordID("A")
if err != nil {
return
}
log.Debug().
Str("id-a", recordIDA).
Str("zone", zoneID).
Msg("ids retreived")
endpoint := s.Endpoint + "/zones/" + zoneID + "/dns_records/" + recordIDA
// Request Object
request := updateRequest{
Type: key,
Content: value,
Name: s.Record,
Proxied: (!s.NoProxy),
TTL: int(s.TTL.Seconds()),
}
// PUT
log.Debug().
Str("record", s.Record).
Str("type", request.Type).
Str("content", request.Content).
Str("name", request.Name).
Bool("proxied", request.Proxied).
Int("TTL", request.TTL).
Msg("updating")
var body bytes.Buffer
if err = json.NewEncoder(&body).Encode(request); err != nil {
return
}
req, err := http.NewRequest("PUT", endpoint, &body)
if err != nil {
return
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+s.Token)
res, err := http.DefaultClient.Do(req)
if err != nil {
return
}
defer res.Body.Close()
r := response{}
if err = json.NewDecoder(res.Body).Decode(&r); err != nil {
return
}
if !r.Success {
return ErrRemote{Endpoint: endpoint, Errors: r.Errors}
}
// TODO: parse the rsponse for 200 OK (request) but errors?
return
}
func (s *Syncer) zones() []string {
url := s.Endpoint + "/zones"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return []string{}
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+s.Token)
res, err := http.DefaultClient.Do(req)
if err != nil {
return []string{}
}
r := struct {
Result []struct {
Name string `json:"name"`
} `json:"result"`
}{}
if err = json.NewDecoder(res.Body).Decode(&r); err != nil {
return []string{}
}
names := []string{}
for _, result := range r.Result {
names = append(names, result.Name)
}
return names
}
func (s *Syncer) records() []string {
zoneID, err := s.ZoneID()
if err != nil {
return []string{}
}
url := s.Endpoint + "/zones/" + zoneID + "/dns_records"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return []string{}
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+s.Token)
res, err := http.DefaultClient.Do(req)
if err != nil {
return []string{}
}
r := struct {
Result []struct {
Name string `json:"name"`
} `json:"result"`
}{}
if err = json.NewDecoder(res.Body).Decode(&r); err != nil {
return []string{}
}
names := []string{}
for _, result := range r.Result {
names = append(names, result.Name)
}
return names
}
// ZoneID returns the ID for the current Syncer's named Zone
func (s *Syncer) ZoneID() (id string, err error) {
if s.zoneID != "" {
return s.zoneID, nil // Cache
}
// Build the lookup request
endpoint := s.Endpoint + "/zones/?name=" + s.Zone
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+s.Token)
// Issue the Lookup Request
res, err := http.DefaultClient.Do(req)
if err != nil {
return
}
defer res.Body.Close()
r := zoneResponse{}
if err = json.NewDecoder(res.Body).Decode(&r); err != nil {
return
}
if !r.Success {
return "", ErrRemote{Endpoint: endpoint, Errors: r.Errors}
}
// Evaluate the Response
if len(r.Result) == 0 {
return "", ErrZoneNotFound{
Zone: s.Zone,
Zones: s.zones(),
}
} else if len(r.Result) > 1 {
return "", fmt.Errorf("zone ID lookup returned %v results (expected 1)",
len(r.Result))
}
s.zoneID = r.Result[0].ID
return s.zoneID, nil
}
// RecordID returns the ID for the current Syncer's named Record of type
// (A or AAAA)
func (s *Syncer) RecordID(typ string) (id string, err error) {
// Build the lookup request
zoneID, err := s.ZoneID()
if err != nil {
return
}
url := s.Endpoint + "/zones/" + zoneID + "/dns_records/?name=" + s.Record
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+s.Token)
// Issue the Lookup Request
res, err := http.DefaultClient.Do(req)
if err != nil {
return
}
defer res.Body.Close()
r := recordResponse{}
if err = json.NewDecoder(res.Body).Decode(&r); err != nil {
return
}
if !r.Success {
return "", ErrRemote{Errors: r.Errors}
}
// Evaluate the Response
if len(r.Result) == 0 {
return "", ErrRecordNotFound{
Zone: s.Zone,
Record: s.Record,
Records: s.records(),
}
}
for _, v := range r.Result {
if v.Type == typ {
return v.ID, nil
}
}
return "", fmt.Errorf("record lookup returned %v results, but none of type %v", len(r.Result), typ)
}
func (s *Syncer) onUpdate(err error) {
// If there is an udpate channel, send nil or the error.
if s.UpdateCh != nil {
s.UpdateCh <- err
}
// Print to log
if err != nil {
log.Error().Str("record", s.Record).Err(err).Msg("sync error")
}
}
// Reporter of IP addresses
type Reporter func() (ipv4, ipv6 string, err error)
// defaultReporter uses ipify.org and ipecho.net
var defaultReporter = func() (ipv4, ipv6 string, err error) {
// TODO: contact another instance of dnsd by default, fallig
// back to ipify, ipecho, etc.
// When using the fallback, run each concurrently witha fairly short
// timeout. If both come back, compare, but if not just log a notice that
// we were unable to do a validation.
// ipify.org
// ---------
res, err := http.Get("https://api.ipify.org")
if err != nil {
return
}
defer res.Body.Close()
bb, err := io.ReadAll(res.Body)
if err != nil {
return
}
ipv4 = string(bb)
// ipecho.net
// ---------
res, err = http.Get("https://ipecho.net/plain")
if err != nil {
return
}
bb, err = io.ReadAll(res.Body)
if err != nil {
return
}
ipv4B := string(bb)
// Cross-check
// -----------
if ipv4 != ipv4B {
log.Error().Str("ipify.org", ipv4).Str("ipecho.net", ipv4B).Msg("mismatch in ipv4 reported by third-parties.")
err = fmt.Errorf("received to differing ipv4 addresses. %v and %v", ipv4, ipv4B)
return
}
// TODO: IPv6 address only works when it is the exact server on which
// the load-balancer for the cluster is running. Therefore the following
// implementation should only be actively used when running as a sampling
// service, and the actual dnsd service should be configured to reach
// out to the load-balancer, asking for its IPv6 address.
var inSamplerMode = false
if inSamplerMode {
// Get our public IPv6 from ipify.org
res, err = http.Get("https://api64.ipify.org")
if err != nil {
return
}
defer res.Body.Close()
bb, err = io.ReadAll(res.Body)
if err != nil {
return
}
ipv6 = string(bb)
// Confirm it is the current machine
var ipv6ok bool
for _, addr := range addresses() {
addr = strings.TrimSuffix(addr, "/64") // trim netmask
if ipv6 == addr {
ipv6ok = true
break
}
}
if !ipv6ok {
return "", "", fmt.Errorf("reported ipv6 address %q not present locally", ipv6)
}
}
return
}
func addresses() (ips []string) {
ips = []string{}
ifaces, err := net.Interfaces()
if err != nil {
log.Error().Err(err).Msg("unable to list available interfaces")
return
}
for _, iface := range ifaces {
addrs, err := iface.Addrs()
if err != nil {
log.Error().Err(err).Msg("unable to list addresses for interface")
return
}
for _, addr := range addrs {
log.Info().Str("addr", addr.String()).Str("name", iface.Name).Msg("interface found")
ips = append(ips, addr.String())
}
}
return
}
// Requests
// --------
type updateRequest struct {
Type string `json:"type"`
Content string `json:"content"`
Name string `json:"name"`
TTL int `json:"ttl"`
Proxied bool `json:"proxied"`
}
// Responses
// ---------
type response struct {
Success bool `json:"success"`
Errors []struct {
Message string `json:"message"`
} `json:"errors"`
}
type zoneResponse struct {
response
Result []struct {
ID string `json:"id"`
} `json:"result"`
}
type recordResponse struct {
response
Result []struct {
ID string `json:"id"`
Type string `json:"type"`
} `json:"result"`
}
// Errors
// ------
type ErrRemote struct {
Endpoint string
Errors []struct {
Message string `json:"message"`
}
}
func (e ErrRemote) Error() string {
s := strings.Builder{}
s.WriteString(fmt.Sprintf("endpoint %q returned errors:", e.Endpoint))
ee := []string{}
for _, e := range e.Errors {
ee = append(ee, e.Message)
}
s.WriteString(strings.Join(ee, ". "))
return s.String()
}
type ErrZoneNotFound struct {
Zone string
Zones []string
}
func (e ErrZoneNotFound) Error() string {
s := strings.Builder{}
s.WriteString("zone not found: ")
s.WriteString(e.Zone)
s.WriteString(". Available zones:")
for _, z := range e.Zones {
s.WriteString("\n " + z)
}
return s.String()
}
type ErrRecordNotFound struct {
Zone string
Record string
Records []string
}
func (e ErrRecordNotFound) Error() string {
s := strings.Builder{}
s.WriteString(fmt.Sprintf("record %v not found for zone %v. Available records: ",
e.Record, e.Zone))
for _, z := range e.Records {
s.WriteString("\n " + z)
}
return s.String()
}