From d0c0924e6cd11aae7c2976238d4ea96f70aac71a Mon Sep 17 00:00:00 2001 From: gVisor bot Date: Wed, 28 Jun 2023 09:17:40 +0800 Subject: [PATCH] chore: better resolv.conf parsing --- dns/system_posix.go | 36 ++++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/dns/system_posix.go b/dns/system_posix.go index d486b4fb..4d07d4ec 100644 --- a/dns/system_posix.go +++ b/dns/system_posix.go @@ -3,25 +3,41 @@ package dns import ( + "bufio" "fmt" + "net/netip" "os" - "regexp" + "strings" ) -var ( - // nameserver xxx.xxx.xxx.xxx - nameserverPattern = regexp.MustCompile(`nameserver\s+(?P\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})`) -) +const resolvConf = "/etc/resolv.conf" func dnsReadConfig() (servers []string, err error) { - content, err := os.ReadFile("/etc/resolv.conf") + file, err := os.Open(resolvConf) if err != nil { - err = fmt.Errorf("failed to read /etc/resolv.conf: %w", err) + err = fmt.Errorf("failed to read %s: %w", resolvConf, err) return } - for _, line := range nameserverPattern.FindAllStringSubmatch(string(content), -1) { - addr := line[1] - servers = append(servers, addr) + defer func() { _ = file.Close() }() + scanner := bufio.NewScanner(file) + for scanner.Scan() { + line := scanner.Text() + if len(line) > 0 && (line[0] == ';' || line[0] == '#') { + // comment. + continue + } + f := strings.Fields(line) + if len(f) < 1 { + continue + } + switch f[0] { + case "nameserver": // add one name server + if len(f) > 1 { + if addr, err := netip.ParseAddr(f[1]); err == nil { + servers = append(servers, addr.String()) + } + } + } } return }