| 1 | // Copyright 2016 CNI authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package main |
| 16 | |
| 17 | import ( |
| 18 | "bufio" |
| 19 | "os" |
| 20 | "strings" |
| 21 | |
| 22 | "github.com/containernetworking/cni/pkg/types" |
| 23 | ) |
| 24 | |
| 25 | // parseResolvConf parses an existing resolv.conf in to a DNS struct |
| 26 | func parseResolvConf(filename string) (*types.DNS, error) { |
| 27 | fp, err := os.Open(filename) |
| 28 | if err != nil { |
| 29 | return nil, err |
| 30 | } |
| 31 | defer fp.Close() |
| 32 | |
| 33 | dns := types.DNS{} |
| 34 | scanner := bufio.NewScanner(fp) |
| 35 | for scanner.Scan() { |
| 36 | line := scanner.Text() |
| 37 | line = strings.TrimSpace(line) |
| 38 | |
| 39 | // Skip comments, empty lines |
| 40 | if len(line) == 0 || line[0] == '#' || line[0] == ';' { |
| 41 | continue |
| 42 | } |
| 43 | |
| 44 | fields := strings.Fields(line) |
| 45 | if len(fields) < 2 { |
| 46 | continue |
| 47 | } |
| 48 | switch fields[0] { |
| 49 | case "nameserver": |
| 50 | dns.Nameservers = append(dns.Nameservers, fields[1]) |
| 51 | case "domain": |
| 52 | dns.Domain = fields[1] |
| 53 | case "search": |
| 54 | dns.Search = append(dns.Search, fields[1:]...) |
| 55 | case "options": |
| 56 | dns.Options = append(dns.Options, fields[1:]...) |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | if err := scanner.Err(); err != nil { |
| 61 | return nil, err |
| 62 | } |
| 63 | |
| 64 | return &dns, nil |
| 65 | } |