Debian Codegraph @

cmd/atomdns/handlers/chaos/chaos.go

raw
1 package chaos
2
3 import (
4 "context"
5 "fmt"
6 "io"
7 "math/rand"
8 "os"
9 "strings"
10 "time"
11
12 "codeberg.org/miekg/dns"
13 "codeberg.org/miekg/dns/cmd/atomdns/internal/dnsctx"
14 "codeberg.org/miekg/dns/cmd/atomdns/internal/dnslog"
15 "codeberg.org/miekg/dns/dnsutil"
16 )
17
18 // Chaos allows atomdns to reply to CH TXT queries and return author or version information.
19 // If the name starts with "authors." the authors are returned if with "version." the version is returned.
20 type Chaos struct {
21 Version string
22 Authors []string
23 }
24
25 func (c *Chaos) HandlerFunc(next dns.HandlerFunc) dns.HandlerFunc {
26 return dns.HandlerFunc(func(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) {
27 if _, ok := r.Question[0].(*dns.TXT); !ok {
28 next.ServeDNS(ctx, w, r)
29 return
30 }
31
32 qname := dnsutil.Canonical(r.Question[0].Header().Name)
33 m := r.Copy()
34 dnsutil.SetReply(m, r)
35 hdr := dns.Header{Name: qname, Class: r.Question[0].Header().Class}
36
37 switch {
38 case strings.HasPrefix(qname, "authors."):
39 rnd := rand.New(rand.NewSource(time.Now().Unix()))
40 for _, i := range rnd.Perm(len(c.Authors)) {
41 m.Answer = append(m.Answer, &dns.TXT{Hdr: hdr, Txt: []string{c.Authors[i]}})
42 }
43 case strings.HasPrefix(qname, "hostname."):
44 fallthrough
45 case strings.HasPrefix(qname, "id."):
46 hostname, err := os.Hostname()
47 if err != nil {
48 hostname = "localhost"
49 }
50 m.Answer = []dns.RR{&dns.TXT{Hdr: hdr, Txt: []string{hostname}}}
51 default:
52 m.Answer = []dns.RR{&dns.TXT{Hdr: hdr, Txt: []string{c.Version}}}
53 }
54
55 m = dnsctx.Funcs(ctx, m)
56 if err := m.Pack(); err != nil {
57 dnslog.PackFail(ctx, log(), Err(err))
58 }
59 io.Copy(w, m)
60 })
61 }
62
63 func (c *Chaos) Class(r *dns.Msg) error {
64 if len(r.Question) == 0 {
65 return nil
66 }
67 if r.Question[0].Header().Class == dns.ClassINET {
68 return nil
69 }
70 if r.Question[0].Header().Class == dns.ClassCHAOS {
71 return nil
72 }
73 return fmt.Errorf("class is not IN or CH")
74 }