...

Source file src/net/dnsconfig_unix.go

Documentation: net

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
     6  
     7  // Read system DNS config from /etc/resolv.conf
     8  
     9  package net
    10  
    11  import (
    12  	"internal/bytealg"
    13  	"os"
    14  	"sync/atomic"
    15  	"time"
    16  )
    17  
    18  var (
    19  	defaultNS   = []string{"127.0.0.1:53", "[::1]:53"}
    20  	getHostname = os.Hostname // variable for testing
    21  )
    22  
    23  type dnsConfig struct {
    24  	servers    []string      // server addresses (in host:port form) to use
    25  	search     []string      // rooted suffixes to append to local name
    26  	ndots      int           // number of dots in name to trigger absolute lookup
    27  	timeout    time.Duration // wait before giving up on a query, including retries
    28  	attempts   int           // lost packets before giving up on server
    29  	rotate     bool          // round robin among servers
    30  	unknownOpt bool          // anything unknown was encountered
    31  	lookup     []string      // OpenBSD top-level database "lookup" order
    32  	err        error         // any error that occurs during open of resolv.conf
    33  	mtime      time.Time     // time of resolv.conf modification
    34  	soffset    uint32        // used by serverOffset
    35  }
    36  
    37  // See resolv.conf(5) on a Linux machine.
    38  func dnsReadConfig(filename string) *dnsConfig {
    39  	conf := &dnsConfig{
    40  		ndots:    1,
    41  		timeout:  5 * time.Second,
    42  		attempts: 2,
    43  	}
    44  	file, err := open(filename)
    45  	if err != nil {
    46  		conf.servers = defaultNS
    47  		conf.search = dnsDefaultSearch()
    48  		conf.err = err
    49  		return conf
    50  	}
    51  	defer file.close()
    52  	if fi, err := file.file.Stat(); err == nil {
    53  		conf.mtime = fi.ModTime()
    54  	} else {
    55  		conf.servers = defaultNS
    56  		conf.search = dnsDefaultSearch()
    57  		conf.err = err
    58  		return conf
    59  	}
    60  	for line, ok := file.readLine(); ok; line, ok = file.readLine() {
    61  		if len(line) > 0 && (line[0] == ';' || line[0] == '#') {
    62  			// comment.
    63  			continue
    64  		}
    65  		f := getFields(line)
    66  		if len(f) < 1 {
    67  			continue
    68  		}
    69  		switch f[0] {
    70  		case "nameserver": // add one name server
    71  			if len(f) > 1 && len(conf.servers) < 3 { // small, but the standard limit
    72  				// One more check: make sure server name is
    73  				// just an IP address. Otherwise we need DNS
    74  				// to look it up.
    75  				if parseIPv4(f[1]) != nil {
    76  					conf.servers = append(conf.servers, JoinHostPort(f[1], "53"))
    77  				} else if ip, _ := parseIPv6Zone(f[1]); ip != nil {
    78  					conf.servers = append(conf.servers, JoinHostPort(f[1], "53"))
    79  				}
    80  			}
    81  
    82  		case "domain": // set search path to just this domain
    83  			if len(f) > 1 {
    84  				conf.search = []string{ensureRooted(f[1])}
    85  			}
    86  
    87  		case "search": // set search path to given servers
    88  			conf.search = make([]string, len(f)-1)
    89  			for i := 0; i < len(conf.search); i++ {
    90  				conf.search[i] = ensureRooted(f[i+1])
    91  			}
    92  
    93  		case "options": // magic options
    94  			for _, s := range f[1:] {
    95  				switch {
    96  				case hasPrefix(s, "ndots:"):
    97  					n, _, _ := dtoi(s[6:])
    98  					if n < 0 {
    99  						n = 0
   100  					} else if n > 15 {
   101  						n = 15
   102  					}
   103  					conf.ndots = n
   104  				case hasPrefix(s, "timeout:"):
   105  					n, _, _ := dtoi(s[8:])
   106  					if n < 1 {
   107  						n = 1
   108  					}
   109  					conf.timeout = time.Duration(n) * time.Second
   110  				case hasPrefix(s, "attempts:"):
   111  					n, _, _ := dtoi(s[9:])
   112  					if n < 1 {
   113  						n = 1
   114  					}
   115  					conf.attempts = n
   116  				case s == "rotate":
   117  					conf.rotate = true
   118  				default:
   119  					conf.unknownOpt = true
   120  				}
   121  			}
   122  
   123  		case "lookup":
   124  			// OpenBSD option:
   125  			// https://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man5/resolv.conf.5
   126  			// "the legal space-separated values are: bind, file, yp"
   127  			conf.lookup = f[1:]
   128  
   129  		default:
   130  			conf.unknownOpt = true
   131  		}
   132  	}
   133  	if len(conf.servers) == 0 {
   134  		conf.servers = defaultNS
   135  	}
   136  	if len(conf.search) == 0 {
   137  		conf.search = dnsDefaultSearch()
   138  	}
   139  	return conf
   140  }
   141  
   142  // serverOffset returns an offset that can be used to determine
   143  // indices of servers in c.servers when making queries.
   144  // When the rotate option is enabled, this offset increases.
   145  // Otherwise it is always 0.
   146  func (c *dnsConfig) serverOffset() uint32 {
   147  	if c.rotate {
   148  		return atomic.AddUint32(&c.soffset, 1) - 1 // return 0 to start
   149  	}
   150  	return 0
   151  }
   152  
   153  func dnsDefaultSearch() []string {
   154  	hn, err := getHostname()
   155  	if err != nil {
   156  		// best effort
   157  		return nil
   158  	}
   159  	if i := bytealg.IndexByteString(hn, '.'); i >= 0 && i < len(hn)-1 {
   160  		return []string{ensureRooted(hn[i+1:])}
   161  	}
   162  	return nil
   163  }
   164  
   165  func hasPrefix(s, prefix string) bool {
   166  	return len(s) >= len(prefix) && s[:len(prefix)] == prefix
   167  }
   168  
   169  func ensureRooted(s string) string {
   170  	if len(s) > 0 && s[len(s)-1] == '.' {
   171  		return s
   172  	}
   173  	return s + "."
   174  }
   175  

View as plain text