summaryrefslogtreecommitdiff
path: root/generate_dns_types.go
blob: 89ba251af0891fb8624ffdaf3b01beff7e4efe01 (plain)
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
//+build ignore

package main

import (
	"fmt"
	"go/types"
	"log"
	"os"
	"text/template"

	"golang.org/x/tools/go/packages"
)

type Field struct {
	Name string
	Type string
}

var tpl = template.Must(template.New("").Parse(`package dns

// GENERATED FILE, DO NOT MODIFY
// See generate_dns_types.go in the repo root.

import (
	"encoding/json"
	"fmt"
	"net"

	"github.com/miekg/dns"

	"code.crute.me/mcrute/go_ddns_manager/bind"
)

{{ range $name, $fields := . -}}
type {{ $name }} struct {
	Name string
	Ttl int
	{{ range $fields -}}
	{{ .Name }} {{ .Type }}
	{{ end -}}
}

func (r *{{ $name }}) ToDNS(zone *bind.Zone) dns.RR {
	return &dns.{{ $name }}{
		Hdr: makeHeader(r.Name, zone, dns.Type{{ $name }}, r.Ttl),
		{{ range $fields -}}
		{{ .Name }}: r.{{ .Name }},
		{{ end }}
	}
}

func (r *{{ $name }}) FromDNS(rr dns.RR) error {
	rt, ok := rr.(*dns.{{ $name }})
	if !ok {
		return fmt.Errorf("Invalid type %T for '{{ $name }}'", rr)
	}

	r.Name = rr.Header().Name
	r.Ttl = int(rr.Header().Ttl)
	{{ range $fields -}}
	r.{{ .Name }} = rt.{{ .Name }}
	{{ end }}

	return nil
}

func (r *{{ $name }}) MarshalJSON() ([]byte, error) {
	type Alias {{ $name }}
	return json.Marshal(&struct {
		Type string
		*Alias
	}{"{{ $name }}", (*Alias)(r)})
}

func (r *{{ $name }}) UnmarshalJSON(data []byte) error {
	type Alias {{ $name }}
	if err := json.Unmarshal(data, &struct{
		Type string
		*Alias
	}{Alias: (*Alias)(r)}); err != nil {
		return err
	}
	return nil
}

var _ RR = (*{{ $name }})(nil)

{{ end }}

func FromDNS(rr dns.RR) interface{} {
	switch v := rr.(type) {
	{{ range $name, $fields := . -}}
	case *dns.{{ $name }}:
		rv := &{{ $name }}{}
		rv.FromDNS(v)
		return rv
	{{ end }}
	}
	return nil
}
`))

var disallowedTypes = map[string]bool{
	"CDNSKEY":   true,
	"CDS":       true,
	"DLV":       true,
	"KEY":       true,
	"OPT":       true,
	"SIG":       true,
	"PrivateRR": true,
	"RFC3597":   true,
	"ANY":       true,
}

var allowedPackages = map[string]bool{
	"net": true,
}

func main() {
	conf := packages.Config{Mode: packages.NeedTypes | packages.NeedTypesInfo | packages.NeedDeps}
	pkgs, err := packages.Load(&conf, "github.com/miekg/dns")
	if err != nil {
		panic(err)
	}

	scope := pkgs[0].Types.Scope()
	localTypes := map[string][]Field{}

	for _, name := range scope.Names() {
		o := scope.Lookup(name)
		if o == nil || !o.Exported() {
			continue
		}

		// Only consider structs
		st, ok := o.Type().Underlying().(*types.Struct)
		if !ok {
			continue
		}

		name := o.Name()

		// Explicitly disallow some types that have complex embedded types
		if _, skip := disallowedTypes[name]; skip {
			continue
		}

		// There must be a type constant for this
		if scope.Lookup(fmt.Sprintf("Type%s", name)) == nil {
			continue
		}

		fields := []Field{}
		for i := 0; i < st.NumFields(); i++ {
			f := st.Field(i)

			// Exclude header field
			if f.Name() == "Hdr" {
				continue
			}

			// Fail if there are complex types embedded
			if tp, ok := f.Type().(*types.Named); ok {
				if _, ok := allowedPackages[tp.Obj().Pkg().Path()]; !ok {
					log.Fatalf("Invalid embedded complex type: %s", tp)
				}
			}

			// Also fail if there are complex types embedded in a slice
			if tp, ok := f.Type().(*types.Slice); ok {
				if ut, ok := tp.Elem().(*types.Named); ok {
					if _, ok := allowedPackages[ut.Obj().Pkg().Path()]; !ok {
						log.Fatalf("Invalid embedded complex type: %s", tp)
					}
				}
			}

			fields = append(fields, Field{f.Name(), f.Type().String()})
		}

		localTypes[name] = fields
	}

	fp, err := os.Create("zzz_types.go")
	if err != nil {
		panic(err)
	}
	defer fp.Close()
	tpl.Execute(fp, localTypes)
}