source sync 20190409
[platform/core/system/edge-orchestration.git] / vendor / github.com / miekg / dns / parse_test.go
1 package dns
2
3 import (
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
18 func 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
36 func 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
49 func 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
62 func 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
84 func 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
113 func 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
147 func 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
175 func 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
205 func 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)
234 func 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
315 func 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
342 func 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
363 func 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
380 func 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
396 func 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
428 func 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
450 func 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
499 func 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
520 func TestOmittedTTL(t *testing.T) {
521         zone := `
522 $ORIGIN example.com.
523 example.com. 42 IN SOA ns1.example.com. hostmaster.example.com. 1 86400 60 86400 3600 ; TTL=42 SOA
524 example.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
530 example.com. 88 MG 7 ; TTL=88 explicit TTL
531 example.com.    MR 8 ; TTL=1337 after first $TTL
532 $TTL 314
533              1 TXT 9 ; TTL=1 implied owner name explicit TTL
534 example.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
561 func 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
608 func TestHIP(t *testing.T) {
609         h := `www.example.com.      IN  HIP ( 2 200100107B1A74DF365639CC39F1D578
610                                 AwEAAbdxyhNuSutc5EMzxTs9LBPCIkOFH8cIvM4p
611 9+LrV4e19WzK00+CI6zBCQTdtWsuxKbWIy87UOoJTwkUs7lBu+Upr1gsNrut79ryra+bSRGQ
612 b1slImA8YVJyuIDsj7kwzG7jnERNqnWxZ48AWkskmdHaVDP4BcelrTI3rMXdXF5D
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
645 func 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
669 func 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
709 func TestEmpty(t *testing.T) {
710         for range ParseZone(strings.NewReader(""), "", "") {
711                 t.Errorf("should be empty")
712         }
713 }
714
715 func 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
741 func 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
776 func 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
788 func 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
815 func 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
835 func 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
852 func 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 := `
863 foo. IN A 10.0.0.1 ; this is comment 1
864 foo. IN A (
865         10.0.0.2 ; this is comment 2
866 )
867 ; this is comment 3
868 foo. IN A 10.0.0.3
869 foo. IN A ( 10.0.0.4 ); this is comment 4
870
871 foo. IN A 10.0.0.5
872 ; this is comment 5
873
874 foo. IN A 10.0.0.6
875
876 foo. IN DNSKEY 256 3 5 AwEAAb+8l ; this is comment 6
877 foo. IN NSEC miek.nl. TXT RRSIG NSEC; this is comment 7
878 foo. 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
891 func 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
990 func 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
1006 func 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
1023 func 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
1099 func 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
1114 func 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
1121 func 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
1148 func 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
1161 func 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
1172 func 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.
1188 func 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
1201 type algorithm struct {
1202         name uint8
1203         bits int
1204 }
1205
1206 func 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                 {DSA, 1024},
1216                 {ED25519, 256},
1217         }
1218
1219         for _, algo := range algorithms {
1220                 key := new(DNSKEY)
1221                 key.Hdr.Rrtype = TypeDNSKEY
1222                 key.Hdr.Name = "miek.nl."
1223                 key.Hdr.Class = ClassINET
1224                 key.Hdr.Ttl = 14400
1225                 key.Flags = 256
1226                 key.Protocol = 3
1227                 key.Algorithm = algo.name
1228                 privkey, err := key.Generate(algo.bits)
1229                 if err != nil {
1230                         t.Fatal(err)
1231                 }
1232
1233                 newPrivKey, err := key.NewPrivateKey(key.PrivateKeyString(privkey))
1234                 if err != nil {
1235                         t.Error(key.String())
1236                         t.Error(key.PrivateKeyString(privkey))
1237                         t.Fatal(err)
1238                 }
1239
1240                 switch newPrivKey := newPrivKey.(type) {
1241                 case *rsa.PrivateKey:
1242                         newPrivKey.Precompute()
1243                 }
1244
1245                 if !reflect.DeepEqual(privkey, newPrivKey) {
1246                         t.Errorf("[%v] Private keys differ:\n%#v\n%#v", AlgorithmToString[algo.name], privkey, newPrivKey)
1247                 }
1248         }
1249 }
1250
1251 // special input test
1252 func TestNewRRSpecial(t *testing.T) {
1253         var (
1254                 rr     RR
1255                 err    error
1256                 expect string
1257         )
1258
1259         rr, err = NewRR("; comment")
1260         expect = ""
1261         if err != nil {
1262                 t.Errorf("unexpected err: %v", err)
1263         }
1264         if rr != nil {
1265                 t.Errorf("unexpected result: [%s] != [%s]", rr, expect)
1266         }
1267
1268         rr, err = NewRR("")
1269         expect = ""
1270         if err != nil {
1271                 t.Errorf("unexpected err: %v", err)
1272         }
1273         if rr != nil {
1274                 t.Errorf("unexpected result: [%s] != [%s]", rr, expect)
1275         }
1276
1277         rr, err = NewRR("$ORIGIN foo.")
1278         expect = ""
1279         if err != nil {
1280                 t.Errorf("unexpected err: %v", err)
1281         }
1282         if rr != nil {
1283                 t.Errorf("unexpected result: [%s] != [%s]", rr, expect)
1284         }
1285
1286         rr, err = NewRR(" ")
1287         expect = ""
1288         if err != nil {
1289                 t.Errorf("unexpected err: %v", err)
1290         }
1291         if rr != nil {
1292                 t.Errorf("unexpected result: [%s] != [%s]", rr, expect)
1293         }
1294
1295         rr, err = NewRR("\n")
1296         expect = ""
1297         if err != nil {
1298                 t.Errorf("unexpected err: %v", err)
1299         }
1300         if rr != nil {
1301                 t.Errorf("unexpected result: [%s] != [%s]", rr, expect)
1302         }
1303
1304         rr, err = NewRR("foo. A 1.1.1.1\nbar. A 2.2.2.2")
1305         expect = "foo.\t3600\tIN\tA\t1.1.1.1"
1306         if err != nil {
1307                 t.Errorf("unexpected err: %v", err)
1308         }
1309         if rr == nil || rr.String() != expect {
1310                 t.Errorf("unexpected result: [%s] != [%s]", rr, expect)
1311         }
1312 }
1313
1314 func TestPrintfVerbsRdata(t *testing.T) {
1315         x, _ := NewRR("www.miek.nl. IN MX 20 mx.miek.nl.")
1316         if Field(x, 1) != "20" {
1317                 t.Errorf("should be 20")
1318         }
1319         if Field(x, 2) != "mx.miek.nl." {
1320                 t.Errorf("should be mx.miek.nl.")
1321         }
1322
1323         x, _ = NewRR("www.miek.nl. IN A 127.0.0.1")
1324         if Field(x, 1) != "127.0.0.1" {
1325                 t.Errorf("should be 127.0.0.1")
1326         }
1327
1328         x, _ = NewRR("www.miek.nl. IN AAAA ::1")
1329         if Field(x, 1) != "::1" {
1330                 t.Errorf("should be ::1")
1331         }
1332
1333         x, _ = NewRR("www.miek.nl. IN NSEC a.miek.nl. A NS SOA MX AAAA")
1334         if Field(x, 1) != "a.miek.nl." {
1335                 t.Errorf("should be a.miek.nl.")
1336         }
1337         if Field(x, 2) != "A NS SOA MX AAAA" {
1338                 t.Errorf("should be A NS SOA MX AAAA")
1339         }
1340
1341         x, _ = NewRR("www.miek.nl. IN TXT \"first\" \"second\"")
1342         if Field(x, 1) != "first second" {
1343                 t.Errorf("should be first second")
1344         }
1345         if Field(x, 0) != "" {
1346                 t.Errorf("should be empty")
1347         }
1348 }
1349
1350 func TestParseTokenOverflow(t *testing.T) {
1351         _, err := NewRR("_443._tcp.example.org. IN TLSA 0 0 0 308205e8308204d0a00302010202100411de8f53b462f6a5a861b712ec6b59300d06092a864886f70d01010b05003070310b300906035504061302555331153013060355040a130c446967694365727420496e6331193017060355040b13107777772e64696769636572742e636f6d312f302d06035504031326446967694365727420534841322048696768204173737572616e636520536572766572204341301e170d3134313130363030303030305a170d3135313131333132303030305a3081a5310b3009060355040613025553311330110603550408130a43616c69666f726e6961311430120603550407130b4c6f7320416e67656c6573313c303a060355040a1333496e7465726e657420436f72706f726174696f6e20666f722041737369676e6564204e616d657320616e64204e756d6265727331133011060355040b130a546563686e6f6c6f6779311830160603550403130f7777772e6578616d706c652e6f726730820122300d06092a864886f70d01010105000382010f003082010a02820101009e663f52a3d18cb67cdfed547408a4e47e4036538988da2798da3b6655f7240d693ed1cb3fe6d6ad3a9e657ff6efa86b83b0cad24e5d31ff2bf70ec3b78b213f1b4bf61bdc669cbbc07d67154128ca92a9b3cbb4213a836fb823ddd4d7cc04918314d25f06086fa9970ba17e357cca9b458c27eb71760ab95e3f9bc898ae89050ae4d09ba2f7e4259d9ff1e072a6971b18355a8b9e53670c3d5dbdbd283f93a764e71b3a4140ca0746090c08510e2e21078d7d07844bf9c03865b531a0bf2ee766bc401f6451c5a1e6f6fb5d5c1d6a97a0abe91ae8b02e89241e07353909ccd5b41c46de207c06801e08f20713603827f2ae3e68cf15ef881d7e0608f70742e30203010001a382024630820242301f0603551d230418301680145168ff90af0207753cccd9656462a212b859723b301d0603551d0e04160414b000a7f422e9b1ce216117c4c46e7164c8e60c553081810603551d11047a3078820f7777772e6578616d706c652e6f7267820b6578616d706c652e636f6d820b6578616d706c652e656475820b6578616d706c652e6e6574820b6578616d706c652e6f7267820f7777772e6578616d706c652e636f6d820f7777772e6578616d706c652e656475820f7777772e6578616d706c652e6e6574300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b0601050507030230750603551d1f046e306c3034a032a030862e687474703a2f2f63726c332e64696769636572742e636f6d2f736861322d68612d7365727665722d67332e63726c3034a032a030862e687474703a2f2f63726c342e64696769636572742e636f6d2f736861322d68612d7365727665722d67332e63726c30420603551d20043b3039303706096086480186fd6c0101302a302806082b06010505070201161c68747470733a2f2f7777772e64696769636572742e636f6d2f43505330818306082b0601050507010104773075302406082b060105050730018618687474703a2f2f6f6373702e64696769636572742e636f6d304d06082b060105050730028641687474703a2f2f636163657274732e64696769636572742e636f6d2f446967694365727453484132486967684173737572616e636553657276657243412e637274300c0603551d130101ff04023000300d06092a864886f70d01010b050003820101005eac2124dedb3978a86ff3608406acb542d3cb54cb83facd63aec88144d6a1bf15dbf1f215c4a73e241e582365cba9ea50dd306541653b3513af1a0756c1b2720e8d112b34fb67181efad9c4609bdc670fb025fa6e6d42188161b026cf3089a08369c2f3609fc84bcc3479140c1922ede430ca8dbac2b2a3cdacb305ba15dc7361c4c3a5e6daa99cb446cb221b28078a7a944efba70d96f31ac143d959bccd2fd50e30c325ea2624fb6b6dbe9344dbcf133bfbd5b4e892d635dbf31596451672c6b65ba5ac9b3cddea92b35dab1065cae3c8cb6bb450a62ea2f72ea7c6bdc7b65fa09b012392543734083c7687d243f8d0375304d99ccd2e148966a8637a6797")
1352         if err == nil {
1353                 t.Fatalf("token overflow should return an error")
1354         }
1355 }
1356
1357 func TestParseTLSA(t *testing.T) {
1358         lt := []string{
1359                 "_443._tcp.example.org.\t3600\tIN\tTLSA\t1 1 1 c22be239f483c08957bc106219cc2d3ac1a308dfbbdd0a365f17b9351234cf00",
1360                 "_443._tcp.example.org.\t3600\tIN\tTLSA\t2 1 2 4e85f45179e9cd6e0e68e2eb5be2e85ec9b92d91c609caf3ef0315213e3f92ece92c38397a607214de95c7fadc0ad0f1c604a469a0387959745032c0d51492f3",
1361                 "_443._tcp.example.org.\t3600\tIN\tTLSA\t3 0 2 69ec8d2277360b215d0cd956b0e2747108dff34b27d461a41c800629e38ee6c2d1230cc9e8e36711330adc6766e6ff7c5fbb37f106f248337c1a20ad682888d2",
1362         }
1363         for _, o := range lt {
1364                 rr, err := NewRR(o)
1365                 if err != nil {
1366                         t.Error("failed to parse RR: ", err)
1367                         continue
1368                 }
1369                 if rr.String() != o {
1370                         t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", o, o, rr.String())
1371                 }
1372         }
1373 }
1374
1375 func TestParseSMIMEA(t *testing.T) {
1376         lt := map[string]string{
1377                 "2e85e1db3e62be6ea._smimecert.example.com.\t3600\tIN\tSMIMEA\t1 1 2 bd80f334566928fc18f58df7e4928c1886f48f71ca3fd41cd9b1854aca7c2180aaacad2819612ed68e7bd3701cc39be7f2529b017c0bc6a53e8fb3f0c7d48070":   "2e85e1db3e62be6ea._smimecert.example.com.\t3600\tIN\tSMIMEA\t1 1 2 bd80f334566928fc18f58df7e4928c1886f48f71ca3fd41cd9b1854aca7c2180aaacad2819612ed68e7bd3701cc39be7f2529b017c0bc6a53e8fb3f0c7d48070",
1378                 "2e85e1db3e62be6ea._smimecert.example.com.\t3600\tIN\tSMIMEA\t0 0 1 cdcf0fc66b182928c5217ddd42c826983f5a4b94160ee6c1c9be62d38199f710":                                                                   "2e85e1db3e62be6ea._smimecert.example.com.\t3600\tIN\tSMIMEA\t0 0 1 cdcf0fc66b182928c5217ddd42c826983f5a4b94160ee6c1c9be62d38199f710",
1379                 "2e85e1db3e62be6ea._smimecert.example.com.\t3600\tIN\tSMIMEA\t3 0 2 499a1eda2af8828b552cdb9d80c3744a25872fddd73f3898d8e4afa3549595d2dd4340126e759566fe8c26b251fa0c887ba4869f011a65f7e79967c2eb729f5b":   "2e85e1db3e62be6ea._smimecert.example.com.\t3600\tIN\tSMIMEA\t3 0 2 499a1eda2af8828b552cdb9d80c3744a25872fddd73f3898d8e4afa3549595d2dd4340126e759566fe8c26b251fa0c887ba4869f011a65f7e79967c2eb729f5b",
1380                 "2e85e1db3e62be6eb._smimecert.example.com.\t3600\tIN\tSMIMEA\t3 0 2 499a1eda2af8828b552cdb9d80c3744a25872fddd73f3898d8e4afa3549595d2dd4340126e759566fe8 c26b251fa0c887ba4869f01 1a65f7e79967c2eb729f5b": "2e85e1db3e62be6eb._smimecert.example.com.\t3600\tIN\tSMIMEA\t3 0 2 499a1eda2af8828b552cdb9d80c3744a25872fddd73f3898d8e4afa3549595d2dd4340126e759566fe8c26b251fa0c887ba4869f011a65f7e79967c2eb729f5b",
1381         }
1382         for i, o := range lt {
1383                 rr, err := NewRR(i)
1384                 if err != nil {
1385                         t.Error("failed to parse RR: ", err)
1386                         continue
1387                 }
1388                 if rr.String() != o {
1389                         t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", o, o, rr.String())
1390                 }
1391         }
1392 }
1393
1394 func TestParseSSHFP(t *testing.T) {
1395         lt := []string{
1396                 "test.example.org.\t300\tSSHFP\t1 2 (\n" +
1397                         "\t\t\t\t\tBC6533CDC95A79078A39A56EA7635984ED655318ADA9\n" +
1398                         "\t\t\t\t\tB6159E30723665DA95BB )",
1399                 "test.example.org.\t300\tSSHFP\t1 2 ( BC6533CDC  95A79078A39A56EA7635984ED655318AD  A9B6159E3072366 5DA95BB )",
1400         }
1401         result := "test.example.org.\t300\tIN\tSSHFP\t1 2 BC6533CDC95A79078A39A56EA7635984ED655318ADA9B6159E30723665DA95BB"
1402         for _, o := range lt {
1403                 rr, err := NewRR(o)
1404                 if err != nil {
1405                         t.Error("failed to parse RR: ", err)
1406                         continue
1407                 }
1408                 if rr.String() != result {
1409                         t.Errorf("`%s' should be equal to\n\n`%s', but is     \n`%s'", o, result, rr.String())
1410                 }
1411         }
1412 }
1413
1414 func TestParseHINFO(t *testing.T) {
1415         dt := map[string]string{
1416                 "example.net. HINFO A B": "example.net. 3600    IN      HINFO   \"A\" \"B\"",
1417                 "example.net. HINFO \"A\" \"B\"": "example.net. 3600    IN      HINFO   \"A\" \"B\"",
1418                 "example.net. HINFO A B C D E F": "example.net. 3600    IN      HINFO   \"A\" \"B C D E F\"",
1419                 "example.net. HINFO AB": "example.net.  3600    IN      HINFO   \"AB\" \"\"",
1420                 // "example.net. HINFO PC-Intel-700mhz \"Redhat Linux 7.1\"": "example.net.     3600    IN      HINFO   \"PC-Intel-700mhz\" \"Redhat Linux 7.1\"",
1421                 // This one is recommended in Pro Bind book http://www.zytrax.com/books/dns/ch8/hinfo.html
1422                 // but effectively, even Bind would replace it to correctly formed text when you AXFR
1423                 // TODO: remove this set of comments or figure support for quoted/unquoted combinations in endingToTxtSlice function
1424         }
1425         for i, o := range dt {
1426                 rr, err := NewRR(i)
1427                 if err != nil {
1428                         t.Error("failed to parse RR: ", err)
1429                         continue
1430                 }
1431                 if rr.String() != o {
1432                         t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", i, o, rr.String())
1433                 }
1434         }
1435 }
1436
1437 func TestParseCAA(t *testing.T) {
1438         lt := map[string]string{
1439                 "example.net.   CAA     0 issue \"symantec.com\"": "example.net.\t3600\tIN\tCAA\t0 issue \"symantec.com\"",
1440                 "example.net.   CAA     0 issuewild \"symantec.com; stuff\"": "example.net.\t3600\tIN\tCAA\t0 issuewild \"symantec.com; stuff\"",
1441                 "example.net.   CAA     128 tbs \"critical\"": "example.net.\t3600\tIN\tCAA\t128 tbs \"critical\"",
1442                 "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\"",
1443                 "example.net.   TYPE257 0 issue \"symantec.com\"": "example.net.\t3600\tIN\tCAA\t0 issue \"symantec.com\"",
1444         }
1445         for i, o := range lt {
1446                 rr, err := NewRR(i)
1447                 if err != nil {
1448                         t.Error("failed to parse RR: ", err)
1449                         continue
1450                 }
1451                 if rr.String() != o {
1452                         t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", i, o, rr.String())
1453                 }
1454         }
1455 }
1456
1457 func TestPackCAA(t *testing.T) {
1458         m := new(Msg)
1459         record := new(CAA)
1460         record.Hdr = RR_Header{Name: "example.com.", Rrtype: TypeCAA, Class: ClassINET, Ttl: 0}
1461         record.Tag = "issue"
1462         record.Value = "symantec.com"
1463         record.Flag = 1
1464
1465         m.Answer = append(m.Answer, record)
1466         bytes, err := m.Pack()
1467         if err != nil {
1468                 t.Fatalf("failed to pack msg: %v", err)
1469         }
1470         if err := m.Unpack(bytes); err != nil {
1471                 t.Fatalf("failed to unpack msg: %v", err)
1472         }
1473         if len(m.Answer) != 1 {
1474                 t.Fatalf("incorrect number of answers unpacked")
1475         }
1476         rr := m.Answer[0].(*CAA)
1477         if rr.Tag != "issue" {
1478                 t.Fatalf("invalid tag for unpacked answer")
1479         } else if rr.Value != "symantec.com" {
1480                 t.Fatalf("invalid value for unpacked answer")
1481         } else if rr.Flag != 1 {
1482                 t.Fatalf("invalid flag for unpacked answer")
1483         }
1484 }
1485
1486 func TestParseURI(t *testing.T) {
1487         lt := map[string]string{
1488                 "_http._tcp. IN URI   10 1 \"http://www.example.com/path\"": "_http._tcp.\t3600\tIN\tURI\t10 1 \"http://www.example.com/path\"",
1489                 "_http._tcp. IN URI   10 1 \"\"":                            "_http._tcp.\t3600\tIN\tURI\t10 1 \"\"",
1490         }
1491         for i, o := range lt {
1492                 rr, err := NewRR(i)
1493                 if err != nil {
1494                         t.Error("failed to parse RR: ", err)
1495                         continue
1496                 }
1497                 if rr.String() != o {
1498                         t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", i, o, rr.String())
1499                 }
1500         }
1501 }
1502
1503 func TestParseAVC(t *testing.T) {
1504         avcs := map[string]string{
1505                 `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"`,
1506         }
1507         for avc, o := range avcs {
1508                 rr, err := NewRR(avc)
1509                 if err != nil {
1510                         t.Error("failed to parse RR: ", err)
1511                         continue
1512                 }
1513                 if rr.String() != o {
1514                         t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", avc, o, rr.String())
1515                 }
1516         }
1517 }
1518
1519 func TestParseCSYNC(t *testing.T) {
1520         syncs := map[string]string{
1521                 `example.com. 3600 IN CSYNC 66 3 A NS AAAA`: `example.com.      3600    IN      CSYNC   66 3 A NS AAAA`,
1522         }
1523         for s, o := range syncs {
1524                 rr, err := NewRR(s)
1525                 if err != nil {
1526                         t.Error("failed to parse RR: ", err)
1527                         continue
1528                 }
1529                 if rr.String() != o {
1530                         t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", s, o, rr.String())
1531                 }
1532         }
1533 }
1534
1535 func TestParseBadNAPTR(t *testing.T) {
1536         // Should look like: mplus.ims.vodafone.com.    3600    IN      NAPTR   10 100 "S" "SIP+D2U" "" _sip._udp.mplus.ims.vodafone.com.
1537         naptr := `mplus.ims.vodafone.com.       3600    IN      NAPTR   10 100 S SIP+D2U  _sip._udp.mplus.ims.vodafone.com.`
1538         _, err := NewRR(naptr) // parse fails, we should not have leaked a goroutine.
1539         if err == nil {
1540                 t.Fatalf("parsing NAPTR should have failed: %s", naptr)
1541         }
1542         if err := goroutineLeaked(); err != nil {
1543                 t.Errorf("leaked goroutines: %s", err)
1544         }
1545 }
1546
1547 func TestUnbalancedParens(t *testing.T) {
1548         sig := `example.com. 3600 IN RRSIG MX 15 2 3600 (
1549               1440021600 1438207200 3613 example.com. (
1550               oL9krJun7xfBOIWcGHi7mag5/hdZrKWw15jPGrHpjQeRAvTdszaPD+QLs3f
1551               x8A4M3e23mRZ9VrbpMngwcrqNAg== )`
1552         _, err := NewRR(sig)
1553         if err == nil {
1554                 t.Fatalf("failed to detect extra opening brace")
1555         }
1556 }
1557
1558 func TestBad(t *testing.T) {
1559         tests := []string{
1560                 `" TYPE257 9 1E12\x00\x105"`,
1561                 `" TYPE256  9 5"`,
1562                 `" TYPE257 0\"00000000000000400000000000000000000\x00\x10000000000000000000000000000000000 9 l\x16\x01\x005266"`,
1563         }
1564         for i := range tests {
1565                 s, err := strconv.Unquote(tests[i])
1566                 if err != nil {
1567                         t.Fatalf("failed to unquote: %q: %s", tests[i], err)
1568                 }
1569                 if _, err = NewRR(s); err == nil {
1570                         t.Errorf("correctly parsed %q", s)
1571                 }
1572         }
1573 }
1574
1575 func TestNULLRecord(t *testing.T) {
1576         // packet captured from iodine
1577         packet := `8116840000010001000000000569627a6c700474657374046d69656b026e6c00000a0001c00c000a0001000000000005497f000001`
1578         data, _ := hex.DecodeString(packet)
1579         msg := new(Msg)
1580         err := msg.Unpack(data)
1581         if err != nil {
1582                 t.Fatalf("Failed to unpack NULL record")
1583         }
1584         if _, ok := msg.Answer[0].(*NULL); !ok {
1585                 t.Fatalf("Expected packet to contain NULL record")
1586         }
1587 }