Source file
src/net/lookup_test.go
1
2
3
4
5 package net
6
7 import (
8 "context"
9 "errors"
10 "fmt"
11 "internal/testenv"
12 "net/netip"
13 "reflect"
14 "runtime"
15 "slices"
16 "strings"
17 "sync"
18 "sync/atomic"
19 "testing"
20 "time"
21 )
22
23 var goResolver = Resolver{PreferGo: true}
24
25 func hasSuffixFold(s, suffix string) bool {
26 return strings.HasSuffix(strings.ToLower(s), strings.ToLower(suffix))
27 }
28
29 func lookupLocalhost(ctx context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) {
30 switch host {
31 case "localhost":
32 return []IPAddr{
33 {IP: IPv4(127, 0, 0, 1)},
34 {IP: IPv6loopback},
35 }, nil
36 default:
37 return fn(ctx, network, host)
38 }
39 }
40
41
42
43
44
45
46
47
48 var lookupGoogleSRVTests = []struct {
49 service, proto, name string
50 cname, target string
51 }{
52 {
53 "ldap", "tcp", "google.com",
54 "google.com.", "google.com.",
55 },
56 {
57 "ldap", "tcp", "google.com.",
58 "google.com.", "google.com.",
59 },
60
61
62 {
63 "", "", "_ldap._tcp.google.com",
64 "google.com.", "google.com.",
65 },
66 {
67 "", "", "_ldap._tcp.google.com.",
68 "google.com.", "google.com.",
69 },
70 }
71
72 var backoffDuration = [...]time.Duration{time.Second, 5 * time.Second, 30 * time.Second}
73
74 func TestLookupGoogleSRV(t *testing.T) {
75 t.Parallel()
76 mustHaveExternalNetwork(t)
77
78 if runtime.GOOS == "ios" {
79 t.Skip("no resolv.conf on iOS")
80 }
81
82 if !supportsIPv4() || !*testIPv4 {
83 t.Skip("IPv4 is required")
84 }
85
86 attempts := 0
87 for i := 0; i < len(lookupGoogleSRVTests); i++ {
88 tt := lookupGoogleSRVTests[i]
89 cname, srvs, err := LookupSRV(tt.service, tt.proto, tt.name)
90 if err != nil {
91 testenv.SkipFlakyNet(t)
92 if attempts < len(backoffDuration) {
93 dur := backoffDuration[attempts]
94 t.Logf("backoff %v after failure %v\n", dur, err)
95 time.Sleep(dur)
96 attempts++
97 i--
98 continue
99 }
100 t.Fatal(err)
101 }
102 if len(srvs) == 0 {
103 t.Error("got no record")
104 }
105 if !hasSuffixFold(cname, tt.cname) {
106 t.Errorf("got %s; want %s", cname, tt.cname)
107 }
108 for _, srv := range srvs {
109 if !hasSuffixFold(srv.Target, tt.target) {
110 t.Errorf("got %v; want a record containing %s", srv, tt.target)
111 }
112 }
113 }
114 }
115
116 var lookupGmailMXTests = []struct {
117 name, host string
118 }{
119 {"gmail.com", "google.com."},
120 {"gmail.com.", "google.com."},
121 }
122
123 func TestLookupGmailMX(t *testing.T) {
124 t.Parallel()
125 mustHaveExternalNetwork(t)
126
127 if runtime.GOOS == "ios" {
128 t.Skip("no resolv.conf on iOS")
129 }
130
131 if !supportsIPv4() || !*testIPv4 {
132 t.Skip("IPv4 is required")
133 }
134
135 attempts := 0
136 for i := 0; i < len(lookupGmailMXTests); i++ {
137 tt := lookupGmailMXTests[i]
138 mxs, err := LookupMX(tt.name)
139 if err != nil {
140 testenv.SkipFlakyNet(t)
141 if attempts < len(backoffDuration) {
142 dur := backoffDuration[attempts]
143 t.Logf("backoff %v after failure %v\n", dur, err)
144 time.Sleep(dur)
145 attempts++
146 i--
147 continue
148 }
149 t.Fatal(err)
150 }
151 if len(mxs) == 0 {
152 t.Error("got no record")
153 }
154 for _, mx := range mxs {
155 if !hasSuffixFold(mx.Host, tt.host) {
156 t.Errorf("got %v; want a record containing %s", mx, tt.host)
157 }
158 }
159 }
160 }
161
162 var lookupGmailNSTests = []struct {
163 name, host string
164 }{
165 {"gmail.com", "google.com."},
166 {"gmail.com.", "google.com."},
167 }
168
169 func TestLookupGmailNS(t *testing.T) {
170 t.Parallel()
171 mustHaveExternalNetwork(t)
172
173 if runtime.GOOS == "ios" {
174 t.Skip("no resolv.conf on iOS")
175 }
176
177 if !supportsIPv4() || !*testIPv4 {
178 t.Skip("IPv4 is required")
179 }
180
181 attempts := 0
182 for i := 0; i < len(lookupGmailNSTests); i++ {
183 tt := lookupGmailNSTests[i]
184 nss, err := LookupNS(tt.name)
185 if err != nil {
186 testenv.SkipFlakyNet(t)
187 if attempts < len(backoffDuration) {
188 dur := backoffDuration[attempts]
189 t.Logf("backoff %v after failure %v\n", dur, err)
190 time.Sleep(dur)
191 attempts++
192 i--
193 continue
194 }
195 t.Fatal(err)
196 }
197 if len(nss) == 0 {
198 t.Error("got no record")
199 }
200 for _, ns := range nss {
201 if !hasSuffixFold(ns.Host, tt.host) {
202 t.Errorf("got %v; want a record containing %s", ns, tt.host)
203 }
204 }
205 }
206 }
207
208 var lookupGmailTXTTests = []struct {
209 name, txt, host string
210 }{
211 {"gmail.com", "spf", "google.com"},
212 {"gmail.com.", "spf", "google.com"},
213 }
214
215 func TestLookupGmailTXT(t *testing.T) {
216 if runtime.GOOS == "plan9" {
217 t.Skip("skipping on plan9; see https://golang.org/issue/29722")
218 }
219 t.Parallel()
220 mustHaveExternalNetwork(t)
221
222 if runtime.GOOS == "ios" {
223 t.Skip("no resolv.conf on iOS")
224 }
225
226 if !supportsIPv4() || !*testIPv4 {
227 t.Skip("IPv4 is required")
228 }
229
230 attempts := 0
231 for i := 0; i < len(lookupGmailTXTTests); i++ {
232 tt := lookupGmailTXTTests[i]
233 txts, err := LookupTXT(tt.name)
234 if err != nil {
235 testenv.SkipFlakyNet(t)
236 if attempts < len(backoffDuration) {
237 dur := backoffDuration[attempts]
238 t.Logf("backoff %v after failure %v\n", dur, err)
239 time.Sleep(dur)
240 attempts++
241 i--
242 continue
243 }
244 t.Fatal(err)
245 }
246 if len(txts) == 0 {
247 t.Error("got no record")
248 }
249
250 if !slices.ContainsFunc(txts, func(txt string) bool {
251 return strings.Contains(txt, tt.txt) && (strings.HasSuffix(txt, tt.host) || strings.HasSuffix(txt, tt.host+"."))
252 }) {
253 t.Errorf("got %v; want a record containing %s, %s", txts, tt.txt, tt.host)
254 }
255 }
256 }
257
258 var lookupGooglePublicDNSAddrTests = []string{
259 "8.8.8.8",
260 "8.8.4.4",
261 "2001:4860:4860::8888",
262 "2001:4860:4860::8844",
263 }
264
265 func TestLookupGooglePublicDNSAddr(t *testing.T) {
266 mustHaveExternalNetwork(t)
267
268 if !supportsIPv4() || !supportsIPv6() || !*testIPv4 || !*testIPv6 {
269 t.Skip("both IPv4 and IPv6 are required")
270 }
271
272 defer dnsWaitGroup.Wait()
273
274 for _, ip := range lookupGooglePublicDNSAddrTests {
275 names, err := LookupAddr(ip)
276 if err != nil {
277 t.Fatal(err)
278 }
279 if len(names) == 0 {
280 t.Error("got no record")
281 }
282 for _, name := range names {
283 if !hasSuffixFold(name, ".google.com.") && !hasSuffixFold(name, ".google.") {
284 t.Errorf("got %q; want a record ending in .google.com. or .google.", name)
285 }
286 }
287 }
288 }
289
290 func TestLookupIPv6LinkLocalAddr(t *testing.T) {
291 if !supportsIPv6() || !*testIPv6 {
292 t.Skip("IPv6 is required")
293 }
294
295 defer dnsWaitGroup.Wait()
296
297 addrs, err := LookupHost("localhost")
298 if err != nil {
299 t.Fatal(err)
300 }
301 if !slices.Contains(addrs, "fe80::1%lo0") {
302 t.Skipf("not supported on %s", runtime.GOOS)
303 }
304 if _, err := LookupAddr("fe80::1%lo0"); err != nil {
305 t.Error(err)
306 }
307 }
308
309 func TestLookupIPv6LinkLocalAddrWithZone(t *testing.T) {
310 if !supportsIPv6() || !*testIPv6 {
311 t.Skip("IPv6 is required")
312 }
313
314 ipaddrs, err := DefaultResolver.LookupIPAddr(context.Background(), "fe80::1%lo0")
315 if err != nil {
316 t.Error(err)
317 }
318 for _, addr := range ipaddrs {
319 if e, a := "lo0", addr.Zone; e != a {
320 t.Errorf("wrong zone: want %q, got %q", e, a)
321 }
322 }
323
324 addrs, err := DefaultResolver.LookupHost(context.Background(), "fe80::1%lo0")
325 if err != nil {
326 t.Error(err)
327 }
328 for _, addr := range addrs {
329 if e, a := "fe80::1%lo0", addr; e != a {
330 t.Errorf("wrong host: want %q got %q", e, a)
331 }
332 }
333 }
334
335 func TestLookupNetIPPreservesZone(t *testing.T) {
336 origTestHookLookupIP := testHookLookupIP
337 t.Cleanup(func() {
338 testHookLookupIP = origTestHookLookupIP
339 })
340 defer dnsWaitGroup.Wait()
341
342 const name = "desktop.local"
343 want := netip.MustParseAddr("fe80::1%lo0")
344 testHookLookupIP = func(
345 ctx context.Context,
346 fn func(context.Context, string, string) ([]IPAddr, error),
347 network string,
348 host string,
349 ) ([]IPAddr, error) {
350 if host == name {
351 return []IPAddr{
352 {
353 IP: want.AsSlice(),
354 Zone: want.Zone(),
355 },
356 }, nil
357 }
358 return nil, newDNSError(errNoSuchHost, host, "")
359 }
360
361 ips, err := DefaultResolver.LookupNetIP(t.Context(), "ip", name)
362 if err != nil {
363 t.Fatalf("DefaultResolver.LookupNetIP() failed: %v", err)
364 }
365 if len(ips) == 0 {
366 t.Fatal("DefaultResolver.LookupNetIP() returned no IPs")
367 }
368 if ips[0] != want {
369 t.Errorf("DefaultResolver.LookupNetIP() = %v, want %v", ips[0], want)
370 }
371 }
372
373 var lookupCNAMETests = []struct {
374 name, cname string
375 }{
376 {"www.golang.org", "golang.org."},
377 {"www.golang.org.", "golang.org."},
378 {"www.google.com", "google.com."},
379 {"google.com", "google.com."},
380 {"cname-to-txt.go4.org", "test-txt-record.go4.org."},
381 }
382
383 func TestLookupCNAME(t *testing.T) {
384 mustHaveExternalNetwork(t)
385 testenv.SkipFlakyNet(t)
386
387 if !supportsIPv4() || !*testIPv4 {
388 t.Skip("IPv4 is required")
389 }
390
391 defer dnsWaitGroup.Wait()
392
393 attempts := 0
394 for i := 0; i < len(lookupCNAMETests); i++ {
395 tt := lookupCNAMETests[i]
396 cname, err := LookupCNAME(tt.name)
397 if err != nil {
398 testenv.SkipFlakyNet(t)
399 if attempts < len(backoffDuration) {
400 dur := backoffDuration[attempts]
401 t.Logf("backoff %v after failure %v\n", dur, err)
402 time.Sleep(dur)
403 attempts++
404 i--
405 continue
406 }
407 t.Fatal(err)
408 }
409 if !hasSuffixFold(cname, tt.cname) {
410 t.Errorf("got %s; want a record containing %s", cname, tt.cname)
411 }
412 }
413 }
414
415 var lookupGoogleHostTests = []struct {
416 name string
417 }{
418 {"google.com"},
419 {"google.com."},
420 }
421
422 func TestLookupGoogleHost(t *testing.T) {
423 mustHaveExternalNetwork(t)
424 testenv.SkipFlakyNet(t)
425
426 if !supportsIPv4() || !*testIPv4 {
427 t.Skip("IPv4 is required")
428 }
429
430 defer dnsWaitGroup.Wait()
431
432 for _, tt := range lookupGoogleHostTests {
433 addrs, err := LookupHost(tt.name)
434 if err != nil {
435 t.Fatal(err)
436 }
437 if len(addrs) == 0 {
438 t.Error("got no record")
439 }
440 for _, addr := range addrs {
441 if ParseIP(addr) == nil {
442 t.Errorf("got %q; want a literal IP address", addr)
443 }
444 }
445 }
446 }
447
448 func TestLookupLongTXT(t *testing.T) {
449 testenv.SkipFlaky(t, 22857)
450 mustHaveExternalNetwork(t)
451
452 defer dnsWaitGroup.Wait()
453
454 txts, err := LookupTXT("golang.rsc.io")
455 if err != nil {
456 t.Fatal(err)
457 }
458 slices.Sort(txts)
459 want := []string{
460 strings.Repeat("abcdefghijklmnopqrstuvwxyABCDEFGHJIKLMNOPQRSTUVWXY", 10),
461 "gophers rule",
462 }
463 if !slices.Equal(txts, want) {
464 t.Fatalf("LookupTXT golang.rsc.io incorrect\nhave %q\nwant %q", txts, want)
465 }
466 }
467
468 var lookupGoogleIPTests = []struct {
469 name string
470 }{
471 {"google.com"},
472 {"google.com."},
473 }
474
475 func TestLookupGoogleIP(t *testing.T) {
476 mustHaveExternalNetwork(t)
477 testenv.SkipFlakyNet(t)
478
479 if !supportsIPv4() || !*testIPv4 {
480 t.Skip("IPv4 is required")
481 }
482
483 defer dnsWaitGroup.Wait()
484
485 for _, tt := range lookupGoogleIPTests {
486 ips, err := LookupIP(tt.name)
487 if err != nil {
488 t.Fatal(err)
489 }
490 if len(ips) == 0 {
491 t.Error("got no record")
492 }
493 for _, ip := range ips {
494 if ip.To4() == nil && ip.To16() == nil {
495 t.Errorf("got %v; want an IP address", ip)
496 }
497 }
498 }
499 }
500
501 var revAddrTests = []struct {
502 Addr string
503 Reverse string
504 ErrPrefix string
505 }{
506 {"1.2.3.4", "4.3.2.1.in-addr.arpa.", ""},
507 {"245.110.36.114", "114.36.110.245.in-addr.arpa.", ""},
508 {"::ffff:12.34.56.78", "78.56.34.12.in-addr.arpa.", ""},
509 {"::1", "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa.", ""},
510 {"1::", "0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.0.0.0.ip6.arpa.", ""},
511 {"1234:567::89a:bcde", "e.d.c.b.a.9.8.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.7.6.5.0.4.3.2.1.ip6.arpa.", ""},
512 {"1234:567:fefe:bcbc:adad:9e4a:89a:bcde", "e.d.c.b.a.9.8.0.a.4.e.9.d.a.d.a.c.b.c.b.e.f.e.f.7.6.5.0.4.3.2.1.ip6.arpa.", ""},
513 {"1.2.3", "", "unrecognized address"},
514 {"1.2.3.4.5", "", "unrecognized address"},
515 {"1234:567:bcbca::89a:bcde", "", "unrecognized address"},
516 {"1234:567::bcbc:adad::89a:bcde", "", "unrecognized address"},
517 }
518
519 func TestReverseAddress(t *testing.T) {
520 defer dnsWaitGroup.Wait()
521 for i, tt := range revAddrTests {
522 a, err := reverseaddr(tt.Addr)
523 if len(tt.ErrPrefix) > 0 && err == nil {
524 t.Errorf("#%d: expected %q, got <nil> (error)", i, tt.ErrPrefix)
525 continue
526 }
527 if len(tt.ErrPrefix) == 0 && err != nil {
528 t.Errorf("#%d: expected <nil>, got %q (error)", i, err)
529 }
530 if err != nil && err.(*DNSError).Err != tt.ErrPrefix {
531 t.Errorf("#%d: expected %q, got %q (mismatched error)", i, tt.ErrPrefix, err.(*DNSError).Err)
532 }
533 if a != tt.Reverse {
534 t.Errorf("#%d: expected %q, got %q (reverse address)", i, tt.Reverse, a)
535 }
536 }
537 }
538
539 func TestDNSFlood(t *testing.T) {
540 if !*testDNSFlood {
541 t.Skip("test disabled; use -dnsflood to enable")
542 }
543
544 defer dnsWaitGroup.Wait()
545
546 var N = 5000
547 if runtime.GOOS == "darwin" || runtime.GOOS == "ios" {
548
549
550
551
552
553
554
555 N = 500
556 }
557
558 const timeout = 3 * time.Second
559 ctxHalfTimeout, cancel := context.WithTimeout(context.Background(), timeout/2)
560 defer cancel()
561 ctxTimeout, cancel := context.WithTimeout(context.Background(), timeout)
562 defer cancel()
563
564 c := make(chan error, 2*N)
565 for i := 0; i < N; i++ {
566 name := fmt.Sprintf("%d.net-test.golang.org", i)
567 go func() {
568 _, err := DefaultResolver.LookupIPAddr(ctxHalfTimeout, name)
569 c <- err
570 }()
571 go func() {
572 _, err := DefaultResolver.LookupIPAddr(ctxTimeout, name)
573 c <- err
574 }()
575 }
576 qstats := struct {
577 succeeded, failed int
578 timeout, temporary, other int
579 unknown int
580 }{}
581 deadline := time.After(timeout + time.Second)
582 for i := 0; i < 2*N; i++ {
583 select {
584 case <-deadline:
585 t.Fatal("deadline exceeded")
586 case err := <-c:
587 switch err := err.(type) {
588 case nil:
589 qstats.succeeded++
590 case Error:
591 qstats.failed++
592 if err.Timeout() {
593 qstats.timeout++
594 }
595 if err.Temporary() {
596 qstats.temporary++
597 }
598 if !err.Timeout() && !err.Temporary() {
599 qstats.other++
600 }
601 default:
602 qstats.failed++
603 qstats.unknown++
604 }
605 }
606 }
607
608
609
610
611
612
613
614
615 t.Logf("%v succeeded, %v failed (%v timeout, %v temporary, %v other, %v unknown)", qstats.succeeded, qstats.failed, qstats.timeout, qstats.temporary, qstats.other, qstats.unknown)
616 }
617
618 func TestLookupDotsWithLocalSource(t *testing.T) {
619 if !supportsIPv4() || !*testIPv4 {
620 t.Skip("IPv4 is required")
621 }
622
623 mustHaveExternalNetwork(t)
624
625 defer dnsWaitGroup.Wait()
626
627 for i, fn := range []func() func(){forceGoDNS, forceCgoDNS} {
628 fixup := fn()
629 if fixup == nil {
630 continue
631 }
632 names, err := LookupAddr("127.0.0.1")
633 fixup()
634 if err != nil {
635 t.Logf("#%d: %v", i, err)
636 continue
637 }
638 mode := "netgo"
639 if i == 1 {
640 mode = "netcgo"
641 }
642 loop:
643 for i, name := range names {
644 if strings.Index(name, ".") == len(name)-1 {
645 for j := range names {
646 if j == i {
647 continue
648 }
649 if names[j] == name[:len(name)-1] {
650
651
652 continue loop
653 }
654 }
655 t.Errorf("%s: got %s; want %s", mode, name, name[:len(name)-1])
656 } else if strings.Contains(name, ".") && !strings.HasSuffix(name, ".") {
657 t.Errorf("%s: got %s; want name ending with trailing dot", mode, name)
658 }
659 }
660 }
661 }
662
663 func TestLookupDotsWithRemoteSource(t *testing.T) {
664 if runtime.GOOS == "darwin" || runtime.GOOS == "ios" {
665 testenv.SkipFlaky(t, 27992)
666 }
667 mustHaveExternalNetwork(t)
668 testenv.SkipFlakyNet(t)
669
670 if !supportsIPv4() || !*testIPv4 {
671 t.Skip("IPv4 is required")
672 }
673
674 if runtime.GOOS == "ios" {
675 t.Skip("no resolv.conf on iOS")
676 }
677
678 defer dnsWaitGroup.Wait()
679
680 if fixup := forceGoDNS(); fixup != nil {
681 testDots(t, "go")
682 fixup()
683 }
684 if fixup := forceCgoDNS(); fixup != nil {
685 testDots(t, "cgo")
686 fixup()
687 }
688 }
689
690 func testDots(t *testing.T, mode string) {
691 names, err := LookupAddr("8.8.8.8")
692 if err != nil {
693 t.Errorf("LookupAddr(8.8.8.8): %v (mode=%v)", err, mode)
694 } else {
695 for _, name := range names {
696 if !hasSuffixFold(name, ".google.com.") && !hasSuffixFold(name, ".google.") {
697 t.Errorf("LookupAddr(8.8.8.8) = %v, want names ending in .google.com or .google with trailing dot (mode=%v)", names, mode)
698 break
699 }
700 }
701 }
702
703 cname, err := LookupCNAME("www.mit.edu")
704 if err != nil {
705 t.Errorf("LookupCNAME(www.mit.edu, mode=%v): %v", mode, err)
706 } else if !strings.HasSuffix(cname, ".") {
707 t.Errorf("LookupCNAME(www.mit.edu) = %v, want cname ending in . with trailing dot (mode=%v)", cname, mode)
708 }
709
710 mxs, err := LookupMX("google.com")
711 if err != nil {
712 t.Errorf("LookupMX(google.com): %v (mode=%v)", err, mode)
713 } else {
714 for _, mx := range mxs {
715 if !hasSuffixFold(mx.Host, ".google.com.") {
716 t.Errorf("LookupMX(google.com) = %v, want names ending in .google.com. with trailing dot (mode=%v)", mxString(mxs), mode)
717 break
718 }
719 }
720 }
721
722 nss, err := LookupNS("google.com")
723 if err != nil {
724 t.Errorf("LookupNS(google.com): %v (mode=%v)", err, mode)
725 } else {
726 for _, ns := range nss {
727 if !hasSuffixFold(ns.Host, ".google.com.") {
728 t.Errorf("LookupNS(google.com) = %v, want names ending in .google.com. with trailing dot (mode=%v)", nsString(nss), mode)
729 break
730 }
731 }
732 }
733
734 cname, srvs, err := LookupSRV("ldap", "tcp", "google.com")
735 if err != nil {
736 t.Errorf("LookupSRV(ldap, tcp, google.com): %v (mode=%v)", err, mode)
737 } else {
738 if !hasSuffixFold(cname, ".google.com.") {
739 t.Errorf("LookupSRV(ldap, tcp, google.com) returned cname=%v, want name ending in .google.com. with trailing dot (mode=%v)", cname, mode)
740 }
741 for _, srv := range srvs {
742 if !hasSuffixFold(srv.Target, ".google.com.") {
743 t.Errorf("LookupSRV(ldap, tcp, google.com) returned addrs=%v, want names ending in .google.com. with trailing dot (mode=%v)", srvString(srvs), mode)
744 break
745 }
746 }
747 }
748 }
749
750 func mxString(mxs []*MX) string {
751 var buf strings.Builder
752 sep := ""
753 fmt.Fprintf(&buf, "[")
754 for _, mx := range mxs {
755 fmt.Fprintf(&buf, "%s%s:%d", sep, mx.Host, mx.Pref)
756 sep = " "
757 }
758 fmt.Fprintf(&buf, "]")
759 return buf.String()
760 }
761
762 func nsString(nss []*NS) string {
763 var buf strings.Builder
764 sep := ""
765 fmt.Fprintf(&buf, "[")
766 for _, ns := range nss {
767 fmt.Fprintf(&buf, "%s%s", sep, ns.Host)
768 sep = " "
769 }
770 fmt.Fprintf(&buf, "]")
771 return buf.String()
772 }
773
774 func srvString(srvs []*SRV) string {
775 var buf strings.Builder
776 sep := ""
777 fmt.Fprintf(&buf, "[")
778 for _, srv := range srvs {
779 fmt.Fprintf(&buf, "%s%s:%d:%d:%d", sep, srv.Target, srv.Port, srv.Priority, srv.Weight)
780 sep = " "
781 }
782 fmt.Fprintf(&buf, "]")
783 return buf.String()
784 }
785
786 func TestLookupPort(t *testing.T) {
787
788
789
790
791
792 type test struct {
793 network string
794 name string
795 port int
796 ok bool
797 }
798 var tests = []test{
799 {"tcp", "0", 0, true},
800 {"udp", "0", 0, true},
801 {"udp", "domain", 53, true},
802
803 {"--badnet--", "zzz", 0, false},
804 {"tcp", "--badport--", 0, false},
805 {"tcp", "-1", 0, false},
806 {"tcp", "65536", 0, false},
807 {"udp", "-1", 0, false},
808 {"udp", "65536", 0, false},
809 {"tcp", "123456789", 0, false},
810 {"tcp", "bad\x00port", 0, false},
811
812
813 {"tcp", "", 0, true},
814 {"tcp4", "", 0, true},
815 {"tcp6", "", 0, true},
816 {"udp", "", 0, true},
817 {"udp4", "", 0, true},
818 {"udp6", "", 0, true},
819 }
820
821 switch runtime.GOOS {
822 case "android":
823 if netGoBuildTag {
824 t.Skipf("not supported on %s without cgo; see golang.org/issues/14576", runtime.GOOS)
825 }
826 default:
827 tests = append(tests, test{"tcp", "http", 80, true})
828 }
829
830 for _, tt := range tests {
831 port, err := LookupPort(tt.network, tt.name)
832 if port != tt.port || (err == nil) != tt.ok {
833 t.Errorf("LookupPort(%q, %q) = %d, %v; want %d, error=%t", tt.network, tt.name, port, err, tt.port, !tt.ok)
834 }
835 if err != nil {
836 if perr := parseLookupPortError(err); perr != nil {
837 t.Error(perr)
838 }
839 }
840 }
841 }
842
843
844
845 func TestLookupPort_Minimal(t *testing.T) {
846 type test struct {
847 network string
848 name string
849 port int
850 }
851 var tests = []test{
852 {"tcp", "http", 80},
853 {"tcp", "HTTP", 80},
854 {"tcp", "https", 443},
855 {"tcp", "ssh", 22},
856 {"tcp", "gopher", 70},
857 {"tcp4", "http", 80},
858 {"tcp6", "http", 80},
859 }
860
861 for _, tt := range tests {
862 port, err := LookupPort(tt.network, tt.name)
863 if port != tt.port || err != nil {
864 t.Errorf("LookupPort(%q, %q) = %d, %v; want %d, error=nil", tt.network, tt.name, port, err, tt.port)
865 }
866 }
867 }
868
869 func TestLookupProtocol_Minimal(t *testing.T) {
870 type test struct {
871 name string
872 want int
873 }
874 var tests = []test{
875 {"tcp", 6},
876 {"TcP", 6},
877 {"icmp", 1},
878 {"igmp", 2},
879 {"udp", 17},
880 {"ipv6-icmp", 58},
881 }
882
883 for _, tt := range tests {
884 got, err := lookupProtocol(context.Background(), tt.name)
885 if got != tt.want || err != nil {
886 t.Errorf("LookupProtocol(%q) = %d, %v; want %d, error=nil", tt.name, got, err, tt.want)
887 }
888 }
889
890 }
891
892 func TestLookupNonLDH(t *testing.T) {
893 defer dnsWaitGroup.Wait()
894
895 if fixup := forceGoDNS(); fixup != nil {
896 defer fixup()
897 }
898
899
900
901
902
903 addrs, err := LookupHost("!!!.###.bogus..domain.")
904 if err == nil {
905 t.Fatalf("lookup succeeded: %v", addrs)
906 }
907 if !strings.HasSuffix(err.Error(), errNoSuchHost.Error()) {
908 t.Fatalf("lookup error = %v, want %v", err, errNoSuchHost)
909 }
910 if !err.(*DNSError).IsNotFound {
911 t.Fatalf("lookup error = %v, want true", err.(*DNSError).IsNotFound)
912 }
913 }
914
915 func TestLookupContextCancel(t *testing.T) {
916 mustHaveExternalNetwork(t)
917 testenv.SkipFlakyNet(t)
918
919 origTestHookLookupIP := testHookLookupIP
920 defer func() {
921 dnsWaitGroup.Wait()
922 testHookLookupIP = origTestHookLookupIP
923 }()
924
925 lookupCtx, cancelLookup := context.WithCancel(context.Background())
926 unblockLookup := make(chan struct{})
927
928
929
930
931 testHookLookupIP = func(
932 ctx context.Context,
933 fn func(context.Context, string, string) ([]IPAddr, error),
934 network string,
935 host string,
936 ) ([]IPAddr, error) {
937 select {
938 case <-unblockLookup:
939 default:
940
941
942
943
944
945 t.Logf("starting concurrent LookupIPAddr")
946 dnsWaitGroup.Add(1)
947 go func() {
948 defer dnsWaitGroup.Done()
949 _, err := DefaultResolver.LookupIPAddr(context.Background(), host)
950 if err != nil {
951 t.Error(err)
952 }
953 }()
954 time.Sleep(1 * time.Millisecond)
955 }
956
957 cancelLookup()
958 <-unblockLookup
959
960
961
962
963
964 if err := ctx.Err(); err != nil {
965 t.Logf("testHookLookupIP canceled")
966 return nil, err
967 }
968 t.Logf("testHookLookupIP performing lookup")
969 return fn(ctx, network, host)
970 }
971
972 _, err := DefaultResolver.LookupIPAddr(lookupCtx, "google.com")
973 if dnsErr, ok := err.(*DNSError); !ok || dnsErr.Err != errCanceled.Error() {
974 t.Errorf("unexpected error from canceled, blocked LookupIPAddr: %v", err)
975 }
976 close(unblockLookup)
977 }
978
979
980
981 func TestNilResolverLookup(t *testing.T) {
982 mustHaveExternalNetwork(t)
983 var r *Resolver = nil
984 ctx := context.Background()
985
986
987 r.LookupAddr(ctx, "8.8.8.8")
988 r.LookupCNAME(ctx, "google.com")
989 r.LookupHost(ctx, "google.com")
990 r.LookupIPAddr(ctx, "google.com")
991 r.LookupIP(ctx, "ip", "google.com")
992 r.LookupMX(ctx, "gmail.com")
993 r.LookupNS(ctx, "google.com")
994 r.LookupPort(ctx, "tcp", "smtp")
995 r.LookupSRV(ctx, "service", "proto", "name")
996 r.LookupTXT(ctx, "gmail.com")
997 }
998
999
1000
1001 func TestLookupHostCancel(t *testing.T) {
1002 mustHaveExternalNetwork(t)
1003 testenv.SkipFlakyNet(t)
1004 t.Parallel()
1005
1006 const (
1007 google = "www.google.com"
1008 invalidDomain = "invalid.invalid"
1009 n = 600
1010 )
1011
1012 _, err := LookupHost(google)
1013 if err != nil {
1014 t.Fatal(err)
1015 }
1016
1017 ctx, cancel := context.WithCancel(context.Background())
1018 cancel()
1019 for i := 0; i < n; i++ {
1020 addr, err := DefaultResolver.LookupHost(ctx, invalidDomain)
1021 if err == nil {
1022 t.Fatalf("LookupHost(%q): returns %v, but should fail", invalidDomain, addr)
1023 }
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033 time.Sleep(time.Millisecond * 1)
1034 }
1035
1036 _, err = LookupHost(google)
1037 if err != nil {
1038 t.Fatal(err)
1039 }
1040 }
1041
1042 type lookupCustomResolver struct {
1043 *Resolver
1044 mu sync.RWMutex
1045 dialed bool
1046 }
1047
1048 func (lcr *lookupCustomResolver) dial() func(ctx context.Context, network, address string) (Conn, error) {
1049 return func(ctx context.Context, network, address string) (Conn, error) {
1050 lcr.mu.Lock()
1051 lcr.dialed = true
1052 lcr.mu.Unlock()
1053 return Dial(network, address)
1054 }
1055 }
1056
1057
1058
1059 func TestConcurrentPreferGoResolversDial(t *testing.T) {
1060 switch runtime.GOOS {
1061 case "plan9":
1062
1063
1064 t.Skipf("skip on %v", runtime.GOOS)
1065 }
1066
1067 testenv.MustHaveExternalNetwork(t)
1068 testenv.SkipFlakyNet(t)
1069
1070 defer dnsWaitGroup.Wait()
1071
1072 resolvers := make([]*lookupCustomResolver, 2)
1073 for i := range resolvers {
1074 cs := lookupCustomResolver{Resolver: &Resolver{PreferGo: true}}
1075 cs.Dial = cs.dial()
1076 resolvers[i] = &cs
1077 }
1078
1079 var wg sync.WaitGroup
1080 wg.Add(len(resolvers))
1081 for i, resolver := range resolvers {
1082 go func(r *Resolver, index int) {
1083 defer wg.Done()
1084 _, err := r.LookupIPAddr(context.Background(), "google.com")
1085 if err != nil {
1086 t.Errorf("lookup failed for resolver %d: %q", index, err)
1087 }
1088 }(resolver.Resolver, i)
1089 }
1090 wg.Wait()
1091
1092 if t.Failed() {
1093 t.FailNow()
1094 }
1095
1096 for i, resolver := range resolvers {
1097 if !resolver.dialed {
1098 t.Errorf("custom resolver %d not dialed during lookup", i)
1099 }
1100 }
1101 }
1102
1103 var ipVersionTests = []struct {
1104 network string
1105 version byte
1106 }{
1107 {"tcp", 0},
1108 {"tcp4", '4'},
1109 {"tcp6", '6'},
1110 {"udp", 0},
1111 {"udp4", '4'},
1112 {"udp6", '6'},
1113 {"ip", 0},
1114 {"ip4", '4'},
1115 {"ip6", '6'},
1116 {"ip7", 0},
1117 {"", 0},
1118 }
1119
1120 func TestIPVersion(t *testing.T) {
1121 for _, tt := range ipVersionTests {
1122 if version := ipVersion(tt.network); version != tt.version {
1123 t.Errorf("Family for: %s. Expected: %s, Got: %s", tt.network,
1124 string(tt.version), string(version))
1125 }
1126 }
1127 }
1128
1129
1130
1131 func TestLookupIPAddrPreservesContextValues(t *testing.T) {
1132 origTestHookLookupIP := testHookLookupIP
1133 defer func() { testHookLookupIP = origTestHookLookupIP }()
1134
1135 keyValues := []struct {
1136 key, value any
1137 }{
1138 {"key-1", 12},
1139 {384, "value2"},
1140 {new(float64), 137},
1141 }
1142 ctx := context.Background()
1143 for _, kv := range keyValues {
1144 ctx = context.WithValue(ctx, kv.key, kv.value)
1145 }
1146
1147 wantIPs := []IPAddr{
1148 {IP: IPv4(127, 0, 0, 1)},
1149 {IP: IPv6loopback},
1150 }
1151
1152 checkCtxValues := func(ctx_ context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) {
1153 for _, kv := range keyValues {
1154 g, w := ctx_.Value(kv.key), kv.value
1155 if !reflect.DeepEqual(g, w) {
1156 t.Errorf("Value lookup:\n\tGot: %v\n\tWant: %v", g, w)
1157 }
1158 }
1159 return wantIPs, nil
1160 }
1161 testHookLookupIP = checkCtxValues
1162
1163 resolvers := []*Resolver{
1164 nil,
1165 new(Resolver),
1166 }
1167
1168 for i, resolver := range resolvers {
1169 gotIPs, err := resolver.LookupIPAddr(ctx, "golang.org")
1170 if err != nil {
1171 t.Errorf("Resolver #%d: unexpected error: %v", i, err)
1172 }
1173 if !reflect.DeepEqual(gotIPs, wantIPs) {
1174 t.Errorf("#%d: mismatched IPAddr results\n\tGot: %v\n\tWant: %v", i, gotIPs, wantIPs)
1175 }
1176 }
1177 }
1178
1179
1180 func TestLookupIPAddrConcurrentCallsForNetworks(t *testing.T) {
1181 origTestHookLookupIP := testHookLookupIP
1182 defer func() { testHookLookupIP = origTestHookLookupIP }()
1183
1184 queries := [][]string{
1185 {"udp", "golang.org"},
1186 {"udp4", "golang.org"},
1187 {"udp6", "golang.org"},
1188 {"udp", "golang.org"},
1189 {"udp", "golang.org"},
1190 }
1191 results := map[[2]string][]IPAddr{
1192 {"udp", "golang.org"}: {
1193 {IP: IPv4(127, 0, 0, 1)},
1194 {IP: IPv6loopback},
1195 },
1196 {"udp4", "golang.org"}: {
1197 {IP: IPv4(127, 0, 0, 1)},
1198 },
1199 {"udp6", "golang.org"}: {
1200 {IP: IPv6loopback},
1201 },
1202 }
1203 calls := int32(0)
1204 waitCh := make(chan struct{})
1205 testHookLookupIP = func(ctx context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) {
1206
1207
1208
1209 if atomic.AddInt32(&calls, 1) == int32(len(results)) {
1210 close(waitCh)
1211 }
1212 select {
1213 case <-waitCh:
1214 case <-ctx.Done():
1215 return nil, ctx.Err()
1216 }
1217 return results[[2]string{network, host}], nil
1218 }
1219
1220 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
1221 defer cancel()
1222 wg := sync.WaitGroup{}
1223 for _, q := range queries {
1224 network := q[0]
1225 host := q[1]
1226 wg.Add(1)
1227 go func() {
1228 defer wg.Done()
1229 gotIPs, err := DefaultResolver.lookupIPAddr(ctx, network, host)
1230 if err != nil {
1231 t.Errorf("lookupIPAddr(%v, %v): unexpected error: %v", network, host, err)
1232 }
1233 wantIPs := results[[2]string{network, host}]
1234 if !reflect.DeepEqual(gotIPs, wantIPs) {
1235 t.Errorf("lookupIPAddr(%v, %v): mismatched IPAddr results\n\tGot: %v\n\tWant: %v", network, host, gotIPs, wantIPs)
1236 }
1237 }()
1238 }
1239 wg.Wait()
1240 }
1241
1242
1243 func TestResolverLookupIPWithEmptyHost(t *testing.T) {
1244 _, err := DefaultResolver.LookupIP(context.Background(), "ip", "")
1245 if err == nil {
1246 t.Fatal("DefaultResolver.LookupIP for empty host success, want no host error")
1247 }
1248 if !strings.HasSuffix(err.Error(), errNoSuchHost.Error()) {
1249 t.Fatalf("lookup error = %v, want %v", err, errNoSuchHost)
1250 }
1251 }
1252
1253 func TestWithUnexpiredValuesPreserved(t *testing.T) {
1254 ctx, cancel := context.WithCancel(context.Background())
1255
1256
1257 key, value := "key-1", 2
1258 ctx = context.WithValue(ctx, key, value)
1259
1260
1261
1262 ctx = withUnexpiredValuesPreserved(ctx)
1263
1264
1265 if g, w := ctx.Value(key), value; g != w {
1266 t.Errorf("Lookup before expiry: Got %v Want %v", g, w)
1267 }
1268
1269
1270 cancel()
1271
1272
1273 if g := ctx.Value(key); g != nil {
1274 t.Errorf("Lookup after expiry: Got %v want nil", g)
1275 }
1276 }
1277
1278
1279 func TestLookupNullByte(t *testing.T) {
1280 testenv.MustHaveExternalNetwork(t)
1281 testenv.SkipFlakyNet(t)
1282 LookupHost("foo\x00bar")
1283 }
1284
1285 func TestResolverLookupIP(t *testing.T) {
1286 testenv.MustHaveExternalNetwork(t)
1287
1288 v4Ok := supportsIPv4() && *testIPv4
1289 v6Ok := supportsIPv6() && *testIPv6
1290
1291 defer dnsWaitGroup.Wait()
1292
1293 for _, impl := range []struct {
1294 name string
1295 fn func() func()
1296 }{
1297 {"go", forceGoDNS},
1298 {"cgo", forceCgoDNS},
1299 } {
1300 t.Run("implementation: "+impl.name, func(t *testing.T) {
1301 fixup := impl.fn()
1302 if fixup == nil {
1303 t.Skip("not supported")
1304 }
1305 defer fixup()
1306
1307 for _, network := range []string{"ip", "ip4", "ip6"} {
1308 t.Run("network: "+network, func(t *testing.T) {
1309 switch {
1310 case network == "ip4" && !v4Ok:
1311 t.Skip("IPv4 is not supported")
1312 case network == "ip6" && !v6Ok:
1313 t.Skip("IPv6 is not supported")
1314 }
1315
1316
1317 const host = "google.com"
1318 ips, err := DefaultResolver.LookupIP(context.Background(), network, host)
1319 if err != nil {
1320 testenv.SkipFlakyNet(t)
1321 t.Fatalf("DefaultResolver.LookupIP(%q, %q): failed with unexpected error: %v", network, host, err)
1322 }
1323
1324 var v4Addrs []netip.Addr
1325 var v6Addrs []netip.Addr
1326 for _, ip := range ips {
1327 if addr, ok := netip.AddrFromSlice(ip); ok {
1328 if addr.Is4() {
1329 v4Addrs = append(v4Addrs, addr)
1330 } else {
1331 v6Addrs = append(v6Addrs, addr)
1332 }
1333 } else {
1334 t.Fatalf("IP=%q is neither IPv4 nor IPv6", ip)
1335 }
1336 }
1337
1338
1339 if network == "ip4" || network == "ip" && v4Ok {
1340 if len(v4Addrs) == 0 {
1341 t.Errorf("DefaultResolver.LookupIP(%q, %q): no IPv4 addresses", network, host)
1342 }
1343 }
1344 if network == "ip6" || network == "ip" && v6Ok {
1345 if len(v6Addrs) == 0 {
1346 t.Errorf("DefaultResolver.LookupIP(%q, %q): no IPv6 addresses", network, host)
1347 }
1348 }
1349
1350
1351 if network == "ip6" && len(v4Addrs) > 0 {
1352 t.Errorf("DefaultResolver.LookupIP(%q, %q): unexpected IPv4 addresses: %v", network, host, v4Addrs)
1353 }
1354 if network == "ip4" && len(v6Addrs) > 0 {
1355 t.Errorf("DefaultResolver.LookupIP(%q, %q): unexpected IPv6 or IPv4-mapped IPv6 addresses: %v", network, host, v6Addrs)
1356 }
1357 })
1358 }
1359 })
1360 }
1361 }
1362
1363
1364 func TestDNSTimeout(t *testing.T) {
1365 origTestHookLookupIP := testHookLookupIP
1366 defer func() { testHookLookupIP = origTestHookLookupIP }()
1367 defer dnsWaitGroup.Wait()
1368
1369 timeoutHookGo := make(chan bool, 1)
1370 timeoutHook := func(ctx context.Context, fn func(context.Context, string, string) ([]IPAddr, error), network, host string) ([]IPAddr, error) {
1371 <-timeoutHookGo
1372 return nil, context.DeadlineExceeded
1373 }
1374 testHookLookupIP = timeoutHook
1375
1376 checkErr := func(err error) {
1377 t.Helper()
1378 if err == nil {
1379 t.Error("expected an error")
1380 } else if dnserr, ok := err.(*DNSError); !ok {
1381 t.Errorf("got error type %T, want %T", err, (*DNSError)(nil))
1382 } else if !dnserr.IsTimeout {
1383 t.Errorf("got error %#v, want IsTimeout == true", dnserr)
1384 } else if isTimeout := dnserr.Timeout(); !isTimeout {
1385 t.Errorf("got err.Timeout() == %t, want true", isTimeout)
1386 }
1387 }
1388
1389
1390 timeoutHookGo <- true
1391 _, err := LookupIP("golang.org")
1392 checkErr(err)
1393
1394
1395 var err1, err2 error
1396 var wg sync.WaitGroup
1397 wg.Add(2)
1398 go func() {
1399 defer wg.Done()
1400 _, err1 = LookupIP("golang1.org")
1401 }()
1402 go func() {
1403 defer wg.Done()
1404 _, err2 = LookupIP("golang1.org")
1405 }()
1406 close(timeoutHookGo)
1407 wg.Wait()
1408 checkErr(err1)
1409 checkErr(err2)
1410
1411
1412 timeoutHookGo = make(chan bool)
1413 ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond)
1414 wg.Add(2)
1415 go func() {
1416 defer wg.Done()
1417 _, err1 = DefaultResolver.LookupIPAddr(ctx, "golang2.org")
1418 }()
1419 go func() {
1420 defer wg.Done()
1421 _, err2 = DefaultResolver.LookupIPAddr(ctx, "golang2.org")
1422 }()
1423 time.Sleep(10 * time.Nanosecond)
1424 close(timeoutHookGo)
1425 wg.Wait()
1426 checkErr(err1)
1427 checkErr(err2)
1428 cancel()
1429 }
1430
1431 func TestLookupNoData(t *testing.T) {
1432 if runtime.GOOS == "plan9" {
1433 t.Skip("not supported on plan9")
1434 }
1435
1436 mustHaveExternalNetwork(t)
1437
1438 testLookupNoData(t, "default resolver")
1439
1440 func() {
1441 defer forceGoDNS()()
1442 testLookupNoData(t, "forced go resolver")
1443 }()
1444
1445 func() {
1446 defer forceCgoDNS()()
1447 testLookupNoData(t, "forced cgo resolver")
1448 }()
1449 }
1450
1451 func testLookupNoData(t *testing.T, prefix string) {
1452 attempts := 0
1453 for {
1454
1455
1456 _, err := LookupHost("golang.rsc.io.")
1457 if err == nil {
1458 t.Errorf("%v: unexpected success", prefix)
1459 return
1460 }
1461
1462 dnsErr, ok := errors.AsType[*DNSError](err)
1463 if ok {
1464 succeeded := true
1465 if !dnsErr.IsNotFound {
1466 succeeded = false
1467 t.Logf("%v: IsNotFound is set to false", prefix)
1468 }
1469
1470 if dnsErr.Err != errNoSuchHost.Error() {
1471 succeeded = false
1472 t.Logf("%v: error message is not equal to: %v", prefix, errNoSuchHost.Error())
1473 }
1474
1475 if succeeded {
1476 return
1477 }
1478 }
1479
1480 testenv.SkipFlakyNet(t)
1481 if attempts < len(backoffDuration) {
1482 dur := backoffDuration[attempts]
1483 t.Logf("%v: backoff %v after failure %v\n", prefix, dur, err)
1484 time.Sleep(dur)
1485 attempts++
1486 continue
1487 }
1488
1489 t.Errorf("%v: unexpected error: %v", prefix, err)
1490 return
1491 }
1492 }
1493
1494 func TestLookupPortNotFound(t *testing.T) {
1495 allResolvers(t, func(t *testing.T) {
1496 _, err := LookupPort("udp", "_-unknown-service-")
1497 if dnsErr, ok := errors.AsType[*DNSError](err); !ok || !dnsErr.IsNotFound {
1498 t.Fatalf("unexpected error: %v", err)
1499 }
1500 })
1501 }
1502
1503
1504
1505 var tcpOnlyService = func() string {
1506
1507 if runtime.GOOS == "plan9" {
1508 return "https"
1509 }
1510 return "submissions"
1511 }()
1512
1513 func TestLookupPortDifferentNetwork(t *testing.T) {
1514 allResolvers(t, func(t *testing.T) {
1515 _, err := LookupPort("udp", tcpOnlyService)
1516 if dnsErr, ok := errors.AsType[*DNSError](err); !ok || !dnsErr.IsNotFound {
1517 t.Fatalf("unexpected error: %v", err)
1518 }
1519 })
1520 }
1521
1522 func TestLookupPortEmptyNetworkString(t *testing.T) {
1523 allResolvers(t, func(t *testing.T) {
1524 _, err := LookupPort("", tcpOnlyService)
1525 if err != nil {
1526 t.Fatalf("unexpected error: %v", err)
1527 }
1528 })
1529 }
1530
1531 func TestLookupPortIPNetworkString(t *testing.T) {
1532 allResolvers(t, func(t *testing.T) {
1533 _, err := LookupPort("ip", tcpOnlyService)
1534 if err != nil {
1535 t.Fatalf("unexpected error: %v", err)
1536 }
1537 })
1538 }
1539
1540 func TestLookupNoSuchHost(t *testing.T) {
1541 mustHaveExternalNetwork(t)
1542
1543 const testNXDOMAIN = "invalid.invalid."
1544 const testNODATA = "_ldap._tcp.google.com."
1545
1546 tests := []struct {
1547 name string
1548 query func() error
1549 }{
1550 {
1551 name: "LookupCNAME NXDOMAIN",
1552 query: func() error {
1553 _, err := LookupCNAME(testNXDOMAIN)
1554 return err
1555 },
1556 },
1557 {
1558 name: "LookupHost NXDOMAIN",
1559 query: func() error {
1560 _, err := LookupHost(testNXDOMAIN)
1561 return err
1562 },
1563 },
1564 {
1565 name: "LookupHost NODATA",
1566 query: func() error {
1567 _, err := LookupHost(testNODATA)
1568 return err
1569 },
1570 },
1571 {
1572 name: "LookupMX NXDOMAIN",
1573 query: func() error {
1574 _, err := LookupMX(testNXDOMAIN)
1575 return err
1576 },
1577 },
1578 {
1579 name: "LookupMX NODATA",
1580 query: func() error {
1581 _, err := LookupMX(testNODATA)
1582 return err
1583 },
1584 },
1585 {
1586 name: "LookupNS NXDOMAIN",
1587 query: func() error {
1588 _, err := LookupNS(testNXDOMAIN)
1589 return err
1590 },
1591 },
1592 {
1593 name: "LookupNS NODATA",
1594 query: func() error {
1595 _, err := LookupNS(testNODATA)
1596 return err
1597 },
1598 },
1599 {
1600 name: "LookupSRV NXDOMAIN",
1601 query: func() error {
1602 _, _, err := LookupSRV("unknown", "tcp", testNXDOMAIN)
1603 return err
1604 },
1605 },
1606 {
1607 name: "LookupTXT NXDOMAIN",
1608 query: func() error {
1609 _, err := LookupTXT(testNXDOMAIN)
1610 return err
1611 },
1612 },
1613 {
1614 name: "LookupTXT NODATA",
1615 query: func() error {
1616 _, err := LookupTXT(testNODATA)
1617 return err
1618 },
1619 },
1620 }
1621
1622 for _, v := range tests {
1623 t.Run(v.name, func(t *testing.T) {
1624 allResolvers(t, func(t *testing.T) {
1625 attempts := 0
1626 for {
1627 err := v.query()
1628 if err == nil {
1629 t.Errorf("unexpected success")
1630 return
1631 }
1632 if dnsErr, ok := err.(*DNSError); ok {
1633 succeeded := true
1634 if !dnsErr.IsNotFound {
1635 succeeded = false
1636 t.Log("IsNotFound is set to false")
1637 }
1638 if dnsErr.Err != errNoSuchHost.Error() {
1639 succeeded = false
1640 t.Logf("error message is not equal to: %v", errNoSuchHost.Error())
1641 }
1642 if succeeded {
1643 return
1644 }
1645 }
1646 testenv.SkipFlakyNet(t)
1647 if attempts < len(backoffDuration) {
1648 dur := backoffDuration[attempts]
1649 t.Logf("backoff %v after failure %v\n", dur, err)
1650 time.Sleep(dur)
1651 attempts++
1652 continue
1653 }
1654 t.Errorf("unexpected error: %v", err)
1655 return
1656 }
1657 })
1658 })
1659 }
1660 }
1661
1662 func TestDNSErrorUnwrap(t *testing.T) {
1663 if runtime.GOOS == "plan9" {
1664
1665 t.Skip("skipping on plan9")
1666 }
1667 rDeadlineExcceeded := &Resolver{PreferGo: true, Dial: func(ctx context.Context, network, address string) (Conn, error) {
1668 return nil, context.DeadlineExceeded
1669 }}
1670 rCancelled := &Resolver{PreferGo: true, Dial: func(ctx context.Context, network, address string) (Conn, error) {
1671 return nil, context.Canceled
1672 }}
1673
1674 _, err := rDeadlineExcceeded.LookupHost(context.Background(), "test.go.dev")
1675 if !errors.Is(err, context.DeadlineExceeded) {
1676 t.Errorf("errors.Is(err, context.DeadlineExceeded) = false; want = true")
1677 }
1678
1679 _, err = rCancelled.LookupHost(context.Background(), "test.go.dev")
1680 if !errors.Is(err, context.Canceled) {
1681 t.Errorf("errors.Is(err, context.Canceled) = false; want = true")
1682 }
1683
1684 ctx, cancel := context.WithCancel(context.Background())
1685 cancel()
1686 _, err = goResolver.LookupHost(ctx, "text.go.dev")
1687 if !errors.Is(err, context.Canceled) {
1688 t.Errorf("errors.Is(err, context.Canceled) = false; want = true")
1689 }
1690 }
1691
View as plain text