net/dns: handle comments in resolv.conf

Currently, comments in resolv.conf cause our parser to fail,
with error messages like:

ParseIP("192.168.0.100 # comment"): unexpected character (at " # comment")

Fix that.

Noticed while looking through logs.

Signed-off-by: Josh Bleecher Snyder <josh@tailscale.com>
(cherry picked from commit 9f00510833)
This commit is contained in:
Josh Bleecher Snyder 2021-11-23 13:36:25 -08:00 committed by Brad Fitzpatrick
parent 47975d373f
commit 21b1a44cd6
2 changed files with 48 additions and 0 deletions

View File

@ -50,6 +50,10 @@ func readResolv(r io.Reader) (config OSConfig, err error) {
scanner := bufio.NewScanner(r) scanner := bufio.NewScanner(r)
for scanner.Scan() { for scanner.Scan() {
line := strings.TrimSpace(scanner.Text()) line := strings.TrimSpace(scanner.Text())
i := strings.IndexByte(line, '#')
if i >= 0 {
line = line[:i]
}
if strings.HasPrefix(line, "nameserver") { if strings.HasPrefix(line, "nameserver") {
nameserver := strings.TrimPrefix(line, "nameserver") nameserver := strings.TrimPrefix(line, "nameserver")

View File

@ -14,6 +14,7 @@
"syscall" "syscall"
"testing" "testing"
qt "github.com/frankban/quicktest"
"inet.af/netaddr" "inet.af/netaddr"
"tailscale.com/util/dnsname" "tailscale.com/util/dnsname"
) )
@ -138,3 +139,46 @@ func TestDirectBrokenRemove(t *testing.T) {
} }
testDirect(t, brokenRemoveFS{directFS{prefix: tmp}}) testDirect(t, brokenRemoveFS{directFS{prefix: tmp}})
} }
func TestReadResolve(t *testing.T) {
c := qt.New(t)
tests := []struct {
in string
want OSConfig
wantErr bool
}{
{in: `nameserver 192.168.0.100`,
want: OSConfig{
Nameservers: []netaddr.IP{
netaddr.MustParseIP("192.168.0.100"),
},
},
},
{in: `nameserver 192.168.0.100 # comment`,
want: OSConfig{
Nameservers: []netaddr.IP{
netaddr.MustParseIP("192.168.0.100"),
},
},
},
{in: `nameserver 192.168.0.100#`,
want: OSConfig{
Nameservers: []netaddr.IP{
netaddr.MustParseIP("192.168.0.100"),
},
},
},
{in: `nameserver #192.168.0.100`, wantErr: true},
{in: `# nameserver 192.168.0.100`, want: OSConfig{}},
}
for _, test := range tests {
cfg, err := readResolv(strings.NewReader(test.in))
if test.wantErr {
c.Assert(err, qt.IsNotNil)
} else {
c.Assert(err, qt.IsNil)
}
c.Assert(cfg, qt.DeepEquals, test.want)
}
}