1// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package net
6
7import (
8	"strings"
9	"testing"
10)
11
12type dnsNameTest struct {
13	name   string
14	result bool
15}
16
17var dnsNameTests = []dnsNameTest{
18	// RFC 2181, section 11.
19	{"_xmpp-server._tcp.google.com", true},
20	{"foo.com", true},
21	{"1foo.com", true},
22	{"26.0.0.73.com", true},
23	{"10-0-0-1", true},
24	{"fo-o.com", true},
25	{"fo1o.com", true},
26	{"foo1.com", true},
27	{"a.b..com", false},
28	{"a.b-.com", false},
29	{"a.b.com-", false},
30	{"a.b..", false},
31	{"b.com.", true},
32}
33
34func emitDNSNameTest(ch chan<- dnsNameTest) {
35	defer close(ch)
36	var char63 = ""
37	for i := 0; i < 63; i++ {
38		char63 += "a"
39	}
40	char64 := char63 + "a"
41	longDomain := strings.Repeat(char63+".", 5) + "example"
42
43	for _, tc := range dnsNameTests {
44		ch <- tc
45	}
46
47	ch <- dnsNameTest{char63 + ".com", true}
48	ch <- dnsNameTest{char64 + ".com", false}
49
50	// Remember: wire format is two octets longer than presentation
51	// (length octets for the first and [root] last labels).
52	// 253 is fine:
53	ch <- dnsNameTest{longDomain[len(longDomain)-253:], true}
54	// A terminal dot doesn't contribute to length:
55	ch <- dnsNameTest{longDomain[len(longDomain)-253:] + ".", true}
56	// 254 is bad:
57	ch <- dnsNameTest{longDomain[len(longDomain)-254:], false}
58}
59
60func TestDNSName(t *testing.T) {
61	ch := make(chan dnsNameTest)
62	go emitDNSNameTest(ch)
63	for tc := range ch {
64		if isDomainName(tc.name) != tc.result {
65			t.Errorf("isDomainName(%q) = %v; want %v", tc.name, !tc.result, tc.result)
66		}
67	}
68}
69
70func BenchmarkDNSName(b *testing.B) {
71	testHookUninstaller.Do(uninstallTestHooks)
72
73	benchmarks := append(dnsNameTests, []dnsNameTest{
74		{strings.Repeat("a", 63), true},
75		{strings.Repeat("a", 64), false},
76	}...)
77	for n := 0; n < b.N; n++ {
78		for _, tc := range benchmarks {
79			if isDomainName(tc.name) != tc.result {
80				b.Errorf("isDomainName(%q) = %v; want %v", tc.name, !tc.result, tc.result)
81			}
82		}
83	}
84}
85