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		expectedTTL, _ := strconv.ParseUint(expected[1], 10, 32)
547		ttl := record.RR.Header().Ttl
548		if ttl != uint32(expectedTTL) {
549			t.Errorf("%s: expected TTL %d, got %d", expected[2], expectedTTL, ttl)
550		}
551	}
552	if i != 10 {
553		t.Errorf("expected %d records, got %d", 5, i)
554	}
555}
556
557func TestRelativeNameErrors(t *testing.T) {
558	var badZones = []struct {
559		label        string
560		zoneContents string
561		expectedErr  string
562	}{
563		{
564			"relative owner name without origin",
565			"example.com 3600 IN SOA ns.example.com. hostmaster.example.com. 1 86400 60 86400 3600",
566			"bad owner name",
567		},
568		{
569			"relative owner name in RDATA",
570			"example.com. 3600 IN SOA ns hostmaster 1 86400 60 86400 3600",
571			"bad SOA Ns",
572		},
573		{
574			"origin reference without origin",
575			"@ 3600 IN SOA ns.example.com. hostmaster.example.com. 1 86400 60 86400 3600",
576			"bad owner name",
577		},
578		{
579			"relative owner name in $INCLUDE",
580			"$INCLUDE file.db example.com",
581			"bad origin name",
582		},
583		{
584			"relative owner name in $ORIGIN",
585			"$ORIGIN example.com",
586			"bad origin name",
587		},
588	}
589	for _, errorCase := range badZones {
590		entries := ParseZone(strings.NewReader(errorCase.zoneContents), "", "")
591		for entry := range entries {
592			if entry.Error == nil {
593				t.Errorf("%s: expected error, got nil", errorCase.label)
594				continue
595			}
596			err := entry.Error.err
597			if err != errorCase.expectedErr {
598				t.Errorf("%s: expected error `%s`, got `%s`", errorCase.label, errorCase.expectedErr, err)
599			}
600		}
601	}
602}
603
604func TestHIP(t *testing.T) {
605	h := `www.example.com.      IN  HIP ( 2 200100107B1A74DF365639CC39F1D578
606                                AwEAAbdxyhNuSutc5EMzxTs9LBPCIkOFH8cIvM4p
6079+LrV4e19WzK00+CI6zBCQTdtWsuxKbWIy87UOoJTwkUs7lBu+Upr1gsNrut79ryra+bSRGQ
608b1slImA8YVJyuIDsj7kwzG7jnERNqnWxZ48AWkskmdHaVDP4BcelrTI3rMXdXF5D
609                                rvs1.example.com.
610                                rvs2.example.com. )`
611	rr, err := NewRR(h)
612	if err != nil {
613		t.Fatalf("failed to parse RR: %v", err)
614	}
615	msg := new(Msg)
616	msg.Answer = []RR{rr, rr}
617	bytes, err := msg.Pack()
618	if err != nil {
619		t.Fatalf("failed to pack msg: %v", err)
620	}
621	if err := msg.Unpack(bytes); err != nil {
622		t.Fatalf("failed to unpack msg: %v", err)
623	}
624	if len(msg.Answer) != 2 {
625		t.Fatalf("2 answers expected: %v", msg)
626	}
627	for i, rr := range msg.Answer {
628		rr := rr.(*HIP)
629		if l := len(rr.RendezvousServers); l != 2 {
630			t.Fatalf("2 servers expected, only %d in record %d:\n%v", l, i, msg)
631		}
632		for j, s := range []string{"rvs1.example.com.", "rvs2.example.com."} {
633			if rr.RendezvousServers[j] != s {
634				t.Fatalf("expected server %d of record %d to be %s:\n%v", j, i, s, msg)
635			}
636		}
637	}
638}
639
640// Test with no known RR on the line
641func TestLineNumberError2(t *testing.T) {
642	tests := map[string]string{
643		"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",
644		"example.com 1000 IN TALINK a.example.com. b..example.com.":                                          "dns: bad TALINK NextName: \"b..example.com.\" at line: 1:57",
645		"example.com 1000 IN TALINK ( a.example.com. b..example.com. )":                                      "dns: bad TALINK NextName: \"b..example.com.\" at line: 1:60",
646		`example.com 1000 IN TALINK ( a.example.com.
647	bb..example.com. )`: "dns: bad TALINK NextName: \"bb..example.com.\" at line: 2:18",
648		// This is a bug, it should report an error on line 1, but the new is already processed.
649		`example.com 1000 IN TALINK ( a.example.com.  b...example.com.
650	)`: "dns: bad TALINK NextName: \"b...example.com.\" at line: 2:1"}
651
652	for in, errStr := range tests {
653		_, err := NewRR(in)
654		if err == nil {
655			t.Error("err is nil")
656		} else {
657			if err.Error() != errStr {
658				t.Errorf("%s: error should be %s is %v", in, errStr, err)
659			}
660		}
661	}
662}
663
664// Test if the calculations are correct
665func TestRfc1982(t *testing.T) {
666	// If the current time and the timestamp are more than 68 years apart
667	// it means the date has wrapped. 0 is 1970
668
669	// fall in the current 68 year span
670	strtests := []string{"20120525134203", "19700101000000", "20380119031408"}
671	for _, v := range strtests {
672		if x, _ := StringToTime(v); v != TimeToString(x) {
673			t.Errorf("1982 arithmetic string failure %s (%s:%d)", v, TimeToString(x), x)
674		}
675	}
676
677	inttests := map[uint32]string{0: "19700101000000",
678		1 << 31:   "20380119031408",
679		1<<32 - 1: "21060207062815",
680	}
681	for i, v := range inttests {
682		if TimeToString(i) != v {
683			t.Errorf("1982 arithmetic int failure %d:%s (%s)", i, v, TimeToString(i))
684		}
685	}
686
687	// Future tests, these dates get parsed to a date within the current 136 year span
688	future := map[string]string{"22680119031408": "20631123173144",
689		"19010101121212": "20370206184028",
690		"19210101121212": "20570206184028",
691		"19500101121212": "20860206184028",
692		"19700101000000": "19700101000000",
693		"19690101000000": "21050207062816",
694		"29210101121212": "21040522212236",
695	}
696	for from, to := range future {
697		x, _ := StringToTime(from)
698		y := TimeToString(x)
699		if y != to {
700			t.Errorf("1982 arithmetic future failure %s:%s (%s)", from, to, y)
701		}
702	}
703}
704
705func TestEmpty(t *testing.T) {
706	for range ParseZone(strings.NewReader(""), "", "") {
707		t.Errorf("should be empty")
708	}
709}
710
711func TestLowercaseTokens(t *testing.T) {
712	var testrecords = []string{
713		"example.org. 300 IN a 1.2.3.4",
714		"example.org. 300 in A 1.2.3.4",
715		"example.org. 300 in a 1.2.3.4",
716		"example.org. 300 a 1.2.3.4",
717		"example.org. 300 A 1.2.3.4",
718		"example.org. IN a 1.2.3.4",
719		"example.org. in A 1.2.3.4",
720		"example.org. in a 1.2.3.4",
721		"example.org. a 1.2.3.4",
722		"example.org. A 1.2.3.4",
723		"example.org. a 1.2.3.4",
724		"$ORIGIN example.org.\n a 1.2.3.4",
725		"$Origin example.org.\n a 1.2.3.4",
726		"$origin example.org.\n a 1.2.3.4",
727		"example.org. Class1 Type1 1.2.3.4",
728	}
729	for _, testrr := range testrecords {
730		_, err := NewRR(testrr)
731		if err != nil {
732			t.Errorf("failed to parse %#v, got %v", testrr, err)
733		}
734	}
735}
736
737func TestSRVPacking(t *testing.T) {
738	msg := Msg{}
739
740	things := []string{"1.2.3.4:8484",
741		"45.45.45.45:8484",
742		"84.84.84.84:8484",
743	}
744
745	for i, n := range things {
746		h, p, err := net.SplitHostPort(n)
747		if err != nil {
748			continue
749		}
750		port, _ := strconv.ParseUint(p, 10, 16)
751
752		rr := &SRV{
753			Hdr: RR_Header{Name: "somename.",
754				Rrtype: TypeSRV,
755				Class:  ClassINET,
756				Ttl:    5},
757			Priority: uint16(i),
758			Weight:   5,
759			Port:     uint16(port),
760			Target:   h + ".",
761		}
762
763		msg.Answer = append(msg.Answer, rr)
764	}
765
766	_, err := msg.Pack()
767	if err != nil {
768		t.Fatalf("couldn't pack %v: %v", msg, err)
769	}
770}
771
772func TestParseBackslash(t *testing.T) {
773	if _, err := NewRR("nul\\000gap.test.globnix.net. 600 IN	A 192.0.2.10"); err != nil {
774		t.Errorf("could not create RR with \\000 in it")
775	}
776	if _, err := NewRR(`nul\000gap.test.globnix.net. 600 IN TXT "Hello\123"`); err != nil {
777		t.Errorf("could not create RR with \\000 in it")
778	}
779	if _, err := NewRR(`m\ @\ iek.nl. IN 3600 A 127.0.0.1`); err != nil {
780		t.Errorf("could not create RR with \\ and \\@ in it")
781	}
782}
783
784func TestILNP(t *testing.T) {
785	tests := []string{
786		"host1.example.com.\t3600\tIN\tNID\t10 0014:4fff:ff20:ee64",
787		"host1.example.com.\t3600\tIN\tNID\t20 0015:5fff:ff21:ee65",
788		"host2.example.com.\t3600\tIN\tNID\t10 0016:6fff:ff22:ee66",
789		"host1.example.com.\t3600\tIN\tL32\t10 10.1.2.0",
790		"host1.example.com.\t3600\tIN\tL32\t20 10.1.4.0",
791		"host2.example.com.\t3600\tIN\tL32\t10 10.1.8.0",
792		"host1.example.com.\t3600\tIN\tL64\t10 2001:0DB8:1140:1000",
793		"host1.example.com.\t3600\tIN\tL64\t20 2001:0DB8:2140:2000",
794		"host2.example.com.\t3600\tIN\tL64\t10 2001:0DB8:4140:4000",
795		"host1.example.com.\t3600\tIN\tLP\t10 l64-subnet1.example.com.",
796		"host1.example.com.\t3600\tIN\tLP\t10 l64-subnet2.example.com.",
797		"host1.example.com.\t3600\tIN\tLP\t20 l32-subnet1.example.com.",
798	}
799	for _, t1 := range tests {
800		r, err := NewRR(t1)
801		if err != nil {
802			t.Fatalf("an error occurred: %v", err)
803		} else {
804			if t1 != r.String() {
805				t.Fatalf("strings should be equal %s %s", t1, r.String())
806			}
807		}
808	}
809}
810
811func TestGposEidNimloc(t *testing.T) {
812	dt := map[string]string{
813		"444433332222111199990123000000ff. NSAP-PTR foo.bar.com.": "444433332222111199990123000000ff.\t3600\tIN\tNSAP-PTR\tfoo.bar.com.",
814		"lillee. IN  GPOS -32.6882 116.8652 10.0":                 "lillee.\t3600\tIN\tGPOS\t-32.6882 116.8652 10.0",
815		"hinault. IN GPOS -22.6882 116.8652 250.0":                "hinault.\t3600\tIN\tGPOS\t-22.6882 116.8652 250.0",
816		"VENERA.   IN NIMLOC  75234159EAC457800920":               "VENERA.\t3600\tIN\tNIMLOC\t75234159EAC457800920",
817		"VAXA.     IN EID     3141592653589793":                   "VAXA.\t3600\tIN\tEID\t3141592653589793",
818	}
819	for i, o := range dt {
820		rr, err := NewRR(i)
821		if err != nil {
822			t.Error("failed to parse RR: ", err)
823			continue
824		}
825		if rr.String() != o {
826			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", i, o, rr.String())
827		}
828	}
829}
830
831func TestPX(t *testing.T) {
832	dt := map[string]string{
833		"*.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.",
834		"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.",
835	}
836	for i, o := range dt {
837		rr, err := NewRR(i)
838		if err != nil {
839			t.Error("failed to parse RR: ", err)
840			continue
841		}
842		if rr.String() != o {
843			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", i, o, rr.String())
844		}
845	}
846}
847
848func TestComment(t *testing.T) {
849	// Comments we must see
850	comments := map[string]bool{
851		"; this is comment 1": true,
852		"; this is comment 2": true,
853		"; this is comment 4": true,
854		"; this is comment 6": true,
855		"; this is comment 7": true,
856		"; this is comment 8": true,
857	}
858	zone := `
859foo. IN A 10.0.0.1 ; this is comment 1
860foo. IN A (
861	10.0.0.2 ; this is comment 2
862)
863; this is comment 3
864foo. IN A 10.0.0.3
865foo. IN A ( 10.0.0.4 ); this is comment 4
866
867foo. IN A 10.0.0.5
868; this is comment 5
869
870foo. IN A 10.0.0.6
871
872foo. IN DNSKEY 256 3 5 AwEAAb+8l ; this is comment 6
873foo. IN NSEC miek.nl. TXT RRSIG NSEC; this is comment 7
874foo. IN TXT "THIS IS TEXT MAN"; this is comment 8
875`
876	for x := range ParseZone(strings.NewReader(zone), ".", "") {
877		if x.Error == nil {
878			if x.Comment != "" {
879				if _, ok := comments[x.Comment]; !ok {
880					t.Errorf("wrong comment %q", x.Comment)
881				}
882			}
883		}
884	}
885}
886
887func TestParseZoneComments(t *testing.T) {
888	for i, test := range []struct {
889		zone     string
890		comments []string
891	}{
892		{
893			`name. IN SOA  a6.nstld.com. hostmaster.nic.name. (
894			203362132 ; serial
895			5m        ; refresh (5 minutes)
896			5m        ; retry (5 minutes)
897			2w        ; expire (2 weeks)
898			300       ; minimum (5 minutes)
899		) ; y
900. 3600000  IN  NS ONE.MY-ROOTS.NET. ; x`,
901			[]string{"; serial ; refresh (5 minutes) ; retry (5 minutes) ; expire (2 weeks) ; minimum (5 minutes) ; y", "; x"},
902		},
903		{
904			`name. IN SOA  a6.nstld.com. hostmaster.nic.name. (
905			203362132 ; serial
906			5m        ; refresh (5 minutes)
907			5m        ; retry (5 minutes)
908			2w        ; expire (2 weeks)
909			300       ; minimum (5 minutes)
910		) ; y
911. 3600000  IN  NS ONE.MY-ROOTS.NET.`,
912			[]string{"; serial ; refresh (5 minutes) ; retry (5 minutes) ; expire (2 weeks) ; minimum (5 minutes) ; y", ""},
913		},
914		{
915			`name. IN SOA  a6.nstld.com. hostmaster.nic.name. (
916			203362132 ; serial
917			5m        ; refresh (5 minutes)
918			5m        ; retry (5 minutes)
919			2w        ; expire (2 weeks)
920			300       ; minimum (5 minutes)
921		)
922. 3600000  IN  NS ONE.MY-ROOTS.NET.`,
923			[]string{"; serial ; refresh (5 minutes) ; retry (5 minutes) ; expire (2 weeks) ; minimum (5 minutes)", ""},
924		},
925		{
926			`name. IN SOA  a6.nstld.com. hostmaster.nic.name. (
927			203362132 ; serial
928			5m        ; refresh (5 minutes)
929			5m        ; retry (5 minutes)
930			2w        ; expire (2 weeks)
931			300       ; minimum (5 minutes)
932		)
933. 3600000  IN  NS ONE.MY-ROOTS.NET. ; x`,
934			[]string{"; serial ; refresh (5 minutes) ; retry (5 minutes) ; expire (2 weeks) ; minimum (5 minutes)", "; x"},
935		},
936		{
937			`name. IN SOA  a6.nstld.com. hostmaster.nic.name. (
938			203362132 ; serial
939			5m        ; refresh (5 minutes)
940			5m        ; retry (5 minutes)
941			2w        ; expire (2 weeks)
942			300       ; minimum (5 minutes)
943		)`,
944			[]string{"; serial ; refresh (5 minutes) ; retry (5 minutes) ; expire (2 weeks) ; minimum (5 minutes)"},
945		},
946		{
947			`. 3600000  IN  NS ONE.MY-ROOTS.NET. ; x`,
948			[]string{"; x"},
949		},
950		{
951			`. 3600000  IN  NS ONE.MY-ROOTS.NET.`,
952			[]string{""},
953		},
954		{
955			`. 3600000  IN  NS ONE.MY-ROOTS.NET. ;;x`,
956			[]string{";;x"},
957		},
958	} {
959		r := strings.NewReader(test.zone)
960
961		var j int
962		for r := range ParseZone(r, "", "") {
963			if r.Error != nil {
964				t.Fatal(r.Error)
965			}
966
967			if j >= len(test.comments) {
968				t.Fatalf("too many records for zone %d at %d record, expected %d", i, j+1, len(test.comments))
969			}
970
971			if r.Comment != test.comments[j] {
972				t.Errorf("invalid comment for record %d:%d %v / %v", i, j, r.RR, r.Error)
973				t.Logf("expected %q", test.comments[j])
974				t.Logf("got      %q", r.Comment)
975			}
976
977			j++
978		}
979
980		if j != len(test.comments) {
981			t.Errorf("too few records for zone %d, got %d, expected %d", i, j, len(test.comments))
982		}
983	}
984}
985
986func TestEUIxx(t *testing.T) {
987	tests := map[string]string{
988		"host.example. IN EUI48 00-00-5e-90-01-2a":       "host.example.\t3600\tIN\tEUI48\t00-00-5e-90-01-2a",
989		"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",
990	}
991	for i, o := range tests {
992		r, err := NewRR(i)
993		if err != nil {
994			t.Errorf("failed to parse %s: %v", i, err)
995		}
996		if r.String() != o {
997			t.Errorf("want %s, got %s", o, r.String())
998		}
999	}
1000}
1001
1002func TestUserRR(t *testing.T) {
1003	tests := map[string]string{
1004		"host.example. IN UID 1234":              "host.example.\t3600\tIN\tUID\t1234",
1005		"host.example. IN GID 1234556":           "host.example.\t3600\tIN\tGID\t1234556",
1006		"host.example. IN UINFO \"Miek Gieben\"": "host.example.\t3600\tIN\tUINFO\t\"Miek Gieben\"",
1007	}
1008	for i, o := range tests {
1009		r, err := NewRR(i)
1010		if err != nil {
1011			t.Errorf("failed to parse %s: %v", i, err)
1012		}
1013		if r.String() != o {
1014			t.Errorf("want %s, got %s", o, r.String())
1015		}
1016	}
1017}
1018
1019func TestTXT(t *testing.T) {
1020	// Test single entry TXT record
1021	rr, err := NewRR(`_raop._tcp.local. 60 IN TXT "single value"`)
1022	if err != nil {
1023		t.Error("failed to parse single value TXT record", err)
1024	} else if rr, ok := rr.(*TXT); !ok {
1025		t.Error("wrong type, record should be of type TXT")
1026	} else {
1027		if len(rr.Txt) != 1 {
1028			t.Error("bad size of TXT value:", len(rr.Txt))
1029		} else if rr.Txt[0] != "single value" {
1030			t.Error("bad single value")
1031		}
1032		if rr.String() != `_raop._tcp.local.	60	IN	TXT	"single value"` {
1033			t.Error("bad representation of TXT record:", rr.String())
1034		}
1035		if rr.len() != 28+1+12 {
1036			t.Error("bad size of serialized record:", rr.len())
1037		}
1038	}
1039
1040	// Test multi entries TXT record
1041	rr, err = NewRR(`_raop._tcp.local. 60 IN TXT "a=1" "b=2" "c=3" "d=4"`)
1042	if err != nil {
1043		t.Error("failed to parse multi-values TXT record", err)
1044	} else if rr, ok := rr.(*TXT); !ok {
1045		t.Error("wrong type, record should be of type TXT")
1046	} else {
1047		if len(rr.Txt) != 4 {
1048			t.Error("bad size of TXT multi-value:", len(rr.Txt))
1049		} else if rr.Txt[0] != "a=1" || rr.Txt[1] != "b=2" || rr.Txt[2] != "c=3" || rr.Txt[3] != "d=4" {
1050			t.Error("bad values in TXT records")
1051		}
1052		if rr.String() != `_raop._tcp.local.	60	IN	TXT	"a=1" "b=2" "c=3" "d=4"` {
1053			t.Error("bad representation of TXT multi value record:", rr.String())
1054		}
1055		if rr.len() != 28+1+3+1+3+1+3+1+3 {
1056			t.Error("bad size of serialized multi value record:", rr.len())
1057		}
1058	}
1059
1060	// Test empty-string in TXT record
1061	rr, err = NewRR(`_raop._tcp.local. 60 IN TXT ""`)
1062	if err != nil {
1063		t.Error("failed to parse empty-string TXT record", err)
1064	} else if rr, ok := rr.(*TXT); !ok {
1065		t.Error("wrong type, record should be of type TXT")
1066	} else {
1067		if len(rr.Txt) != 1 {
1068			t.Error("bad size of TXT empty-string value:", len(rr.Txt))
1069		} else if rr.Txt[0] != "" {
1070			t.Error("bad value for empty-string TXT record")
1071		}
1072		if rr.String() != `_raop._tcp.local.	60	IN	TXT	""` {
1073			t.Error("bad representation of empty-string TXT record:", rr.String())
1074		}
1075		if rr.len() != 28+1 {
1076			t.Error("bad size of serialized record:", rr.len())
1077		}
1078	}
1079
1080	// Test TXT record with chunk larger than 255 bytes, they should be split up, by the parser
1081	s := ""
1082	for i := 0; i < 255; i++ {
1083		s += "a"
1084	}
1085	s += "b"
1086	rr, err = NewRR(`test.local. 60 IN TXT "` + s + `"`)
1087	if err != nil {
1088		t.Error("failed to parse empty-string TXT record", err)
1089	}
1090	if rr.(*TXT).Txt[1] != "b" {
1091		t.Errorf("Txt should have two chunk, last one my be 'b', but is %s", rr.(*TXT).Txt[1])
1092	}
1093}
1094
1095func TestTypeXXXX(t *testing.T) {
1096	_, err := NewRR("example.com IN TYPE1234 \\# 4 aabbccdd")
1097	if err != nil {
1098		t.Errorf("failed to parse TYPE1234 RR: %v", err)
1099	}
1100	_, err = NewRR("example.com IN TYPE655341 \\# 8 aabbccddaabbccdd")
1101	if err == nil {
1102		t.Errorf("this should not work, for TYPE655341")
1103	}
1104	_, err = NewRR("example.com IN TYPE1 \\# 4 0a000001")
1105	if err == nil {
1106		t.Errorf("this should not work")
1107	}
1108}
1109
1110func TestPTR(t *testing.T) {
1111	_, err := NewRR("144.2.0.192.in-addr.arpa. 900 IN PTR ilouse03146p0\\(.example.com.")
1112	if err != nil {
1113		t.Error("failed to parse ", err)
1114	}
1115}
1116
1117func TestDigit(t *testing.T) {
1118	tests := map[string]byte{
1119		"miek\\000.nl. 100 IN TXT \"A\"": 0,
1120		"miek\\001.nl. 100 IN TXT \"A\"": 1,
1121		"miek\\254.nl. 100 IN TXT \"A\"": 254,
1122		"miek\\255.nl. 100 IN TXT \"A\"": 255,
1123		"miek\\256.nl. 100 IN TXT \"A\"": 0,
1124		"miek\\257.nl. 100 IN TXT \"A\"": 1,
1125		"miek\\004.nl. 100 IN TXT \"A\"": 4,
1126	}
1127	for s, i := range tests {
1128		r, err := NewRR(s)
1129		buf := make([]byte, 40)
1130		if err != nil {
1131			t.Fatalf("failed to parse %v", err)
1132		}
1133		PackRR(r, buf, 0, nil, false)
1134		if buf[5] != i {
1135			t.Fatalf("5 pos must be %d, is %d", i, buf[5])
1136		}
1137		r1, _, _ := UnpackRR(buf, 0)
1138		if r1.Header().Ttl != 100 {
1139			t.Fatalf("TTL should %d, is %d", 100, r1.Header().Ttl)
1140		}
1141	}
1142}
1143
1144func TestParseRRSIGTimestamp(t *testing.T) {
1145	tests := map[string]bool{
1146		`miek.nl.  IN RRSIG SOA 8 2 43200 20140210031301 20140111031301 12051 miek.nl. MVZUyrYwq0iZhMFDDnVXD2BvuNiUJjSYlJAgzyAE6CF875BMvvZa+Sb0 RlSCL7WODQSQHhCx/fegHhVVF+Iz8N8kOLrmXD1+jO3Bm6Prl5UhcsPx WTBsg/kmxbp8sR1kvH4oZJtVfakG3iDerrxNaf0sQwhZzyfJQAqpC7pcBoc=`: true,
1147		`miek.nl.  IN RRSIG SOA 8 2 43200 315565800 4102477800 12051 miek.nl. MVZUyrYwq0iZhMFDDnVXD2BvuNiUJjSYlJAgzyAE6CF875BMvvZa+Sb0 RlSCL7WODQSQHhCx/fegHhVVF+Iz8N8kOLrmXD1+jO3Bm6Prl5UhcsPx WTBsg/kmxbp8sR1kvH4oZJtVfakG3iDerrxNaf0sQwhZzyfJQAqpC7pcBoc=`:          true,
1148	}
1149	for r := range tests {
1150		_, err := NewRR(r)
1151		if err != nil {
1152			t.Error(err)
1153		}
1154	}
1155}
1156
1157func TestTxtEqual(t *testing.T) {
1158	rr1 := new(TXT)
1159	rr1.Hdr = RR_Header{Name: ".", Rrtype: TypeTXT, Class: ClassINET, Ttl: 0}
1160	rr1.Txt = []string{"a\"a", "\"", "b"}
1161	rr2, _ := NewRR(rr1.String())
1162	if rr1.String() != rr2.String() {
1163		// This is not an error, but keep this test.
1164		t.Errorf("these two TXT records should match:\n%s\n%s", rr1.String(), rr2.String())
1165	}
1166}
1167
1168func TestTxtLong(t *testing.T) {
1169	rr1 := new(TXT)
1170	rr1.Hdr = RR_Header{Name: ".", Rrtype: TypeTXT, Class: ClassINET, Ttl: 0}
1171	// Make a long txt record, this breaks when sending the packet,
1172	// but not earlier.
1173	rr1.Txt = []string{"start-"}
1174	for i := 0; i < 200; i++ {
1175		rr1.Txt[0] += "start-"
1176	}
1177	str := rr1.String()
1178	if len(str) < len(rr1.Txt[0]) {
1179		t.Error("string conversion should work")
1180	}
1181}
1182
1183// Basically, don't crash.
1184func TestMalformedPackets(t *testing.T) {
1185	var packets = []string{
1186		"0021641c0000000100000000000078787878787878787878787303636f6d0000100001",
1187	}
1188
1189	// com = 63 6f 6d
1190	for _, packet := range packets {
1191		data, _ := hex.DecodeString(packet)
1192		var msg Msg
1193		msg.Unpack(data)
1194	}
1195}
1196
1197type algorithm struct {
1198	name uint8
1199	bits int
1200}
1201
1202func TestNewPrivateKey(t *testing.T) {
1203	if testing.Short() {
1204		t.Skip("skipping test in short mode.")
1205	}
1206	algorithms := []algorithm{
1207		{ECDSAP256SHA256, 256},
1208		{ECDSAP384SHA384, 384},
1209		{RSASHA1, 1024},
1210		{RSASHA256, 2048},
1211		{DSA, 1024},
1212		{ED25519, 256},
1213	}
1214
1215	for _, algo := range algorithms {
1216		key := new(DNSKEY)
1217		key.Hdr.Rrtype = TypeDNSKEY
1218		key.Hdr.Name = "miek.nl."
1219		key.Hdr.Class = ClassINET
1220		key.Hdr.Ttl = 14400
1221		key.Flags = 256
1222		key.Protocol = 3
1223		key.Algorithm = algo.name
1224		privkey, err := key.Generate(algo.bits)
1225		if err != nil {
1226			t.Fatal(err)
1227		}
1228
1229		newPrivKey, err := key.NewPrivateKey(key.PrivateKeyString(privkey))
1230		if err != nil {
1231			t.Error(key.String())
1232			t.Error(key.PrivateKeyString(privkey))
1233			t.Fatal(err)
1234		}
1235
1236		switch newPrivKey := newPrivKey.(type) {
1237		case *rsa.PrivateKey:
1238			newPrivKey.Precompute()
1239		}
1240
1241		if !reflect.DeepEqual(privkey, newPrivKey) {
1242			t.Errorf("[%v] Private keys differ:\n%#v\n%#v", AlgorithmToString[algo.name], privkey, newPrivKey)
1243		}
1244	}
1245}
1246
1247// special input test
1248func TestNewRRSpecial(t *testing.T) {
1249	var (
1250		rr     RR
1251		err    error
1252		expect string
1253	)
1254
1255	rr, err = NewRR("; comment")
1256	expect = ""
1257	if err != nil {
1258		t.Errorf("unexpected err: %v", err)
1259	}
1260	if rr != nil {
1261		t.Errorf("unexpected result: [%s] != [%s]", rr, expect)
1262	}
1263
1264	rr, err = NewRR("")
1265	expect = ""
1266	if err != nil {
1267		t.Errorf("unexpected err: %v", err)
1268	}
1269	if rr != nil {
1270		t.Errorf("unexpected result: [%s] != [%s]", rr, expect)
1271	}
1272
1273	rr, err = NewRR("$ORIGIN foo.")
1274	expect = ""
1275	if err != nil {
1276		t.Errorf("unexpected err: %v", err)
1277	}
1278	if rr != nil {
1279		t.Errorf("unexpected result: [%s] != [%s]", rr, expect)
1280	}
1281
1282	rr, err = NewRR(" ")
1283	expect = ""
1284	if err != nil {
1285		t.Errorf("unexpected err: %v", err)
1286	}
1287	if rr != nil {
1288		t.Errorf("unexpected result: [%s] != [%s]", rr, expect)
1289	}
1290
1291	rr, err = NewRR("\n")
1292	expect = ""
1293	if err != nil {
1294		t.Errorf("unexpected err: %v", err)
1295	}
1296	if rr != nil {
1297		t.Errorf("unexpected result: [%s] != [%s]", rr, expect)
1298	}
1299
1300	rr, err = NewRR("foo. A 1.1.1.1\nbar. A 2.2.2.2")
1301	expect = "foo.\t3600\tIN\tA\t1.1.1.1"
1302	if err != nil {
1303		t.Errorf("unexpected err: %v", err)
1304	}
1305	if rr == nil || rr.String() != expect {
1306		t.Errorf("unexpected result: [%s] != [%s]", rr, expect)
1307	}
1308}
1309
1310func TestPrintfVerbsRdata(t *testing.T) {
1311	x, _ := NewRR("www.miek.nl. IN MX 20 mx.miek.nl.")
1312	if Field(x, 1) != "20" {
1313		t.Errorf("should be 20")
1314	}
1315	if Field(x, 2) != "mx.miek.nl." {
1316		t.Errorf("should be mx.miek.nl.")
1317	}
1318
1319	x, _ = NewRR("www.miek.nl. IN A 127.0.0.1")
1320	if Field(x, 1) != "127.0.0.1" {
1321		t.Errorf("should be 127.0.0.1")
1322	}
1323
1324	x, _ = NewRR("www.miek.nl. IN AAAA ::1")
1325	if Field(x, 1) != "::1" {
1326		t.Errorf("should be ::1")
1327	}
1328
1329	x, _ = NewRR("www.miek.nl. IN NSEC a.miek.nl. A NS SOA MX AAAA")
1330	if Field(x, 1) != "a.miek.nl." {
1331		t.Errorf("should be a.miek.nl.")
1332	}
1333	if Field(x, 2) != "A NS SOA MX AAAA" {
1334		t.Errorf("should be A NS SOA MX AAAA")
1335	}
1336
1337	x, _ = NewRR("www.miek.nl. IN TXT \"first\" \"second\"")
1338	if Field(x, 1) != "first second" {
1339		t.Errorf("should be first second")
1340	}
1341	if Field(x, 0) != "" {
1342		t.Errorf("should be empty")
1343	}
1344}
1345
1346func TestParseTokenOverflow(t *testing.T) {
1347	_, err := NewRR("_443._tcp.example.org. IN TLSA 0 0 0 308205e8308204d0a00302010202100411de8f53b462f6a5a861b712ec6b59300d06092a864886f70d01010b05003070310b300906035504061302555331153013060355040a130c446967694365727420496e6331193017060355040b13107777772e64696769636572742e636f6d312f302d06035504031326446967694365727420534841322048696768204173737572616e636520536572766572204341301e170d3134313130363030303030305a170d3135313131333132303030305a3081a5310b3009060355040613025553311330110603550408130a43616c69666f726e6961311430120603550407130b4c6f7320416e67656c6573313c303a060355040a1333496e7465726e657420436f72706f726174696f6e20666f722041737369676e6564204e616d657320616e64204e756d6265727331133011060355040b130a546563686e6f6c6f6779311830160603550403130f7777772e6578616d706c652e6f726730820122300d06092a864886f70d01010105000382010f003082010a02820101009e663f52a3d18cb67cdfed547408a4e47e4036538988da2798da3b6655f7240d693ed1cb3fe6d6ad3a9e657ff6efa86b83b0cad24e5d31ff2bf70ec3b78b213f1b4bf61bdc669cbbc07d67154128ca92a9b3cbb4213a836fb823ddd4d7cc04918314d25f06086fa9970ba17e357cca9b458c27eb71760ab95e3f9bc898ae89050ae4d09ba2f7e4259d9ff1e072a6971b18355a8b9e53670c3d5dbdbd283f93a764e71b3a4140ca0746090c08510e2e21078d7d07844bf9c03865b531a0bf2ee766bc401f6451c5a1e6f6fb5d5c1d6a97a0abe91ae8b02e89241e07353909ccd5b41c46de207c06801e08f20713603827f2ae3e68cf15ef881d7e0608f70742e30203010001a382024630820242301f0603551d230418301680145168ff90af0207753cccd9656462a212b859723b301d0603551d0e04160414b000a7f422e9b1ce216117c4c46e7164c8e60c553081810603551d11047a3078820f7777772e6578616d706c652e6f7267820b6578616d706c652e636f6d820b6578616d706c652e656475820b6578616d706c652e6e6574820b6578616d706c652e6f7267820f7777772e6578616d706c652e636f6d820f7777772e6578616d706c652e656475820f7777772e6578616d706c652e6e6574300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b0601050507030230750603551d1f046e306c3034a032a030862e687474703a2f2f63726c332e64696769636572742e636f6d2f736861322d68612d7365727665722d67332e63726c3034a032a030862e687474703a2f2f63726c342e64696769636572742e636f6d2f736861322d68612d7365727665722d67332e63726c30420603551d20043b3039303706096086480186fd6c0101302a302806082b06010505070201161c68747470733a2f2f7777772e64696769636572742e636f6d2f43505330818306082b0601050507010104773075302406082b060105050730018618687474703a2f2f6f6373702e64696769636572742e636f6d304d06082b060105050730028641687474703a2f2f636163657274732e64696769636572742e636f6d2f446967694365727453484132486967684173737572616e636553657276657243412e637274300c0603551d130101ff04023000300d06092a864886f70d01010b050003820101005eac2124dedb3978a86ff3608406acb542d3cb54cb83facd63aec88144d6a1bf15dbf1f215c4a73e241e582365cba9ea50dd306541653b3513af1a0756c1b2720e8d112b34fb67181efad9c4609bdc670fb025fa6e6d42188161b026cf3089a08369c2f3609fc84bcc3479140c1922ede430ca8dbac2b2a3cdacb305ba15dc7361c4c3a5e6daa99cb446cb221b28078a7a944efba70d96f31ac143d959bccd2fd50e30c325ea2624fb6b6dbe9344dbcf133bfbd5b4e892d635dbf31596451672c6b65ba5ac9b3cddea92b35dab1065cae3c8cb6bb450a62ea2f72ea7c6bdc7b65fa09b012392543734083c7687d243f8d0375304d99ccd2e148966a8637a6797")
1348	if err == nil {
1349		t.Fatalf("token overflow should return an error")
1350	}
1351}
1352
1353func TestParseTLSA(t *testing.T) {
1354	lt := []string{
1355		"_443._tcp.example.org.\t3600\tIN\tTLSA\t1 1 1 c22be239f483c08957bc106219cc2d3ac1a308dfbbdd0a365f17b9351234cf00",
1356		"_443._tcp.example.org.\t3600\tIN\tTLSA\t2 1 2 4e85f45179e9cd6e0e68e2eb5be2e85ec9b92d91c609caf3ef0315213e3f92ece92c38397a607214de95c7fadc0ad0f1c604a469a0387959745032c0d51492f3",
1357		"_443._tcp.example.org.\t3600\tIN\tTLSA\t3 0 2 69ec8d2277360b215d0cd956b0e2747108dff34b27d461a41c800629e38ee6c2d1230cc9e8e36711330adc6766e6ff7c5fbb37f106f248337c1a20ad682888d2",
1358	}
1359	for _, o := range lt {
1360		rr, err := NewRR(o)
1361		if err != nil {
1362			t.Error("failed to parse RR: ", err)
1363			continue
1364		}
1365		if rr.String() != o {
1366			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", o, o, rr.String())
1367		}
1368	}
1369}
1370
1371func TestParseSMIMEA(t *testing.T) {
1372	lt := map[string]string{
1373		"2e85e1db3e62be6ea._smimecert.example.com.\t3600\tIN\tSMIMEA\t1 1 2 bd80f334566928fc18f58df7e4928c1886f48f71ca3fd41cd9b1854aca7c2180aaacad2819612ed68e7bd3701cc39be7f2529b017c0bc6a53e8fb3f0c7d48070":   "2e85e1db3e62be6ea._smimecert.example.com.\t3600\tIN\tSMIMEA\t1 1 2 bd80f334566928fc18f58df7e4928c1886f48f71ca3fd41cd9b1854aca7c2180aaacad2819612ed68e7bd3701cc39be7f2529b017c0bc6a53e8fb3f0c7d48070",
1374		"2e85e1db3e62be6ea._smimecert.example.com.\t3600\tIN\tSMIMEA\t0 0 1 cdcf0fc66b182928c5217ddd42c826983f5a4b94160ee6c1c9be62d38199f710":                                                                   "2e85e1db3e62be6ea._smimecert.example.com.\t3600\tIN\tSMIMEA\t0 0 1 cdcf0fc66b182928c5217ddd42c826983f5a4b94160ee6c1c9be62d38199f710",
1375		"2e85e1db3e62be6ea._smimecert.example.com.\t3600\tIN\tSMIMEA\t3 0 2 499a1eda2af8828b552cdb9d80c3744a25872fddd73f3898d8e4afa3549595d2dd4340126e759566fe8c26b251fa0c887ba4869f011a65f7e79967c2eb729f5b":   "2e85e1db3e62be6ea._smimecert.example.com.\t3600\tIN\tSMIMEA\t3 0 2 499a1eda2af8828b552cdb9d80c3744a25872fddd73f3898d8e4afa3549595d2dd4340126e759566fe8c26b251fa0c887ba4869f011a65f7e79967c2eb729f5b",
1376		"2e85e1db3e62be6eb._smimecert.example.com.\t3600\tIN\tSMIMEA\t3 0 2 499a1eda2af8828b552cdb9d80c3744a25872fddd73f3898d8e4afa3549595d2dd4340126e759566fe8 c26b251fa0c887ba4869f01 1a65f7e79967c2eb729f5b": "2e85e1db3e62be6eb._smimecert.example.com.\t3600\tIN\tSMIMEA\t3 0 2 499a1eda2af8828b552cdb9d80c3744a25872fddd73f3898d8e4afa3549595d2dd4340126e759566fe8c26b251fa0c887ba4869f011a65f7e79967c2eb729f5b",
1377	}
1378	for i, o := range lt {
1379		rr, err := NewRR(i)
1380		if err != nil {
1381			t.Error("failed to parse RR: ", err)
1382			continue
1383		}
1384		if rr.String() != o {
1385			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", o, o, rr.String())
1386		}
1387	}
1388}
1389
1390func TestParseSSHFP(t *testing.T) {
1391	lt := []string{
1392		"test.example.org.\t300\tSSHFP\t1 2 (\n" +
1393			"\t\t\t\t\tBC6533CDC95A79078A39A56EA7635984ED655318ADA9\n" +
1394			"\t\t\t\t\tB6159E30723665DA95BB )",
1395		"test.example.org.\t300\tSSHFP\t1 2 ( BC6533CDC  95A79078A39A56EA7635984ED655318AD  A9B6159E3072366 5DA95BB )",
1396	}
1397	result := "test.example.org.\t300\tIN\tSSHFP\t1 2 BC6533CDC95A79078A39A56EA7635984ED655318ADA9B6159E30723665DA95BB"
1398	for _, o := range lt {
1399		rr, err := NewRR(o)
1400		if err != nil {
1401			t.Error("failed to parse RR: ", err)
1402			continue
1403		}
1404		if rr.String() != result {
1405			t.Errorf("`%s' should be equal to\n\n`%s', but is     \n`%s'", o, result, rr.String())
1406		}
1407	}
1408}
1409
1410func TestParseHINFO(t *testing.T) {
1411	dt := map[string]string{
1412		"example.net. HINFO A B": "example.net.	3600	IN	HINFO	\"A\" \"B\"",
1413		"example.net. HINFO \"A\" \"B\"": "example.net.	3600	IN	HINFO	\"A\" \"B\"",
1414		"example.net. HINFO A B C D E F": "example.net.	3600	IN	HINFO	\"A\" \"B C D E F\"",
1415		"example.net. HINFO AB": "example.net.	3600	IN	HINFO	\"AB\" \"\"",
1416		// "example.net. HINFO PC-Intel-700mhz \"Redhat Linux 7.1\"": "example.net.	3600	IN	HINFO	\"PC-Intel-700mhz\" \"Redhat Linux 7.1\"",
1417		// This one is recommended in Pro Bind book http://www.zytrax.com/books/dns/ch8/hinfo.html
1418		// but effectively, even Bind would replace it to correctly formed text when you AXFR
1419		// TODO: remove this set of comments or figure support for quoted/unquoted combinations in endingToTxtSlice function
1420	}
1421	for i, o := range dt {
1422		rr, err := NewRR(i)
1423		if err != nil {
1424			t.Error("failed to parse RR: ", err)
1425			continue
1426		}
1427		if rr.String() != o {
1428			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", i, o, rr.String())
1429		}
1430	}
1431}
1432
1433func TestParseCAA(t *testing.T) {
1434	lt := map[string]string{
1435		"example.net.	CAA	0 issue \"symantec.com\"": "example.net.\t3600\tIN\tCAA\t0 issue \"symantec.com\"",
1436		"example.net.	CAA	0 issuewild \"symantec.com; stuff\"": "example.net.\t3600\tIN\tCAA\t0 issuewild \"symantec.com; stuff\"",
1437		"example.net.	CAA	128 tbs \"critical\"": "example.net.\t3600\tIN\tCAA\t128 tbs \"critical\"",
1438		"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\"",
1439		"example.net.   TYPE257	0 issue \"symantec.com\"": "example.net.\t3600\tIN\tCAA\t0 issue \"symantec.com\"",
1440	}
1441	for i, o := range lt {
1442		rr, err := NewRR(i)
1443		if err != nil {
1444			t.Error("failed to parse RR: ", err)
1445			continue
1446		}
1447		if rr.String() != o {
1448			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", i, o, rr.String())
1449		}
1450	}
1451}
1452
1453func TestPackCAA(t *testing.T) {
1454	m := new(Msg)
1455	record := new(CAA)
1456	record.Hdr = RR_Header{Name: "example.com.", Rrtype: TypeCAA, Class: ClassINET, Ttl: 0}
1457	record.Tag = "issue"
1458	record.Value = "symantec.com"
1459	record.Flag = 1
1460
1461	m.Answer = append(m.Answer, record)
1462	bytes, err := m.Pack()
1463	if err != nil {
1464		t.Fatalf("failed to pack msg: %v", err)
1465	}
1466	if err := m.Unpack(bytes); err != nil {
1467		t.Fatalf("failed to unpack msg: %v", err)
1468	}
1469	if len(m.Answer) != 1 {
1470		t.Fatalf("incorrect number of answers unpacked")
1471	}
1472	rr := m.Answer[0].(*CAA)
1473	if rr.Tag != "issue" {
1474		t.Fatalf("invalid tag for unpacked answer")
1475	} else if rr.Value != "symantec.com" {
1476		t.Fatalf("invalid value for unpacked answer")
1477	} else if rr.Flag != 1 {
1478		t.Fatalf("invalid flag for unpacked answer")
1479	}
1480}
1481
1482func TestParseURI(t *testing.T) {
1483	lt := map[string]string{
1484		"_http._tcp. IN URI   10 1 \"http://www.example.com/path\"": "_http._tcp.\t3600\tIN\tURI\t10 1 \"http://www.example.com/path\"",
1485		"_http._tcp. IN URI   10 1 \"\"":                            "_http._tcp.\t3600\tIN\tURI\t10 1 \"\"",
1486	}
1487	for i, o := range lt {
1488		rr, err := NewRR(i)
1489		if err != nil {
1490			t.Error("failed to parse RR: ", err)
1491			continue
1492		}
1493		if rr.String() != o {
1494			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", i, o, rr.String())
1495		}
1496	}
1497}
1498
1499func TestParseAVC(t *testing.T) {
1500	avcs := map[string]string{
1501		`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"`,
1502	}
1503	for avc, o := range avcs {
1504		rr, err := NewRR(avc)
1505		if err != nil {
1506			t.Error("failed to parse RR: ", err)
1507			continue
1508		}
1509		if rr.String() != o {
1510			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", avc, o, rr.String())
1511		}
1512	}
1513}
1514
1515func TestParseCSYNC(t *testing.T) {
1516	syncs := map[string]string{
1517		`example.com. 3600 IN CSYNC 66 3 A NS AAAA`: `example.com.	3600	IN	CSYNC	66 3 A NS AAAA`,
1518	}
1519	for s, o := range syncs {
1520		rr, err := NewRR(s)
1521		if err != nil {
1522			t.Error("failed to parse RR: ", err)
1523			continue
1524		}
1525		if rr.String() != o {
1526			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", s, o, rr.String())
1527		}
1528	}
1529}
1530
1531func TestParseBadNAPTR(t *testing.T) {
1532	// Should look like: mplus.ims.vodafone.com.	3600	IN	NAPTR	10 100 "S" "SIP+D2U" "" _sip._udp.mplus.ims.vodafone.com.
1533	naptr := `mplus.ims.vodafone.com.	3600	IN	NAPTR	10 100 S SIP+D2U  _sip._udp.mplus.ims.vodafone.com.`
1534	_, err := NewRR(naptr) // parse fails, we should not have leaked a goroutine.
1535	if err == nil {
1536		t.Fatalf("parsing NAPTR should have failed: %s", naptr)
1537	}
1538	if err := goroutineLeaked(); err != nil {
1539		t.Errorf("leaked goroutines: %s", err)
1540	}
1541}
1542
1543func TestUnbalancedParens(t *testing.T) {
1544	sig := `example.com. 3600 IN RRSIG MX 15 2 3600 (
1545              1440021600 1438207200 3613 example.com. (
1546              oL9krJun7xfBOIWcGHi7mag5/hdZrKWw15jPGrHpjQeRAvTdszaPD+QLs3f
1547              x8A4M3e23mRZ9VrbpMngwcrqNAg== )`
1548	_, err := NewRR(sig)
1549	if err == nil {
1550		t.Fatalf("failed to detect extra opening brace")
1551	}
1552}
1553
1554func TestBad(t *testing.T) {
1555	tests := []string{
1556		`" TYPE257 9 1E12\x00\x105"`,
1557		`" TYPE256  9 5"`,
1558		`" TYPE257 0\"00000000000000400000000000000000000\x00\x10000000000000000000000000000000000 9 l\x16\x01\x005266"`,
1559	}
1560	for i := range tests {
1561		s, err := strconv.Unquote(tests[i])
1562		if err != nil {
1563			t.Fatalf("failed to unquote: %q: %s", tests[i], err)
1564		}
1565		if _, err = NewRR(s); err == nil {
1566			t.Errorf("correctly parsed %q", s)
1567		}
1568	}
1569}
1570