From 21b1a44cd61db603f363c9cb2aed5b05f3e38a9d Mon Sep 17 00:00:00 2001 From: Josh Bleecher Snyder Date: Tue, 23 Nov 2021 13:36:25 -0800 Subject: [PATCH] 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 (cherry picked from commit 9f00510833857845ae71c891f1ebba4986d0f804) --- net/dns/direct.go | 4 ++++ net/dns/direct_test.go | 44 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/net/dns/direct.go b/net/dns/direct.go index 5742d2d21..d74e2bc89 100644 --- a/net/dns/direct.go +++ b/net/dns/direct.go @@ -50,6 +50,10 @@ func readResolv(r io.Reader) (config OSConfig, err error) { scanner := bufio.NewScanner(r) for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) + i := strings.IndexByte(line, '#') + if i >= 0 { + line = line[:i] + } if strings.HasPrefix(line, "nameserver") { nameserver := strings.TrimPrefix(line, "nameserver") diff --git a/net/dns/direct_test.go b/net/dns/direct_test.go index 07147b669..6cd8ff8c5 100644 --- a/net/dns/direct_test.go +++ b/net/dns/direct_test.go @@ -14,6 +14,7 @@ "syscall" "testing" + qt "github.com/frankban/quicktest" "inet.af/netaddr" "tailscale.com/util/dnsname" ) @@ -138,3 +139,46 @@ func TestDirectBrokenRemove(t *testing.T) { } 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) + } +}