1package dns
2
3import (
4	"bytes"
5	"crypto/rsa"
6	"encoding/hex"
7	"fmt"
8	"math/rand"
9	"net"
10	"reflect"
11	"regexp"
12	"strconv"
13	"strings"
14	"testing"
15	"testing/quick"
16)
17
18func TestDotInName(t *testing.T) {
19	buf := make([]byte, 20)
20	PackDomainName("aa\\.bb.nl.", buf, 0, nil, false)
21	// index 3 must be a real dot
22	if buf[3] != '.' {
23		t.Error("dot should be a real dot")
24	}
25
26	if buf[6] != 2 {
27		t.Error("this must have the value 2")
28	}
29	dom, _, _ := UnpackDomainName(buf, 0)
30	// printing it should yield the backspace again
31	if dom != "aa\\.bb.nl." {
32		t.Error("dot should have been escaped: ", dom)
33	}
34}
35
36func TestDotLastInLabel(t *testing.T) {
37	sample := "aa\\..au."
38	buf := make([]byte, 20)
39	_, err := PackDomainName(sample, buf, 0, nil, false)
40	if err != nil {
41		t.Fatalf("unexpected error packing domain: %v", err)
42	}
43	dom, _, _ := UnpackDomainName(buf, 0)
44	if dom != sample {
45		t.Fatalf("unpacked domain `%s' doesn't match packed domain", dom)
46	}
47}
48
49func TestTooLongDomainName(t *testing.T) {
50	l := "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrsssttt."
51	dom := l + l + l + l + l + l + l
52	_, err := NewRR(dom + " IN A 127.0.0.1")
53	if err == nil {
54		t.Error("should be too long")
55	}
56	_, err = NewRR("..com. IN A 127.0.0.1")
57	if err == nil {
58		t.Error("should fail")
59	}
60}
61
62func TestDomainName(t *testing.T) {
63	tests := []string{"r\\.gieben.miek.nl.", "www\\.www.miek.nl.",
64		"www.*.miek.nl.", "www.*.miek.nl.",
65	}
66	dbuff := make([]byte, 40)
67
68	for _, ts := range tests {
69		if _, err := PackDomainName(ts, dbuff, 0, nil, false); err != nil {
70			t.Error("not a valid domain name")
71			continue
72		}
73		n, _, err := UnpackDomainName(dbuff, 0)
74		if err != nil {
75			t.Error("failed to unpack packed domain name")
76			continue
77		}
78		if ts != n {
79			t.Errorf("must be equal: in: %s, out: %s", ts, n)
80		}
81	}
82}
83
84func TestDomainNameAndTXTEscapes(t *testing.T) {
85	tests := []byte{'.', '(', ')', ';', ' ', '@', '"', '\\', 9, 13, 10, 0, 255}
86	for _, b := range tests {
87		rrbytes := []byte{
88			1, b, 0, // owner
89			byte(TypeTXT >> 8), byte(TypeTXT),
90			byte(ClassINET >> 8), byte(ClassINET),
91			0, 0, 0, 1, // TTL
92			0, 2, 1, b, // Data
93		}
94		rr1, _, err := UnpackRR(rrbytes, 0)
95		if err != nil {
96			panic(err)
97		}
98		s := rr1.String()
99		rr2, err := NewRR(s)
100		if err != nil {
101			t.Errorf("error parsing unpacked RR's string: %v", err)
102		}
103		repacked := make([]byte, len(rrbytes))
104		if _, err := PackRR(rr2, repacked, 0, nil, false); err != nil {
105			t.Errorf("error packing parsed RR: %v", err)
106		}
107		if !bytes.Equal(repacked, rrbytes) {
108			t.Error("packed bytes don't match original bytes")
109		}
110	}
111}
112
113func TestTXTEscapeParsing(t *testing.T) {
114	test := [][]string{
115		{`";"`, `";"`},
116		{`\;`, `";"`},
117		{`"\t"`, `"t"`},
118		{`"\r"`, `"r"`},
119		{`"\ "`, `" "`},
120		{`"\;"`, `";"`},
121		{`"\;\""`, `";\""`},
122		{`"\(a\)"`, `"(a)"`},
123		{`"\(a)"`, `"(a)"`},
124		{`"(a\)"`, `"(a)"`},
125		{`"(a)"`, `"(a)"`},
126		{`"\048"`, `"0"`},
127		{`"\` + "\t" + `"`, `"\009"`},
128		{`"\` + "\n" + `"`, `"\010"`},
129		{`"\` + "\r" + `"`, `"\013"`},
130		{`"\` + "\x11" + `"`, `"\017"`},
131		{`"\'"`, `"'"`},
132	}
133	for _, s := range test {
134		rr, err := NewRR(fmt.Sprintf("example.com. IN TXT %v", s[0]))
135		if err != nil {
136			t.Errorf("could not parse %v TXT: %s", s[0], err)
137			continue
138		}
139
140		txt := sprintTxt(rr.(*TXT).Txt)
141		if txt != s[1] {
142			t.Errorf("mismatch after parsing `%v` TXT record: `%v` != `%v`", s[0], txt, s[1])
143		}
144	}
145}
146
147func GenerateDomain(r *rand.Rand, size int) []byte {
148	dnLen := size % 70 // artificially limit size so there's less to interpret if a failure occurs
149	var dn []byte
150	done := false
151	for i := 0; i < dnLen && !done; {
152		max := dnLen - i
153		if max > 63 {
154			max = 63
155		}
156		lLen := max
157		if lLen != 0 {
158			lLen = int(r.Int31()) % max
159		}
160		done = lLen == 0
161		if done {
162			continue
163		}
164		l := make([]byte, lLen+1)
165		l[0] = byte(lLen)
166		for j := 0; j < lLen; j++ {
167			l[j+1] = byte(rand.Int31())
168		}
169		dn = append(dn, l...)
170		i += 1 + lLen
171	}
172	return append(dn, 0)
173}
174
175func TestDomainQuick(t *testing.T) {
176	r := rand.New(rand.NewSource(0))
177	f := func(l int) bool {
178		db := GenerateDomain(r, l)
179		ds, _, err := UnpackDomainName(db, 0)
180		if err != nil {
181			panic(err)
182		}
183		buf := make([]byte, 255)
184		off, err := PackDomainName(ds, buf, 0, nil, false)
185		if err != nil {
186			t.Errorf("error packing domain: %v", err)
187			t.Errorf(" bytes: %v", db)
188			t.Errorf("string: %v", ds)
189			return false
190		}
191		if !bytes.Equal(db, buf[:off]) {
192			t.Errorf("repacked domain doesn't match original:")
193			t.Errorf("src bytes: %v", db)
194			t.Errorf("   string: %v", ds)
195			t.Errorf("out bytes: %v", buf[:off])
196			return false
197		}
198		return true
199	}
200	if err := quick.Check(f, nil); err != nil {
201		t.Error(err)
202	}
203}
204
205func GenerateTXT(r *rand.Rand, size int) []byte {
206	rdLen := size % 300 // artificially limit size so there's less to interpret if a failure occurs
207	var rd []byte
208	for i := 0; i < rdLen; {
209		max := rdLen - 1
210		if max > 255 {
211			max = 255
212		}
213		sLen := max
214		if max != 0 {
215			sLen = int(r.Int31()) % max
216		}
217		s := make([]byte, sLen+1)
218		s[0] = byte(sLen)
219		for j := 0; j < sLen; j++ {
220			s[j+1] = byte(rand.Int31())
221		}
222		rd = append(rd, s...)
223		i += 1 + sLen
224	}
225	return rd
226}
227
228// Ok, 2 things. 1) this test breaks with the new functionality of splitting up larger txt
229// chunks into 255 byte pieces. 2) I don't like the random nature of this thing, because I can't
230// place the quotes where they need to be.
231// So either add some code the places the quotes in just the right spots, make this non random
232// or do something else.
233// Disabled for now. (miek)
234func testTXTRRQuick(t *testing.T) {
235	s := rand.NewSource(0)
236	r := rand.New(s)
237	typeAndClass := []byte{
238		byte(TypeTXT >> 8), byte(TypeTXT),
239		byte(ClassINET >> 8), byte(ClassINET),
240		0, 0, 0, 1, // TTL
241	}
242	f := func(l int) bool {
243		owner := GenerateDomain(r, l)
244		rdata := GenerateTXT(r, l)
245		rrbytes := make([]byte, 0, len(owner)+2+2+4+2+len(rdata))
246		rrbytes = append(rrbytes, owner...)
247		rrbytes = append(rrbytes, typeAndClass...)
248		rrbytes = append(rrbytes, byte(len(rdata)>>8))
249		rrbytes = append(rrbytes, byte(len(rdata)))
250		rrbytes = append(rrbytes, rdata...)
251		rr, _, err := UnpackRR(rrbytes, 0)
252		if err != nil {
253			panic(err)
254		}
255		buf := make([]byte, len(rrbytes)*3)
256		off, err := PackRR(rr, buf, 0, nil, false)
257		if err != nil {
258			t.Errorf("pack Error: %v\nRR: %v", err, rr)
259			return false
260		}
261		buf = buf[:off]
262		if !bytes.Equal(buf, rrbytes) {
263			t.Errorf("packed bytes don't match original bytes")
264			t.Errorf("src bytes: %v", rrbytes)
265			t.Errorf("   struct: %v", rr)
266			t.Errorf("out bytes: %v", buf)
267			return false
268		}
269		if len(rdata) == 0 {
270			// string'ing won't produce any data to parse
271			return true
272		}
273		rrString := rr.String()
274		rr2, err := NewRR(rrString)
275		if err != nil {
276			t.Errorf("error parsing own output: %v", err)
277			t.Errorf("struct: %v", rr)
278			t.Errorf("string: %v", rrString)
279			return false
280		}
281		if rr2.String() != rrString {
282			t.Errorf("parsed rr.String() doesn't match original string")
283			t.Errorf("original: %v", rrString)
284			t.Errorf("  parsed: %v", rr2.String())
285			return false
286		}
287
288		buf = make([]byte, len(rrbytes)*3)
289		off, err = PackRR(rr2, buf, 0, nil, false)
290		if err != nil {
291			t.Errorf("error packing parsed rr: %v", err)
292			t.Errorf("unpacked Struct: %v", rr)
293			t.Errorf("         string: %v", rrString)
294			t.Errorf("  parsed Struct: %v", rr2)
295			return false
296		}
297		buf = buf[:off]
298		if !bytes.Equal(buf, rrbytes) {
299			t.Errorf("parsed packed bytes don't match original bytes")
300			t.Errorf("   source bytes: %v", rrbytes)
301			t.Errorf("unpacked struct: %v", rr)
302			t.Errorf("         string: %v", rrString)
303			t.Errorf("  parsed struct: %v", rr2)
304			t.Errorf(" repacked bytes: %v", buf)
305			return false
306		}
307		return true
308	}
309	c := &quick.Config{MaxCountScale: 10}
310	if err := quick.Check(f, c); err != nil {
311		t.Error(err)
312	}
313}
314
315func TestParseDirectiveMisc(t *testing.T) {
316	tests := map[string]string{
317		"$ORIGIN miek.nl.\na IN NS b": "a.miek.nl.\t3600\tIN\tNS\tb.miek.nl.",
318		"$TTL 2H\nmiek.nl. IN NS b.":  "miek.nl.\t7200\tIN\tNS\tb.",
319		"miek.nl. 1D IN NS b.":        "miek.nl.\t86400\tIN\tNS\tb.",
320		`name. IN SOA  a6.nstld.com. hostmaster.nic.name. (
321        203362132 ; serial
322        5m        ; refresh (5 minutes)
323        5m        ; retry (5 minutes)
324        2w        ; expire (2 weeks)
325        300       ; minimum (5 minutes)
326)`: "name.\t3600\tIN\tSOA\ta6.nstld.com. hostmaster.nic.name. 203362132 300 300 1209600 300",
327		". 3600000  IN  NS ONE.MY-ROOTS.NET.":        ".\t3600000\tIN\tNS\tONE.MY-ROOTS.NET.",
328		"ONE.MY-ROOTS.NET. 3600000 IN A 192.168.1.1": "ONE.MY-ROOTS.NET.\t3600000\tIN\tA\t192.168.1.1",
329	}
330	for i, o := range tests {
331		rr, err := NewRR(i)
332		if err != nil {
333			t.Error("failed to parse RR: ", err)
334			continue
335		}
336		if rr.String() != o {
337			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", i, o, rr.String())
338		}
339	}
340}
341
342func TestNSEC(t *testing.T) {
343	nsectests := map[string]string{
344		"nl. IN NSEC3PARAM 1 0 5 30923C44C6CBBB8F": "nl.\t3600\tIN\tNSEC3PARAM\t1 0 5 30923C44C6CBBB8F",
345		"p2209hipbpnm681knjnu0m1febshlv4e.nl. IN NSEC3 1 1 5 30923C44C6CBBB8F P90DG1KE8QEAN0B01613LHQDG0SOJ0TA NS SOA TXT RRSIG DNSKEY NSEC3PARAM": "p2209hipbpnm681knjnu0m1febshlv4e.nl.\t3600\tIN\tNSEC3\t1 1 5 30923C44C6CBBB8F P90DG1KE8QEAN0B01613LHQDG0SOJ0TA NS SOA TXT RRSIG DNSKEY NSEC3PARAM",
346		"localhost.dnssex.nl. IN NSEC www.dnssex.nl. A RRSIG NSEC":                                                                                 "localhost.dnssex.nl.\t3600\tIN\tNSEC\twww.dnssex.nl. A RRSIG NSEC",
347		"localhost.dnssex.nl. IN NSEC www.dnssex.nl. A RRSIG NSEC TYPE65534":                                                                       "localhost.dnssex.nl.\t3600\tIN\tNSEC\twww.dnssex.nl. A RRSIG NSEC TYPE65534",
348		"localhost.dnssex.nl. IN NSEC www.dnssex.nl. A RRSIG NSec Type65534":                                                                       "localhost.dnssex.nl.\t3600\tIN\tNSEC\twww.dnssex.nl. A RRSIG NSEC TYPE65534",
349		"44ohaq2njb0idnvolt9ggthvsk1e1uv8.skydns.test. NSEC3 1 0 0 - 44OHAQ2NJB0IDNVOLT9GGTHVSK1E1UVA":                                             "44ohaq2njb0idnvolt9ggthvsk1e1uv8.skydns.test.\t3600\tIN\tNSEC3\t1 0 0 - 44OHAQ2NJB0IDNVOLT9GGTHVSK1E1UVA",
350	}
351	for i, o := range nsectests {
352		rr, err := NewRR(i)
353		if err != nil {
354			t.Error("failed to parse RR: ", err)
355			continue
356		}
357		if rr.String() != o {
358			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", i, o, rr.String())
359		}
360	}
361}
362
363func TestParseLOC(t *testing.T) {
364	lt := map[string]string{
365		"SW1A2AA.find.me.uk.	LOC	51 30 12.748 N 00 07 39.611 W 0.00m 0.00m 0.00m 0.00m": "SW1A2AA.find.me.uk.\t3600\tIN\tLOC\t51 30 12.748 N 00 07 39.611 W 0m 0.00m 0.00m 0.00m",
366		"SW1A2AA.find.me.uk.	LOC	51 0 0.0 N 00 07 39.611 W 0.00m 0.00m 0.00m 0.00m": "SW1A2AA.find.me.uk.\t3600\tIN\tLOC\t51 00 0.000 N 00 07 39.611 W 0m 0.00m 0.00m 0.00m",
367	}
368	for i, o := range lt {
369		rr, err := NewRR(i)
370		if err != nil {
371			t.Error("failed to parse RR: ", err)
372			continue
373		}
374		if rr.String() != o {
375			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", i, o, rr.String())
376		}
377	}
378}
379
380func TestParseDS(t *testing.T) {
381	dt := map[string]string{
382		"example.net. 3600 IN DS 40692 12 3 22261A8B0E0D799183E35E24E2AD6BB58533CBA7E3B14D659E9CA09B 2071398F": "example.net.\t3600\tIN\tDS\t40692 12 3 22261A8B0E0D799183E35E24E2AD6BB58533CBA7E3B14D659E9CA09B2071398F",
383	}
384	for i, o := range dt {
385		rr, err := NewRR(i)
386		if err != nil {
387			t.Error("failed to parse RR: ", err)
388			continue
389		}
390		if rr.String() != o {
391			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", i, o, rr.String())
392		}
393	}
394}
395
396func TestQuotes(t *testing.T) {
397	tests := map[string]string{
398		`t.example.com. IN TXT "a bc"`: "t.example.com.\t3600\tIN\tTXT\t\"a bc\"",
399		`t.example.com. IN TXT "a
400 bc"`: "t.example.com.\t3600\tIN\tTXT\t\"a\\010 bc\"",
401		`t.example.com. IN TXT ""`:              "t.example.com.\t3600\tIN\tTXT\t\"\"",
402		`t.example.com. IN TXT "a"`:             "t.example.com.\t3600\tIN\tTXT\t\"a\"",
403		`t.example.com. IN TXT "aa"`:            "t.example.com.\t3600\tIN\tTXT\t\"aa\"",
404		`t.example.com. IN TXT "aaa" ;`:         "t.example.com.\t3600\tIN\tTXT\t\"aaa\"",
405		`t.example.com. IN TXT "abc" "DEF"`:     "t.example.com.\t3600\tIN\tTXT\t\"abc\" \"DEF\"",
406		`t.example.com. IN TXT "abc" ( "DEF" )`: "t.example.com.\t3600\tIN\tTXT\t\"abc\" \"DEF\"",
407		`t.example.com. IN TXT aaa ;`:           "t.example.com.\t3600\tIN\tTXT\t\"aaa\"",
408		`t.example.com. IN TXT aaa aaa;`:        "t.example.com.\t3600\tIN\tTXT\t\"aaa\" \"aaa\"",
409		`t.example.com. IN TXT aaa aaa`:         "t.example.com.\t3600\tIN\tTXT\t\"aaa\" \"aaa\"",
410		`t.example.com. IN TXT aaa`:             "t.example.com.\t3600\tIN\tTXT\t\"aaa\"",
411		"cid.urn.arpa. NAPTR 100 50 \"s\" \"z3950+I2L+I2C\"    \"\" _z3950._tcp.gatech.edu.": "cid.urn.arpa.\t3600\tIN\tNAPTR\t100 50 \"s\" \"z3950+I2L+I2C\" \"\" _z3950._tcp.gatech.edu.",
412		"cid.urn.arpa. NAPTR 100 50 \"s\" \"rcds+I2C\"         \"\" _rcds._udp.gatech.edu.":  "cid.urn.arpa.\t3600\tIN\tNAPTR\t100 50 \"s\" \"rcds+I2C\" \"\" _rcds._udp.gatech.edu.",
413		"cid.urn.arpa. NAPTR 100 50 \"s\" \"http+I2L+I2C+I2R\" \"\" _http._tcp.gatech.edu.":  "cid.urn.arpa.\t3600\tIN\tNAPTR\t100 50 \"s\" \"http+I2L+I2C+I2R\" \"\" _http._tcp.gatech.edu.",
414		"cid.urn.arpa. NAPTR 100 10 \"\" \"\" \"/urn:cid:.+@([^\\.]+\\.)(.*)$/\\2/i\" .":     "cid.urn.arpa.\t3600\tIN\tNAPTR\t100 10 \"\" \"\" \"/urn:cid:.+@([^\\.]+\\.)(.*)$/\\2/i\" .",
415	}
416	for i, o := range tests {
417		rr, err := NewRR(i)
418		if err != nil {
419			t.Error("failed to parse RR: ", err)
420			continue
421		}
422		if rr.String() != o {
423			t.Errorf("`%s' should be equal to\n`%s', but is\n`%s'", i, o, rr.String())
424		}
425	}
426}
427
428func TestParseClass(t *testing.T) {
429	tests := map[string]string{
430		"t.example.com. IN A 127.0.0.1": "t.example.com.	3600	IN	A	127.0.0.1",
431		"t.example.com. CS A 127.0.0.1": "t.example.com.	3600	CS	A	127.0.0.1",
432		"t.example.com. CH A 127.0.0.1": "t.example.com.	3600	CH	A	127.0.0.1",
433		// ClassANY can not occur in zone files
434		// "t.example.com. ANY A 127.0.0.1": "t.example.com.	3600	ANY	A	127.0.0.1",
435		"t.example.com. NONE A 127.0.0.1": "t.example.com.	3600	NONE	A	127.0.0.1",
436		"t.example.com. CLASS255 A 127.0.0.1": "t.example.com.	3600	CLASS255	A	127.0.0.1",
437	}
438	for i, o := range tests {
439		rr, err := NewRR(i)
440		if err != nil {
441			t.Error("failed to parse RR: ", err)
442			continue
443		}
444		if rr.String() != o {
445			t.Errorf("`%s' should be equal to\n`%s', but is\n`%s'", i, o, rr.String())
446		}
447	}
448}
449
450func TestBrace(t *testing.T) {
451	tests := map[string]string{
452		"(miek.nl.) 3600 IN A 127.0.1.1":                 "miek.nl.\t3600\tIN\tA\t127.0.1.1",
453		"miek.nl. (3600) IN MX (10) elektron.atoom.net.": "miek.nl.\t3600\tIN\tMX\t10 elektron.atoom.net.",
454		`miek.nl. IN (
455                        3600 A 127.0.0.1)`: "miek.nl.\t3600\tIN\tA\t127.0.0.1",
456		"(miek.nl.) (A) (127.0.2.1)":                          "miek.nl.\t3600\tIN\tA\t127.0.2.1",
457		"miek.nl A 127.0.3.1":                                 "miek.nl.\t3600\tIN\tA\t127.0.3.1",
458		"_ssh._tcp.local. 60 IN (PTR) stora._ssh._tcp.local.": "_ssh._tcp.local.\t60\tIN\tPTR\tstora._ssh._tcp.local.",
459		"miek.nl. NS ns.miek.nl":                              "miek.nl.\t3600\tIN\tNS\tns.miek.nl.",
460		`(miek.nl.) (
461                        (IN)
462                        (AAAA)
463                        (::1) )`: "miek.nl.\t3600\tIN\tAAAA\t::1",
464		`(miek.nl.) (
465                        (IN)
466                        (AAAA)
467                        (::1))`: "miek.nl.\t3600\tIN\tAAAA\t::1",
468		"miek.nl. IN AAAA ::2": "miek.nl.\t3600\tIN\tAAAA\t::2",
469		`((m)(i)ek.(n)l.) (SOA) (soa.) (soa.) (
470                                2009032802 ; serial
471                                21600      ; refresh (6 hours)
472                                7(2)00       ; retry (2 hours)
473                                604()800     ; expire (1 week)
474                                3600       ; minimum (1 hour)
475                        )`: "miek.nl.\t3600\tIN\tSOA\tsoa. soa. 2009032802 21600 7200 604800 3600",
476		"miek\\.nl. IN A 127.0.0.10": "miek\\.nl.\t3600\tIN\tA\t127.0.0.10",
477		"miek.nl. IN A 127.0.0.11":   "miek.nl.\t3600\tIN\tA\t127.0.0.11",
478		"miek.nl. A 127.0.0.12":      "miek.nl.\t3600\tIN\tA\t127.0.0.12",
479		`miek.nl.       86400 IN SOA elektron.atoom.net. miekg.atoom.net. (
480                                2009032802 ; serial
481                                21600      ; refresh (6 hours)
482                                7200       ; retry (2 hours)
483                                604800     ; expire (1 week)
484                                3600       ; minimum (1 hour)
485                        )`: "miek.nl.\t86400\tIN\tSOA\telektron.atoom.net. miekg.atoom.net. 2009032802 21600 7200 604800 3600",
486	}
487	for i, o := range tests {
488		rr, err := NewRR(i)
489		if err != nil {
490			t.Errorf("failed to parse RR: %v\n\t%s", err, i)
491			continue
492		}
493		if rr.String() != o {
494			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", i, o, rr.String())
495		}
496	}
497}
498
499func TestParseFailure(t *testing.T) {
500	tests := []string{"miek.nl. IN A 327.0.0.1",
501		"miek.nl. IN AAAA ::x",
502		"miek.nl. IN MX a0 miek.nl.",
503		"miek.nl aap IN MX mx.miek.nl.",
504		"miek.nl 200 IN mxx 10 mx.miek.nl.",
505		"miek.nl. inn MX 10 mx.miek.nl.",
506		// "miek.nl. IN CNAME ", // actually valid nowadays, zero size rdata
507		"miek.nl. IN CNAME ..",
508		"miek.nl. PA MX 10 miek.nl.",
509		"miek.nl. ) IN MX 10 miek.nl.",
510	}
511
512	for _, s := range tests {
513		_, err := NewRR(s)
514		if err == nil {
515			t.Errorf("should have triggered an error: \"%s\"", s)
516		}
517	}
518}
519
520func TestOmittedTTL(t *testing.T) {
521	zone := `
522$ORIGIN example.com.
523example.com. 42 IN SOA ns1.example.com. hostmaster.example.com. 1 86400 60 86400 3600 ; TTL=42 SOA
524example.com.        NS 2 ; TTL=42 absolute owner name
525@                   MD 3 ; TTL=42 current-origin owner name
526                    MF 4 ; TTL=42 leading-space implied owner name
527	43 TYPE65280 \# 1 05 ; TTL=43 implied owner name explicit TTL
528	          MB 6       ; TTL=43 leading-tab implied owner name
529$TTL 1337
530example.com. 88 MG 7 ; TTL=88 explicit TTL
531example.com.    MR 8 ; TTL=1337 after first $TTL
532$TTL 314
533             1 TXT 9 ; TTL=1 implied owner name explicit TTL
534example.com.   DNAME 10 ; TTL=314 after second $TTL
535`
536	reCaseFromComment := regexp.MustCompile(`TTL=(\d+)\s+(.*)`)
537	records := ParseZone(strings.NewReader(zone), "", "")
538	var i int
539	for record := range records {
540		i++
541		if record.Error != nil {
542			t.Error(record.Error)
543			continue
544		}
545		expected := reCaseFromComment.FindStringSubmatch(record.Comment)
546		if len(expected) != 3 {
547			t.Errorf("regexp didn't match for record %d", i)
548			continue
549		}
550		expectedTTL, _ := strconv.ParseUint(expected[1], 10, 32)
551		ttl := record.RR.Header().Ttl
552		if ttl != uint32(expectedTTL) {
553			t.Errorf("%s: expected TTL %d, got %d", expected[2], expectedTTL, ttl)
554		}
555	}
556	if i != 10 {
557		t.Errorf("expected %d records, got %d", 5, i)
558	}
559}
560
561func TestRelativeNameErrors(t *testing.T) {
562	var badZones = []struct {
563		label        string
564		zoneContents string
565		expectedErr  string
566	}{
567		{
568			"relative owner name without origin",
569			"example.com 3600 IN SOA ns.example.com. hostmaster.example.com. 1 86400 60 86400 3600",
570			"bad owner name",
571		},
572		{
573			"relative owner name in RDATA",
574			"example.com. 3600 IN SOA ns hostmaster 1 86400 60 86400 3600",
575			"bad SOA Ns",
576		},
577		{
578			"origin reference without origin",
579			"@ 3600 IN SOA ns.example.com. hostmaster.example.com. 1 86400 60 86400 3600",
580			"bad owner name",
581		},
582		{
583			"relative owner name in $INCLUDE",
584			"$INCLUDE file.db example.com",
585			"bad origin name",
586		},
587		{
588			"relative owner name in $ORIGIN",
589			"$ORIGIN example.com",
590			"bad origin name",
591		},
592	}
593	for _, errorCase := range badZones {
594		entries := ParseZone(strings.NewReader(errorCase.zoneContents), "", "")
595		for entry := range entries {
596			if entry.Error == nil {
597				t.Errorf("%s: expected error, got nil", errorCase.label)
598				continue
599			}
600			err := entry.Error.err
601			if err != errorCase.expectedErr {
602				t.Errorf("%s: expected error `%s`, got `%s`", errorCase.label, errorCase.expectedErr, err)
603			}
604		}
605	}
606}
607
608func TestHIP(t *testing.T) {
609	h := `www.example.com.      IN  HIP ( 2 200100107B1A74DF365639CC39F1D578
610                                AwEAAbdxyhNuSutc5EMzxTs9LBPCIkOFH8cIvM4p
6119+LrV4e19WzK00+CI6zBCQTdtWsuxKbWIy87UOoJTwkUs7lBu+Upr1gsNrut79ryra+bSRGQ
612b1slImA8YVJyuIDsj7kwzG7jnERNqnWxZ48AWkskmdHaVDP4BcelrTI3rMXdXF5D
613                                rvs1.example.com.
614                                rvs2.example.com. )`
615	rr, err := NewRR(h)
616	if err != nil {
617		t.Fatalf("failed to parse RR: %v", err)
618	}
619	msg := new(Msg)
620	msg.Answer = []RR{rr, rr}
621	bytes, err := msg.Pack()
622	if err != nil {
623		t.Fatalf("failed to pack msg: %v", err)
624	}
625	if err := msg.Unpack(bytes); err != nil {
626		t.Fatalf("failed to unpack msg: %v", err)
627	}
628	if len(msg.Answer) != 2 {
629		t.Fatalf("2 answers expected: %v", msg)
630	}
631	for i, rr := range msg.Answer {
632		rr := rr.(*HIP)
633		if l := len(rr.RendezvousServers); l != 2 {
634			t.Fatalf("2 servers expected, only %d in record %d:\n%v", l, i, msg)
635		}
636		for j, s := range []string{"rvs1.example.com.", "rvs2.example.com."} {
637			if rr.RendezvousServers[j] != s {
638				t.Fatalf("expected server %d of record %d to be %s:\n%v", j, i, s, msg)
639			}
640		}
641	}
642}
643
644// Test with no known RR on the line
645func TestLineNumberError2(t *testing.T) {
646	tests := map[string]string{
647		"example.com. 1000 SO master.example.com. admin.example.com. 1 4294967294 4294967293 4294967295 100": "dns: expecting RR type or class, not this...: \"SO\" at line: 1:21",
648		"example.com 1000 IN TALINK a.example.com. b..example.com.":                                          "dns: bad TALINK NextName: \"b..example.com.\" at line: 1:57",
649		"example.com 1000 IN TALINK ( a.example.com. b..example.com. )":                                      "dns: bad TALINK NextName: \"b..example.com.\" at line: 1:60",
650		`example.com 1000 IN TALINK ( a.example.com.
651	bb..example.com. )`: "dns: bad TALINK NextName: \"bb..example.com.\" at line: 2:18",
652		// This is a bug, it should report an error on line 1, but the new is already processed.
653		`example.com 1000 IN TALINK ( a.example.com.  b...example.com.
654	)`: "dns: bad TALINK NextName: \"b...example.com.\" at line: 2:1"}
655
656	for in, errStr := range tests {
657		_, err := NewRR(in)
658		if err == nil {
659			t.Error("err is nil")
660		} else {
661			if err.Error() != errStr {
662				t.Errorf("%s: error should be %s is %v", in, errStr, err)
663			}
664		}
665	}
666}
667
668// Test if the calculations are correct
669func TestRfc1982(t *testing.T) {
670	// If the current time and the timestamp are more than 68 years apart
671	// it means the date has wrapped. 0 is 1970
672
673	// fall in the current 68 year span
674	strtests := []string{"20120525134203", "19700101000000", "20380119031408"}
675	for _, v := range strtests {
676		if x, _ := StringToTime(v); v != TimeToString(x) {
677			t.Errorf("1982 arithmetic string failure %s (%s:%d)", v, TimeToString(x), x)
678		}
679	}
680
681	inttests := map[uint32]string{0: "19700101000000",
682		1 << 31:   "20380119031408",
683		1<<32 - 1: "21060207062815",
684	}
685	for i, v := range inttests {
686		if TimeToString(i) != v {
687			t.Errorf("1982 arithmetic int failure %d:%s (%s)", i, v, TimeToString(i))
688		}
689	}
690
691	// Future tests, these dates get parsed to a date within the current 136 year span
692	future := map[string]string{"22680119031408": "20631123173144",
693		"19010101121212": "20370206184028",
694		"19210101121212": "20570206184028",
695		"19500101121212": "20860206184028",
696		"19700101000000": "19700101000000",
697		"19690101000000": "21050207062816",
698		"29210101121212": "21040522212236",
699	}
700	for from, to := range future {
701		x, _ := StringToTime(from)
702		y := TimeToString(x)
703		if y != to {
704			t.Errorf("1982 arithmetic future failure %s:%s (%s)", from, to, y)
705		}
706	}
707}
708
709func TestEmpty(t *testing.T) {
710	for range ParseZone(strings.NewReader(""), "", "") {
711		t.Errorf("should be empty")
712	}
713}
714
715func TestLowercaseTokens(t *testing.T) {
716	var testrecords = []string{
717		"example.org. 300 IN a 1.2.3.4",
718		"example.org. 300 in A 1.2.3.4",
719		"example.org. 300 in a 1.2.3.4",
720		"example.org. 300 a 1.2.3.4",
721		"example.org. 300 A 1.2.3.4",
722		"example.org. IN a 1.2.3.4",
723		"example.org. in A 1.2.3.4",
724		"example.org. in a 1.2.3.4",
725		"example.org. a 1.2.3.4",
726		"example.org. A 1.2.3.4",
727		"example.org. a 1.2.3.4",
728		"$ORIGIN example.org.\n a 1.2.3.4",
729		"$Origin example.org.\n a 1.2.3.4",
730		"$origin example.org.\n a 1.2.3.4",
731		"example.org. Class1 Type1 1.2.3.4",
732	}
733	for _, testrr := range testrecords {
734		_, err := NewRR(testrr)
735		if err != nil {
736			t.Errorf("failed to parse %#v, got %v", testrr, err)
737		}
738	}
739}
740
741func TestSRVPacking(t *testing.T) {
742	msg := Msg{}
743
744	things := []string{"1.2.3.4:8484",
745		"45.45.45.45:8484",
746		"84.84.84.84:8484",
747	}
748
749	for i, n := range things {
750		h, p, err := net.SplitHostPort(n)
751		if err != nil {
752			continue
753		}
754		port, _ := strconv.ParseUint(p, 10, 16)
755
756		rr := &SRV{
757			Hdr: RR_Header{Name: "somename.",
758				Rrtype: TypeSRV,
759				Class:  ClassINET,
760				Ttl:    5},
761			Priority: uint16(i),
762			Weight:   5,
763			Port:     uint16(port),
764			Target:   h + ".",
765		}
766
767		msg.Answer = append(msg.Answer, rr)
768	}
769
770	_, err := msg.Pack()
771	if err != nil {
772		t.Fatalf("couldn't pack %v: %v", msg, err)
773	}
774}
775
776func TestParseBackslash(t *testing.T) {
777	if _, err := NewRR("nul\\000gap.test.globnix.net. 600 IN	A 192.0.2.10"); err != nil {
778		t.Errorf("could not create RR with \\000 in it")
779	}
780	if _, err := NewRR(`nul\000gap.test.globnix.net. 600 IN TXT "Hello\123"`); err != nil {
781		t.Errorf("could not create RR with \\000 in it")
782	}
783	if _, err := NewRR(`m\ @\ iek.nl. IN 3600 A 127.0.0.1`); err != nil {
784		t.Errorf("could not create RR with \\ and \\@ in it")
785	}
786}
787
788func TestILNP(t *testing.T) {
789	tests := []string{
790		"host1.example.com.\t3600\tIN\tNID\t10 0014:4fff:ff20:ee64",
791		"host1.example.com.\t3600\tIN\tNID\t20 0015:5fff:ff21:ee65",
792		"host2.example.com.\t3600\tIN\tNID\t10 0016:6fff:ff22:ee66",
793		"host1.example.com.\t3600\tIN\tL32\t10 10.1.2.0",
794		"host1.example.com.\t3600\tIN\tL32\t20 10.1.4.0",
795		"host2.example.com.\t3600\tIN\tL32\t10 10.1.8.0",
796		"host1.example.com.\t3600\tIN\tL64\t10 2001:0DB8:1140:1000",
797		"host1.example.com.\t3600\tIN\tL64\t20 2001:0DB8:2140:2000",
798		"host2.example.com.\t3600\tIN\tL64\t10 2001:0DB8:4140:4000",
799		"host1.example.com.\t3600\tIN\tLP\t10 l64-subnet1.example.com.",
800		"host1.example.com.\t3600\tIN\tLP\t10 l64-subnet2.example.com.",
801		"host1.example.com.\t3600\tIN\tLP\t20 l32-subnet1.example.com.",
802	}
803	for _, t1 := range tests {
804		r, err := NewRR(t1)
805		if err != nil {
806			t.Fatalf("an error occurred: %v", err)
807		} else {
808			if t1 != r.String() {
809				t.Fatalf("strings should be equal %s %s", t1, r.String())
810			}
811		}
812	}
813}
814
815func TestGposEidNimloc(t *testing.T) {
816	dt := map[string]string{
817		"444433332222111199990123000000ff. NSAP-PTR foo.bar.com.": "444433332222111199990123000000ff.\t3600\tIN\tNSAP-PTR\tfoo.bar.com.",
818		"lillee. IN  GPOS -32.6882 116.8652 10.0":                 "lillee.\t3600\tIN\tGPOS\t-32.6882 116.8652 10.0",
819		"hinault. IN GPOS -22.6882 116.8652 250.0":                "hinault.\t3600\tIN\tGPOS\t-22.6882 116.8652 250.0",
820		"VENERA.   IN NIMLOC  75234159EAC457800920":               "VENERA.\t3600\tIN\tNIMLOC\t75234159EAC457800920",
821		"VAXA.     IN EID     3141592653589793":                   "VAXA.\t3600\tIN\tEID\t3141592653589793",
822	}
823	for i, o := range dt {
824		rr, err := NewRR(i)
825		if err != nil {
826			t.Error("failed to parse RR: ", err)
827			continue
828		}
829		if rr.String() != o {
830			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", i, o, rr.String())
831		}
832	}
833}
834
835func TestPX(t *testing.T) {
836	dt := map[string]string{
837		"*.net2.it. IN PX 10 net2.it. PRMD-net2.ADMD-p400.C-it.":      "*.net2.it.\t3600\tIN\tPX\t10 net2.it. PRMD-net2.ADMD-p400.C-it.",
838		"ab.net2.it. IN PX 10 ab.net2.it. O-ab.PRMD-net2.ADMDb.C-it.": "ab.net2.it.\t3600\tIN\tPX\t10 ab.net2.it. O-ab.PRMD-net2.ADMDb.C-it.",
839	}
840	for i, o := range dt {
841		rr, err := NewRR(i)
842		if err != nil {
843			t.Error("failed to parse RR: ", err)
844			continue
845		}
846		if rr.String() != o {
847			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", i, o, rr.String())
848		}
849	}
850}
851
852func TestComment(t *testing.T) {
853	// Comments we must see
854	comments := map[string]bool{
855		"; this is comment 1": true,
856		"; this is comment 2": true,
857		"; this is comment 4": true,
858		"; this is comment 6": true,
859		"; this is comment 7": true,
860		"; this is comment 8": true,
861	}
862	zone := `
863foo. IN A 10.0.0.1 ; this is comment 1
864foo. IN A (
865	10.0.0.2 ; this is comment 2
866)
867; this is comment 3
868foo. IN A 10.0.0.3
869foo. IN A ( 10.0.0.4 ); this is comment 4
870
871foo. IN A 10.0.0.5
872; this is comment 5
873
874foo. IN A 10.0.0.6
875
876foo. IN DNSKEY 256 3 5 AwEAAb+8l ; this is comment 6
877foo. IN NSEC miek.nl. TXT RRSIG NSEC; this is comment 7
878foo. IN TXT "THIS IS TEXT MAN"; this is comment 8
879`
880	for x := range ParseZone(strings.NewReader(zone), ".", "") {
881		if x.Error == nil {
882			if x.Comment != "" {
883				if _, ok := comments[x.Comment]; !ok {
884					t.Errorf("wrong comment %q", x.Comment)
885				}
886			}
887		}
888	}
889}
890
891func TestParseZoneComments(t *testing.T) {
892	for i, test := range []struct {
893		zone     string
894		comments []string
895	}{
896		{
897			`name. IN SOA  a6.nstld.com. hostmaster.nic.name. (
898			203362132 ; serial
899			5m        ; refresh (5 minutes)
900			5m        ; retry (5 minutes)
901			2w        ; expire (2 weeks)
902			300       ; minimum (5 minutes)
903		) ; y
904. 3600000  IN  NS ONE.MY-ROOTS.NET. ; x`,
905			[]string{"; serial ; refresh (5 minutes) ; retry (5 minutes) ; expire (2 weeks) ; minimum (5 minutes) ; y", "; x"},
906		},
907		{
908			`name. IN SOA  a6.nstld.com. hostmaster.nic.name. (
909			203362132 ; serial
910			5m        ; refresh (5 minutes)
911			5m        ; retry (5 minutes)
912			2w        ; expire (2 weeks)
913			300       ; minimum (5 minutes)
914		) ; y
915. 3600000  IN  NS ONE.MY-ROOTS.NET.`,
916			[]string{"; serial ; refresh (5 minutes) ; retry (5 minutes) ; expire (2 weeks) ; minimum (5 minutes) ; y", ""},
917		},
918		{
919			`name. IN SOA  a6.nstld.com. hostmaster.nic.name. (
920			203362132 ; serial
921			5m        ; refresh (5 minutes)
922			5m        ; retry (5 minutes)
923			2w        ; expire (2 weeks)
924			300       ; minimum (5 minutes)
925		)
926. 3600000  IN  NS ONE.MY-ROOTS.NET.`,
927			[]string{"; serial ; refresh (5 minutes) ; retry (5 minutes) ; expire (2 weeks) ; minimum (5 minutes)", ""},
928		},
929		{
930			`name. IN SOA  a6.nstld.com. hostmaster.nic.name. (
931			203362132 ; serial
932			5m        ; refresh (5 minutes)
933			5m        ; retry (5 minutes)
934			2w        ; expire (2 weeks)
935			300       ; minimum (5 minutes)
936		)
937. 3600000  IN  NS ONE.MY-ROOTS.NET. ; x`,
938			[]string{"; serial ; refresh (5 minutes) ; retry (5 minutes) ; expire (2 weeks) ; minimum (5 minutes)", "; x"},
939		},
940		{
941			`name. IN SOA  a6.nstld.com. hostmaster.nic.name. (
942			203362132 ; serial
943			5m        ; refresh (5 minutes)
944			5m        ; retry (5 minutes)
945			2w        ; expire (2 weeks)
946			300       ; minimum (5 minutes)
947		)`,
948			[]string{"; serial ; refresh (5 minutes) ; retry (5 minutes) ; expire (2 weeks) ; minimum (5 minutes)"},
949		},
950		{
951			`. 3600000  IN  NS ONE.MY-ROOTS.NET. ; x`,
952			[]string{"; x"},
953		},
954		{
955			`. 3600000  IN  NS ONE.MY-ROOTS.NET.`,
956			[]string{""},
957		},
958		{
959			`. 3600000  IN  NS ONE.MY-ROOTS.NET. ;;x`,
960			[]string{";;x"},
961		},
962	} {
963		r := strings.NewReader(test.zone)
964
965		var j int
966		for r := range ParseZone(r, "", "") {
967			if r.Error != nil {
968				t.Fatal(r.Error)
969			}
970
971			if j >= len(test.comments) {
972				t.Fatalf("too many records for zone %d at %d record, expected %d", i, j+1, len(test.comments))
973			}
974
975			if r.Comment != test.comments[j] {
976				t.Errorf("invalid comment for record %d:%d %v / %v", i, j, r.RR, r.Error)
977				t.Logf("expected %q", test.comments[j])
978				t.Logf("got      %q", r.Comment)
979			}
980
981			j++
982		}
983
984		if j != len(test.comments) {
985			t.Errorf("too few records for zone %d, got %d, expected %d", i, j, len(test.comments))
986		}
987	}
988}
989
990func TestEUIxx(t *testing.T) {
991	tests := map[string]string{
992		"host.example. IN EUI48 00-00-5e-90-01-2a":       "host.example.\t3600\tIN\tEUI48\t00-00-5e-90-01-2a",
993		"host.example. IN EUI64 00-00-5e-ef-00-00-00-2a": "host.example.\t3600\tIN\tEUI64\t00-00-5e-ef-00-00-00-2a",
994	}
995	for i, o := range tests {
996		r, err := NewRR(i)
997		if err != nil {
998			t.Errorf("failed to parse %s: %v", i, err)
999		}
1000		if r.String() != o {
1001			t.Errorf("want %s, got %s", o, r.String())
1002		}
1003	}
1004}
1005
1006func TestUserRR(t *testing.T) {
1007	tests := map[string]string{
1008		"host.example. IN UID 1234":              "host.example.\t3600\tIN\tUID\t1234",
1009		"host.example. IN GID 1234556":           "host.example.\t3600\tIN\tGID\t1234556",
1010		"host.example. IN UINFO \"Miek Gieben\"": "host.example.\t3600\tIN\tUINFO\t\"Miek Gieben\"",
1011	}
1012	for i, o := range tests {
1013		r, err := NewRR(i)
1014		if err != nil {
1015			t.Errorf("failed to parse %s: %v", i, err)
1016		}
1017		if r.String() != o {
1018			t.Errorf("want %s, got %s", o, r.String())
1019		}
1020	}
1021}
1022
1023func TestTXT(t *testing.T) {
1024	// Test single entry TXT record
1025	rr, err := NewRR(`_raop._tcp.local. 60 IN TXT "single value"`)
1026	if err != nil {
1027		t.Error("failed to parse single value TXT record", err)
1028	} else if rr, ok := rr.(*TXT); !ok {
1029		t.Error("wrong type, record should be of type TXT")
1030	} else {
1031		if len(rr.Txt) != 1 {
1032			t.Error("bad size of TXT value:", len(rr.Txt))
1033		} else if rr.Txt[0] != "single value" {
1034			t.Error("bad single value")
1035		}
1036		if rr.String() != `_raop._tcp.local.	60	IN	TXT	"single value"` {
1037			t.Error("bad representation of TXT record:", rr.String())
1038		}
1039		if Len(rr) != 28+1+12 {
1040			t.Error("bad size of serialized record:", Len(rr))
1041		}
1042	}
1043
1044	// Test multi entries TXT record
1045	rr, err = NewRR(`_raop._tcp.local. 60 IN TXT "a=1" "b=2" "c=3" "d=4"`)
1046	if err != nil {
1047		t.Error("failed to parse multi-values TXT record", err)
1048	} else if rr, ok := rr.(*TXT); !ok {
1049		t.Error("wrong type, record should be of type TXT")
1050	} else {
1051		if len(rr.Txt) != 4 {
1052			t.Error("bad size of TXT multi-value:", len(rr.Txt))
1053		} else if rr.Txt[0] != "a=1" || rr.Txt[1] != "b=2" || rr.Txt[2] != "c=3" || rr.Txt[3] != "d=4" {
1054			t.Error("bad values in TXT records")
1055		}
1056		if rr.String() != `_raop._tcp.local.	60	IN	TXT	"a=1" "b=2" "c=3" "d=4"` {
1057			t.Error("bad representation of TXT multi value record:", rr.String())
1058		}
1059		if Len(rr) != 28+1+3+1+3+1+3+1+3 {
1060			t.Error("bad size of serialized multi value record:", Len(rr))
1061		}
1062	}
1063
1064	// Test empty-string in TXT record
1065	rr, err = NewRR(`_raop._tcp.local. 60 IN TXT ""`)
1066	if err != nil {
1067		t.Error("failed to parse empty-string TXT record", err)
1068	} else if rr, ok := rr.(*TXT); !ok {
1069		t.Error("wrong type, record should be of type TXT")
1070	} else {
1071		if len(rr.Txt) != 1 {
1072			t.Error("bad size of TXT empty-string value:", len(rr.Txt))
1073		} else if rr.Txt[0] != "" {
1074			t.Error("bad value for empty-string TXT record")
1075		}
1076		if rr.String() != `_raop._tcp.local.	60	IN	TXT	""` {
1077			t.Error("bad representation of empty-string TXT record:", rr.String())
1078		}
1079		if Len(rr) != 28+1 {
1080			t.Error("bad size of serialized record:", Len(rr))
1081		}
1082	}
1083
1084	// Test TXT record with chunk larger than 255 bytes, they should be split up, by the parser
1085	s := ""
1086	for i := 0; i < 255; i++ {
1087		s += "a"
1088	}
1089	s += "b"
1090	rr, err = NewRR(`test.local. 60 IN TXT "` + s + `"`)
1091	if err != nil {
1092		t.Error("failed to parse empty-string TXT record", err)
1093	}
1094	if rr.(*TXT).Txt[1] != "b" {
1095		t.Errorf("Txt should have two chunk, last one my be 'b', but is %s", rr.(*TXT).Txt[1])
1096	}
1097}
1098
1099func TestTypeXXXX(t *testing.T) {
1100	_, err := NewRR("example.com IN TYPE1234 \\# 4 aabbccdd")
1101	if err != nil {
1102		t.Errorf("failed to parse TYPE1234 RR: %v", err)
1103	}
1104	_, err = NewRR("example.com IN TYPE655341 \\# 8 aabbccddaabbccdd")
1105	if err == nil {
1106		t.Errorf("this should not work, for TYPE655341")
1107	}
1108	_, err = NewRR("example.com IN TYPE1 \\# 4 0a000001")
1109	if err == nil {
1110		t.Errorf("this should not work")
1111	}
1112}
1113
1114func TestPTR(t *testing.T) {
1115	_, err := NewRR("144.2.0.192.in-addr.arpa. 900 IN PTR ilouse03146p0\\(.example.com.")
1116	if err != nil {
1117		t.Error("failed to parse ", err)
1118	}
1119}
1120
1121func TestDigit(t *testing.T) {
1122	tests := map[string]byte{
1123		"miek\\000.nl. 100 IN TXT \"A\"": 0,
1124		"miek\\001.nl. 100 IN TXT \"A\"": 1,
1125		"miek\\254.nl. 100 IN TXT \"A\"": 254,
1126		"miek\\255.nl. 100 IN TXT \"A\"": 255,
1127		"miek\\256.nl. 100 IN TXT \"A\"": 0,
1128		"miek\\257.nl. 100 IN TXT \"A\"": 1,
1129		"miek\\004.nl. 100 IN TXT \"A\"": 4,
1130	}
1131	for s, i := range tests {
1132		r, err := NewRR(s)
1133		buf := make([]byte, 40)
1134		if err != nil {
1135			t.Fatalf("failed to parse %v", err)
1136		}
1137		PackRR(r, buf, 0, nil, false)
1138		if buf[5] != i {
1139			t.Fatalf("5 pos must be %d, is %d", i, buf[5])
1140		}
1141		r1, _, _ := UnpackRR(buf, 0)
1142		if r1.Header().Ttl != 100 {
1143			t.Fatalf("TTL should %d, is %d", 100, r1.Header().Ttl)
1144		}
1145	}
1146}
1147
1148func TestParseRRSIGTimestamp(t *testing.T) {
1149	tests := map[string]bool{
1150		`miek.nl.  IN RRSIG SOA 8 2 43200 20140210031301 20140111031301 12051 miek.nl. MVZUyrYwq0iZhMFDDnVXD2BvuNiUJjSYlJAgzyAE6CF875BMvvZa+Sb0 RlSCL7WODQSQHhCx/fegHhVVF+Iz8N8kOLrmXD1+jO3Bm6Prl5UhcsPx WTBsg/kmxbp8sR1kvH4oZJtVfakG3iDerrxNaf0sQwhZzyfJQAqpC7pcBoc=`: true,
1151		`miek.nl.  IN RRSIG SOA 8 2 43200 315565800 4102477800 12051 miek.nl. MVZUyrYwq0iZhMFDDnVXD2BvuNiUJjSYlJAgzyAE6CF875BMvvZa+Sb0 RlSCL7WODQSQHhCx/fegHhVVF+Iz8N8kOLrmXD1+jO3Bm6Prl5UhcsPx WTBsg/kmxbp8sR1kvH4oZJtVfakG3iDerrxNaf0sQwhZzyfJQAqpC7pcBoc=`:          true,
1152	}
1153	for r := range tests {
1154		_, err := NewRR(r)
1155		if err != nil {
1156			t.Error(err)
1157		}
1158	}
1159}
1160
1161func TestTxtEqual(t *testing.T) {
1162	rr1 := new(TXT)
1163	rr1.Hdr = RR_Header{Name: ".", Rrtype: TypeTXT, Class: ClassINET, Ttl: 0}
1164	rr1.Txt = []string{"a\"a", "\"", "b"}
1165	rr2, _ := NewRR(rr1.String())
1166	if rr1.String() != rr2.String() {
1167		// This is not an error, but keep this test.
1168		t.Errorf("these two TXT records should match:\n%s\n%s", rr1.String(), rr2.String())
1169	}
1170}
1171
1172func TestTxtLong(t *testing.T) {
1173	rr1 := new(TXT)
1174	rr1.Hdr = RR_Header{Name: ".", Rrtype: TypeTXT, Class: ClassINET, Ttl: 0}
1175	// Make a long txt record, this breaks when sending the packet,
1176	// but not earlier.
1177	rr1.Txt = []string{"start-"}
1178	for i := 0; i < 200; i++ {
1179		rr1.Txt[0] += "start-"
1180	}
1181	str := rr1.String()
1182	if len(str) < len(rr1.Txt[0]) {
1183		t.Error("string conversion should work")
1184	}
1185}
1186
1187// Basically, don't crash.
1188func TestMalformedPackets(t *testing.T) {
1189	var packets = []string{
1190		"0021641c0000000100000000000078787878787878787878787303636f6d0000100001",
1191	}
1192
1193	// com = 63 6f 6d
1194	for _, packet := range packets {
1195		data, _ := hex.DecodeString(packet)
1196		var msg Msg
1197		msg.Unpack(data)
1198	}
1199}
1200
1201type algorithm struct {
1202	name uint8
1203	bits int
1204}
1205
1206func TestNewPrivateKey(t *testing.T) {
1207	if testing.Short() {
1208		t.Skip("skipping test in short mode.")
1209	}
1210	algorithms := []algorithm{
1211		{ECDSAP256SHA256, 256},
1212		{ECDSAP384SHA384, 384},
1213		{RSASHA1, 1024},
1214		{RSASHA256, 2048},
1215		{ED25519, 256},
1216	}
1217
1218	for _, algo := range algorithms {
1219		key := new(DNSKEY)
1220		key.Hdr.Rrtype = TypeDNSKEY
1221		key.Hdr.Name = "miek.nl."
1222		key.Hdr.Class = ClassINET
1223		key.Hdr.Ttl = 14400
1224		key.Flags = 256
1225		key.Protocol = 3
1226		key.Algorithm = algo.name
1227		privkey, err := key.Generate(algo.bits)
1228		if err != nil {
1229			t.Fatal(err)
1230		}
1231
1232		newPrivKey, err := key.NewPrivateKey(key.PrivateKeyString(privkey))
1233		if err != nil {
1234			t.Error(key.String())
1235			t.Error(key.PrivateKeyString(privkey))
1236			t.Fatal(err)
1237		}
1238
1239		switch newPrivKey := newPrivKey.(type) {
1240		case *rsa.PrivateKey:
1241			newPrivKey.Precompute()
1242		}
1243
1244		if !reflect.DeepEqual(privkey, newPrivKey) {
1245			t.Errorf("[%v] Private keys differ:\n%#v\n%#v", AlgorithmToString[algo.name], privkey, newPrivKey)
1246		}
1247	}
1248}
1249
1250// special input test
1251func TestNewRRSpecial(t *testing.T) {
1252	var (
1253		rr     RR
1254		err    error
1255		expect string
1256	)
1257
1258	rr, err = NewRR("; comment")
1259	expect = ""
1260	if err != nil {
1261		t.Errorf("unexpected err: %v", err)
1262	}
1263	if rr != nil {
1264		t.Errorf("unexpected result: [%s] != [%s]", rr, expect)
1265	}
1266
1267	rr, err = NewRR("")
1268	expect = ""
1269	if err != nil {
1270		t.Errorf("unexpected err: %v", err)
1271	}
1272	if rr != nil {
1273		t.Errorf("unexpected result: [%s] != [%s]", rr, expect)
1274	}
1275
1276	rr, err = NewRR("$ORIGIN foo.")
1277	expect = ""
1278	if err != nil {
1279		t.Errorf("unexpected err: %v", err)
1280	}
1281	if rr != nil {
1282		t.Errorf("unexpected result: [%s] != [%s]", rr, expect)
1283	}
1284
1285	rr, err = NewRR(" ")
1286	expect = ""
1287	if err != nil {
1288		t.Errorf("unexpected err: %v", err)
1289	}
1290	if rr != nil {
1291		t.Errorf("unexpected result: [%s] != [%s]", rr, expect)
1292	}
1293
1294	rr, err = NewRR("\n")
1295	expect = ""
1296	if err != nil {
1297		t.Errorf("unexpected err: %v", err)
1298	}
1299	if rr != nil {
1300		t.Errorf("unexpected result: [%s] != [%s]", rr, expect)
1301	}
1302
1303	rr, err = NewRR("foo. A 1.1.1.1\nbar. A 2.2.2.2")
1304	expect = "foo.\t3600\tIN\tA\t1.1.1.1"
1305	if err != nil {
1306		t.Errorf("unexpected err: %v", err)
1307	}
1308	if rr == nil || rr.String() != expect {
1309		t.Errorf("unexpected result: [%s] != [%s]", rr, expect)
1310	}
1311}
1312
1313func TestPrintfVerbsRdata(t *testing.T) {
1314	x, _ := NewRR("www.miek.nl. IN MX 20 mx.miek.nl.")
1315	if Field(x, 1) != "20" {
1316		t.Errorf("should be 20")
1317	}
1318	if Field(x, 2) != "mx.miek.nl." {
1319		t.Errorf("should be mx.miek.nl.")
1320	}
1321
1322	x, _ = NewRR("www.miek.nl. IN A 127.0.0.1")
1323	if Field(x, 1) != "127.0.0.1" {
1324		t.Errorf("should be 127.0.0.1")
1325	}
1326
1327	x, _ = NewRR("www.miek.nl. IN AAAA ::1")
1328	if Field(x, 1) != "::1" {
1329		t.Errorf("should be ::1")
1330	}
1331
1332	x, _ = NewRR("www.miek.nl. IN NSEC a.miek.nl. A NS SOA MX AAAA")
1333	if Field(x, 1) != "a.miek.nl." {
1334		t.Errorf("should be a.miek.nl.")
1335	}
1336	if Field(x, 2) != "A NS SOA MX AAAA" {
1337		t.Errorf("should be A NS SOA MX AAAA")
1338	}
1339
1340	x, _ = NewRR("www.miek.nl. IN TXT \"first\" \"second\"")
1341	if Field(x, 1) != "first second" {
1342		t.Errorf("should be first second")
1343	}
1344	if Field(x, 0) != "" {
1345		t.Errorf("should be empty")
1346	}
1347}
1348
1349func TestParseTokenOverflow(t *testing.T) {
1350	_, err := NewRR("_443._tcp.example.org. IN TLSA 0 0 0 308205e8308204d0a00302010202100411de8f53b462f6a5a861b712ec6b59300d06092a864886f70d01010b05003070310b300906035504061302555331153013060355040a130c446967694365727420496e6331193017060355040b13107777772e64696769636572742e636f6d312f302d06035504031326446967694365727420534841322048696768204173737572616e636520536572766572204341301e170d3134313130363030303030305a170d3135313131333132303030305a3081a5310b3009060355040613025553311330110603550408130a43616c69666f726e6961311430120603550407130b4c6f7320416e67656c6573313c303a060355040a1333496e7465726e657420436f72706f726174696f6e20666f722041737369676e6564204e616d657320616e64204e756d6265727331133011060355040b130a546563686e6f6c6f6779311830160603550403130f7777772e6578616d706c652e6f726730820122300d06092a864886f70d01010105000382010f003082010a02820101009e663f52a3d18cb67cdfed547408a4e47e4036538988da2798da3b6655f7240d693ed1cb3fe6d6ad3a9e657ff6efa86b83b0cad24e5d31ff2bf70ec3b78b213f1b4bf61bdc669cbbc07d67154128ca92a9b3cbb4213a836fb823ddd4d7cc04918314d25f06086fa9970ba17e357cca9b458c27eb71760ab95e3f9bc898ae89050ae4d09ba2f7e4259d9ff1e072a6971b18355a8b9e53670c3d5dbdbd283f93a764e71b3a4140ca0746090c08510e2e21078d7d07844bf9c03865b531a0bf2ee766bc401f6451c5a1e6f6fb5d5c1d6a97a0abe91ae8b02e89241e07353909ccd5b41c46de207c06801e08f20713603827f2ae3e68cf15ef881d7e0608f70742e30203010001a382024630820242301f0603551d230418301680145168ff90af0207753cccd9656462a212b859723b301d0603551d0e04160414b000a7f422e9b1ce216117c4c46e7164c8e60c553081810603551d11047a3078820f7777772e6578616d706c652e6f7267820b6578616d706c652e636f6d820b6578616d706c652e656475820b6578616d706c652e6e6574820b6578616d706c652e6f7267820f7777772e6578616d706c652e636f6d820f7777772e6578616d706c652e656475820f7777772e6578616d706c652e6e6574300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b0601050507030230750603551d1f046e306c3034a032a030862e687474703a2f2f63726c332e64696769636572742e636f6d2f736861322d68612d7365727665722d67332e63726c3034a032a030862e687474703a2f2f63726c342e64696769636572742e636f6d2f736861322d68612d7365727665722d67332e63726c30420603551d20043b3039303706096086480186fd6c0101302a302806082b06010505070201161c68747470733a2f2f7777772e64696769636572742e636f6d2f43505330818306082b0601050507010104773075302406082b060105050730018618687474703a2f2f6f6373702e64696769636572742e636f6d304d06082b060105050730028641687474703a2f2f636163657274732e64696769636572742e636f6d2f446967694365727453484132486967684173737572616e636553657276657243412e637274300c0603551d130101ff04023000300d06092a864886f70d01010b050003820101005eac2124dedb3978a86ff3608406acb542d3cb54cb83facd63aec88144d6a1bf15dbf1f215c4a73e241e582365cba9ea50dd306541653b3513af1a0756c1b2720e8d112b34fb67181efad9c4609bdc670fb025fa6e6d42188161b026cf3089a08369c2f3609fc84bcc3479140c1922ede430ca8dbac2b2a3cdacb305ba15dc7361c4c3a5e6daa99cb446cb221b28078a7a944efba70d96f31ac143d959bccd2fd50e30c325ea2624fb6b6dbe9344dbcf133bfbd5b4e892d635dbf31596451672c6b65ba5ac9b3cddea92b35dab1065cae3c8cb6bb450a62ea2f72ea7c6bdc7b65fa09b012392543734083c7687d243f8d0375304d99ccd2e148966a8637a6797")
1351	if err == nil {
1352		t.Fatalf("token overflow should return an error")
1353	}
1354}
1355
1356func TestParseTLSA(t *testing.T) {
1357	lt := []string{
1358		"_443._tcp.example.org.\t3600\tIN\tTLSA\t1 1 1 c22be239f483c08957bc106219cc2d3ac1a308dfbbdd0a365f17b9351234cf00",
1359		"_443._tcp.example.org.\t3600\tIN\tTLSA\t2 1 2 4e85f45179e9cd6e0e68e2eb5be2e85ec9b92d91c609caf3ef0315213e3f92ece92c38397a607214de95c7fadc0ad0f1c604a469a0387959745032c0d51492f3",
1360		"_443._tcp.example.org.\t3600\tIN\tTLSA\t3 0 2 69ec8d2277360b215d0cd956b0e2747108dff34b27d461a41c800629e38ee6c2d1230cc9e8e36711330adc6766e6ff7c5fbb37f106f248337c1a20ad682888d2",
1361	}
1362	for _, o := range lt {
1363		rr, err := NewRR(o)
1364		if err != nil {
1365			t.Error("failed to parse RR: ", err)
1366			continue
1367		}
1368		if rr.String() != o {
1369			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", o, o, rr.String())
1370		}
1371	}
1372}
1373
1374func TestParseSMIMEA(t *testing.T) {
1375	lt := map[string]string{
1376		"2e85e1db3e62be6ea._smimecert.example.com.\t3600\tIN\tSMIMEA\t1 1 2 bd80f334566928fc18f58df7e4928c1886f48f71ca3fd41cd9b1854aca7c2180aaacad2819612ed68e7bd3701cc39be7f2529b017c0bc6a53e8fb3f0c7d48070":   "2e85e1db3e62be6ea._smimecert.example.com.\t3600\tIN\tSMIMEA\t1 1 2 bd80f334566928fc18f58df7e4928c1886f48f71ca3fd41cd9b1854aca7c2180aaacad2819612ed68e7bd3701cc39be7f2529b017c0bc6a53e8fb3f0c7d48070",
1377		"2e85e1db3e62be6ea._smimecert.example.com.\t3600\tIN\tSMIMEA\t0 0 1 cdcf0fc66b182928c5217ddd42c826983f5a4b94160ee6c1c9be62d38199f710":                                                                   "2e85e1db3e62be6ea._smimecert.example.com.\t3600\tIN\tSMIMEA\t0 0 1 cdcf0fc66b182928c5217ddd42c826983f5a4b94160ee6c1c9be62d38199f710",
1378		"2e85e1db3e62be6ea._smimecert.example.com.\t3600\tIN\tSMIMEA\t3 0 2 499a1eda2af8828b552cdb9d80c3744a25872fddd73f3898d8e4afa3549595d2dd4340126e759566fe8c26b251fa0c887ba4869f011a65f7e79967c2eb729f5b":   "2e85e1db3e62be6ea._smimecert.example.com.\t3600\tIN\tSMIMEA\t3 0 2 499a1eda2af8828b552cdb9d80c3744a25872fddd73f3898d8e4afa3549595d2dd4340126e759566fe8c26b251fa0c887ba4869f011a65f7e79967c2eb729f5b",
1379		"2e85e1db3e62be6eb._smimecert.example.com.\t3600\tIN\tSMIMEA\t3 0 2 499a1eda2af8828b552cdb9d80c3744a25872fddd73f3898d8e4afa3549595d2dd4340126e759566fe8 c26b251fa0c887ba4869f01 1a65f7e79967c2eb729f5b": "2e85e1db3e62be6eb._smimecert.example.com.\t3600\tIN\tSMIMEA\t3 0 2 499a1eda2af8828b552cdb9d80c3744a25872fddd73f3898d8e4afa3549595d2dd4340126e759566fe8c26b251fa0c887ba4869f011a65f7e79967c2eb729f5b",
1380	}
1381	for i, o := range lt {
1382		rr, err := NewRR(i)
1383		if err != nil {
1384			t.Error("failed to parse RR: ", err)
1385			continue
1386		}
1387		if rr.String() != o {
1388			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", o, o, rr.String())
1389		}
1390	}
1391}
1392
1393func TestParseSSHFP(t *testing.T) {
1394	lt := []string{
1395		"test.example.org.\t300\tSSHFP\t1 2 (\n" +
1396			"\t\t\t\t\tBC6533CDC95A79078A39A56EA7635984ED655318ADA9\n" +
1397			"\t\t\t\t\tB6159E30723665DA95BB )",
1398		"test.example.org.\t300\tSSHFP\t1 2 ( BC6533CDC  95A79078A39A56EA7635984ED655318AD  A9B6159E3072366 5DA95BB )",
1399	}
1400	result := "test.example.org.\t300\tIN\tSSHFP\t1 2 BC6533CDC95A79078A39A56EA7635984ED655318ADA9B6159E30723665DA95BB"
1401	for _, o := range lt {
1402		rr, err := NewRR(o)
1403		if err != nil {
1404			t.Error("failed to parse RR: ", err)
1405			continue
1406		}
1407		if rr.String() != result {
1408			t.Errorf("`%s' should be equal to\n\n`%s', but is     \n`%s'", o, result, rr.String())
1409		}
1410	}
1411}
1412
1413func TestParseHINFO(t *testing.T) {
1414	dt := map[string]string{
1415		"example.net. HINFO A B": "example.net.	3600	IN	HINFO	\"A\" \"B\"",
1416		"example.net. HINFO \"A\" \"B\"": "example.net.	3600	IN	HINFO	\"A\" \"B\"",
1417		"example.net. HINFO A B C D E F": "example.net.	3600	IN	HINFO	\"A\" \"B C D E F\"",
1418		"example.net. HINFO AB": "example.net.	3600	IN	HINFO	\"AB\" \"\"",
1419		// "example.net. HINFO PC-Intel-700mhz \"Redhat Linux 7.1\"": "example.net.	3600	IN	HINFO	\"PC-Intel-700mhz\" \"Redhat Linux 7.1\"",
1420		// This one is recommended in Pro Bind book http://www.zytrax.com/books/dns/ch8/hinfo.html
1421		// but effectively, even Bind would replace it to correctly formed text when you AXFR
1422		// TODO: remove this set of comments or figure support for quoted/unquoted combinations in endingToTxtSlice function
1423	}
1424	for i, o := range dt {
1425		rr, err := NewRR(i)
1426		if err != nil {
1427			t.Error("failed to parse RR: ", err)
1428			continue
1429		}
1430		if rr.String() != o {
1431			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", i, o, rr.String())
1432		}
1433	}
1434}
1435
1436func TestParseCAA(t *testing.T) {
1437	lt := map[string]string{
1438		"example.net.	CAA	0 issue \"symantec.com\"": "example.net.\t3600\tIN\tCAA\t0 issue \"symantec.com\"",
1439		"example.net.	CAA	0 issuewild \"symantec.com; stuff\"": "example.net.\t3600\tIN\tCAA\t0 issuewild \"symantec.com; stuff\"",
1440		"example.net.	CAA	128 tbs \"critical\"": "example.net.\t3600\tIN\tCAA\t128 tbs \"critical\"",
1441		"example.net.	CAA	2 auth \"0>09\\006\\010+\\006\\001\\004\\001\\214y\\002\\003\\001\\006\\009`\\134H\\001e\\003\\004\\002\\001\\004 y\\209\\012\\221r\\220\\156Q\\218\\150\\150{\\166\\245:\\231\\182%\\157:\\133\\179}\\1923r\\238\\151\\255\\128q\\145\\002\\001\\000\"": "example.net.\t3600\tIN\tCAA\t2 auth \"0>09\\006\\010+\\006\\001\\004\\001\\214y\\002\\003\\001\\006\\009`\\134H\\001e\\003\\004\\002\\001\\004 y\\209\\012\\221r\\220\\156Q\\218\\150\\150{\\166\\245:\\231\\182%\\157:\\133\\179}\\1923r\\238\\151\\255\\128q\\145\\002\\001\\000\"",
1442		"example.net.   TYPE257	0 issue \"symantec.com\"": "example.net.\t3600\tIN\tCAA\t0 issue \"symantec.com\"",
1443	}
1444	for i, o := range lt {
1445		rr, err := NewRR(i)
1446		if err != nil {
1447			t.Error("failed to parse RR: ", err)
1448			continue
1449		}
1450		if rr.String() != o {
1451			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", i, o, rr.String())
1452		}
1453	}
1454}
1455
1456func TestPackCAA(t *testing.T) {
1457	m := new(Msg)
1458	record := new(CAA)
1459	record.Hdr = RR_Header{Name: "example.com.", Rrtype: TypeCAA, Class: ClassINET, Ttl: 0}
1460	record.Tag = "issue"
1461	record.Value = "symantec.com"
1462	record.Flag = 1
1463
1464	m.Answer = append(m.Answer, record)
1465	bytes, err := m.Pack()
1466	if err != nil {
1467		t.Fatalf("failed to pack msg: %v", err)
1468	}
1469	if err := m.Unpack(bytes); err != nil {
1470		t.Fatalf("failed to unpack msg: %v", err)
1471	}
1472	if len(m.Answer) != 1 {
1473		t.Fatalf("incorrect number of answers unpacked")
1474	}
1475	rr := m.Answer[0].(*CAA)
1476	if rr.Tag != "issue" {
1477		t.Fatalf("invalid tag for unpacked answer")
1478	} else if rr.Value != "symantec.com" {
1479		t.Fatalf("invalid value for unpacked answer")
1480	} else if rr.Flag != 1 {
1481		t.Fatalf("invalid flag for unpacked answer")
1482	}
1483}
1484
1485func TestParseURI(t *testing.T) {
1486	lt := map[string]string{
1487		"_http._tcp. IN URI   10 1 \"http://www.example.com/path\"": "_http._tcp.\t3600\tIN\tURI\t10 1 \"http://www.example.com/path\"",
1488		"_http._tcp. IN URI   10 1 \"\"":                            "_http._tcp.\t3600\tIN\tURI\t10 1 \"\"",
1489	}
1490	for i, o := range lt {
1491		rr, err := NewRR(i)
1492		if err != nil {
1493			t.Error("failed to parse RR: ", err)
1494			continue
1495		}
1496		if rr.String() != o {
1497			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", i, o, rr.String())
1498		}
1499	}
1500}
1501
1502func TestParseAVC(t *testing.T) {
1503	avcs := map[string]string{
1504		`example.org. IN AVC "app-name:WOLFGANG|app-class:OAM|business=yes"`: `example.org.	3600	IN	AVC	"app-name:WOLFGANG|app-class:OAM|business=yes"`,
1505	}
1506	for avc, o := range avcs {
1507		rr, err := NewRR(avc)
1508		if err != nil {
1509			t.Error("failed to parse RR: ", err)
1510			continue
1511		}
1512		if rr.String() != o {
1513			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", avc, o, rr.String())
1514		}
1515	}
1516}
1517
1518func TestParseCSYNC(t *testing.T) {
1519	syncs := map[string]string{
1520		`example.com. 3600 IN CSYNC 66 3 A NS AAAA`: `example.com.	3600	IN	CSYNC	66 3 A NS AAAA`,
1521	}
1522	for s, o := range syncs {
1523		rr, err := NewRR(s)
1524		if err != nil {
1525			t.Error("failed to parse RR: ", err)
1526			continue
1527		}
1528		if rr.String() != o {
1529			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", s, o, rr.String())
1530		}
1531	}
1532}
1533
1534func TestParseBadNAPTR(t *testing.T) {
1535	// Should look like: mplus.ims.vodafone.com.	3600	IN	NAPTR	10 100 "S" "SIP+D2U" "" _sip._udp.mplus.ims.vodafone.com.
1536	naptr := `mplus.ims.vodafone.com.	3600	IN	NAPTR	10 100 S SIP+D2U  _sip._udp.mplus.ims.vodafone.com.`
1537	_, err := NewRR(naptr) // parse fails, we should not have leaked a goroutine.
1538	if err == nil {
1539		t.Fatalf("parsing NAPTR should have failed: %s", naptr)
1540	}
1541	if err := goroutineLeaked(); err != nil {
1542		t.Errorf("leaked goroutines: %s", err)
1543	}
1544}
1545
1546func TestUnbalancedParens(t *testing.T) {
1547	sig := `example.com. 3600 IN RRSIG MX 15 2 3600 (
1548              1440021600 1438207200 3613 example.com. (
1549              oL9krJun7xfBOIWcGHi7mag5/hdZrKWw15jPGrHpjQeRAvTdszaPD+QLs3f
1550              x8A4M3e23mRZ9VrbpMngwcrqNAg== )`
1551	_, err := NewRR(sig)
1552	if err == nil {
1553		t.Fatalf("failed to detect extra opening brace")
1554	}
1555}
1556
1557func TestBad(t *testing.T) {
1558	tests := []string{
1559		`" TYPE257 9 1E12\x00\x105"`,
1560		`" TYPE256  9 5"`,
1561		`" TYPE257 0\"00000000000000400000000000000000000\x00\x10000000000000000000000000000000000 9 l\x16\x01\x005266"`,
1562	}
1563	for i := range tests {
1564		s, err := strconv.Unquote(tests[i])
1565		if err != nil {
1566			t.Fatalf("failed to unquote: %q: %s", tests[i], err)
1567		}
1568		if _, err = NewRR(s); err == nil {
1569			t.Errorf("correctly parsed %q", s)
1570		}
1571	}
1572}
1573
1574func TestNULLRecord(t *testing.T) {
1575	// packet captured from iodine
1576	packet := `8116840000010001000000000569627a6c700474657374046d69656b026e6c00000a0001c00c000a0001000000000005497f000001`
1577	data, _ := hex.DecodeString(packet)
1578	msg := new(Msg)
1579	err := msg.Unpack(data)
1580	if err != nil {
1581		t.Fatalf("Failed to unpack NULL record")
1582	}
1583	if _, ok := msg.Answer[0].(*NULL); !ok {
1584		t.Fatalf("Expected packet to contain NULL record")
1585	}
1586}
1587
1588func TestParseAPL(t *testing.T) {
1589	tests := []struct {
1590		name   string
1591		in     string
1592		expect string
1593	}{
1594		{
1595			"v4",
1596			". APL 1:192.0.2.0/24",
1597			".\t3600\tIN\tAPL\t1:192.0.2.0/24",
1598		},
1599		{
1600			"v6",
1601			". APL 2:2001:db8::/32",
1602			".\t3600\tIN\tAPL\t2:2001:db8::/32",
1603		},
1604		{
1605			"null v6",
1606			". APL 2:::/0",
1607			".\t3600\tIN\tAPL\t2:::/0",
1608		},
1609		{
1610			"null v4",
1611			". APL 1:0.0.0.0/0",
1612			".\t3600\tIN\tAPL\t1:0.0.0.0/0",
1613		},
1614		{
1615			"full v6",
1616			". APL 2:::/0",
1617			".\t3600\tIN\tAPL\t2:::/0",
1618		},
1619		{
1620			"full v4",
1621			". APL 1:192.0.2.1/32",
1622			".\t3600\tIN\tAPL\t1:192.0.2.1/32",
1623		},
1624		{
1625			"full v6",
1626			". APL 2:2001:0db8:d2b4:b6ba:50db:49cc:a8d1:5bb1/128",
1627			".\t3600\tIN\tAPL\t2:2001:db8:d2b4:b6ba:50db:49cc:a8d1:5bb1/128",
1628		},
1629		{
1630			"v4in6",
1631			". APL 2:::ffff:192.0.2.0/120",
1632			".\t3600\tIN\tAPL\t2:::ffff:192.0.2.0/120",
1633		},
1634		{
1635			"v4in6 v6 syntax",
1636			". APL 2:::ffff:c000:0200/120",
1637			".\t3600\tIN\tAPL\t2:::ffff:192.0.2.0/120",
1638		},
1639		{
1640			"negate",
1641			". APL !1:192.0.2.0/24",
1642			".\t3600\tIN\tAPL\t!1:192.0.2.0/24",
1643		},
1644		{
1645			"multiple",
1646			". APL 1:192.0.2.0/24 !1:192.0.2.1/32 2:2001:db8::/32 !2:2001:db8:1::0/48",
1647			".\t3600\tIN\tAPL\t1:192.0.2.0/24 !1:192.0.2.1/32 2:2001:db8::/32 !2:2001:db8:1::/48",
1648		},
1649		{
1650			"no address",
1651			". APL",
1652			".\t3600\tIN\tAPL\t",
1653		},
1654	}
1655	for _, tc := range tests {
1656		t.Run(tc.name, func(t *testing.T) {
1657			rr, err := NewRR(tc.in)
1658			if err != nil {
1659				t.Fatalf("failed to parse RR: %s", err)
1660			}
1661
1662			got := rr.String()
1663			if got != tc.expect {
1664				t.Errorf("expected %q, got %q", tc.expect, got)
1665			}
1666		})
1667	}
1668}
1669
1670func TestParseAPLErrors(t *testing.T) {
1671	tests := []struct {
1672		name string
1673		in   string
1674	}{
1675		{
1676			"unexpected",
1677			`. APL ""`,
1678		},
1679		{
1680			"unrecognized family",
1681			". APL 3:0.0.0.0/0",
1682		},
1683		{
1684			"malformed family",
1685			". APL foo:0.0.0.0/0",
1686		},
1687		{
1688			"malformed address",
1689			". APL 1:192.0.2/16",
1690		},
1691		{
1692			"extra bits",
1693			". APL 2:2001:db8::/0",
1694		},
1695		{
1696			"address mismatch v2",
1697			". APL 1:2001:db8::/64",
1698		},
1699		{
1700			"address mismatch v6",
1701			". APL 2:192.0.2.1/32",
1702		},
1703		{
1704			"no prefix",
1705			". APL 1:192.0.2.1",
1706		},
1707		{
1708			"no family",
1709			". APL 0.0.0.0/0",
1710		},
1711	}
1712	for _, tc := range tests {
1713		t.Run(tc.name, func(t *testing.T) {
1714			_, err := NewRR(tc.in)
1715			if err == nil {
1716				t.Fatal("expected error, got none")
1717			}
1718		})
1719	}
1720}
1721