Skip to content

Commit

Permalink
net: fall back to hosts file if DNS lookup fails, despite order
Browse files Browse the repository at this point in the history
Fixes golang#13090

Change-Id: I5612d792dabdff89bd0cec57dc2cacf9be7ebf64
Reviewed-on: https://go-review.googlesource.com/16341
Run-TryBot: Brad Fitzpatrick <[email protected]>
TryBot-Result: Gobot Gobot <[email protected]>
Reviewed-by: Brad Fitzpatrick <[email protected]>
  • Loading branch information
Benjamin Prosnitz authored and bradfitz committed Dec 2, 2015
1 parent e4e4942 commit e614d60
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/net/dnsclient_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -473,12 +473,12 @@ func goLookupIPOrder(name string, order hostLookupOrder) (addrs []IPAddr, err er
}
sortByRFC6724(addrs)
if len(addrs) == 0 {
if lastErr != nil {
return nil, lastErr
}
if order == hostLookupDNSFiles {
addrs = goLookupIPFiles(name)
}
if lastErr != nil {
return nil, lastErr
}
}
return addrs, nil
}
Expand Down
42 changes: 42 additions & 0 deletions src/net/dnsclient_unix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,48 @@ func TestGoLookupIPWithResolverConfig(t *testing.T) {
}
}

// Test that goLookupIPOrder falls back to the host file when no DNS servers are available.
func TestGoLookupIPOrderFallbackToFile(t *testing.T) {
if testing.Short() || !*testExternal {
t.Skip("avoid external network")
}

// Add a config that simulates no dns servers being available.
conf, err := newResolvConfTest()
if err != nil {
t.Fatal(err)
}
if err := conf.writeAndUpdate([]string{}); err != nil {
t.Fatal(err)
}
conf.tryUpdate(conf.path)
// Redirect host file lookups.
defer func(orig string) { testHookHostsPath = orig }(testHookHostsPath)
testHookHostsPath = "testdata/hosts"

for _, order := range []hostLookupOrder{hostLookupFilesDNS, hostLookupDNSFiles} {
name := fmt.Sprintf("order %v", order)

// First ensure that we get an error when contacting a non-existant host.
_, err := goLookupIPOrder("notarealhost", order)
if err == nil {
t.Errorf("%s: expected error while looking up name not in hosts file", name)
continue
}

// Now check that we get an address when the name appears in the hosts file.
addrs, err := goLookupIPOrder("thor", order) // entry is in "testdata/hosts"
if err != nil {
t.Errorf("%s: expected to successfully lookup host entry", name)
continue
}
if got, want := addrs, []IPAddr{IPAddr{IP: IP{127, 0, 0, 1}}}; !reflect.DeepEqual(got, want) {
t.Errorf("%s: address doesn't match expectation. got %v, want %v", name, got, want)
}
}
defer conf.teardown()
}

func BenchmarkGoLookupIP(b *testing.B) {
testHookUninstaller.Do(uninstallTestHooks)

Expand Down

0 comments on commit e614d60

Please sign in to comment.