github.com/docker/engine@v22.0.0-20211208180946-d456264580cf+incompatible/libnetwork/resolvconf/resolvconf.go (about)

     1  // Package resolvconf provides utility code to query and update DNS configuration in /etc/resolv.conf
     2  package resolvconf
     3  
     4  import (
     5  	"bytes"
     6  	"os"
     7  	"regexp"
     8  	"strings"
     9  	"sync"
    10  
    11  	"github.com/sirupsen/logrus"
    12  )
    13  
    14  const (
    15  	// defaultPath is the default path to the resolv.conf that contains information to resolve DNS. See Path().
    16  	defaultPath = "/etc/resolv.conf"
    17  	// alternatePath is a path different from defaultPath, that may be used to resolve DNS. See Path().
    18  	alternatePath = "/run/systemd/resolve/resolv.conf"
    19  )
    20  
    21  // constants for the IP address type
    22  const (
    23  	IP = iota // IPv4 and IPv6
    24  	IPv4
    25  	IPv6
    26  )
    27  
    28  var (
    29  	detectSystemdResolvConfOnce sync.Once
    30  	pathAfterSystemdDetection   = defaultPath
    31  )
    32  
    33  // Path returns the path to the resolv.conf file that libnetwork should use.
    34  //
    35  // When /etc/resolv.conf contains 127.0.0.53 as the only nameserver, then
    36  // it is assumed systemd-resolved manages DNS. Because inside the container 127.0.0.53
    37  // is not a valid DNS server, Path() returns /run/systemd/resolve/resolv.conf
    38  // which is the resolv.conf that systemd-resolved generates and manages.
    39  // Otherwise Path() returns /etc/resolv.conf.
    40  //
    41  // Errors are silenced as they will inevitably resurface at future open/read calls.
    42  //
    43  // More information at https://www.freedesktop.org/software/systemd/man/systemd-resolved.service.html#/etc/resolv.conf
    44  func Path() string {
    45  	detectSystemdResolvConfOnce.Do(func() {
    46  		candidateResolvConf, err := os.ReadFile(defaultPath)
    47  		if err != nil {
    48  			// silencing error as it will resurface at next calls trying to read defaultPath
    49  			return
    50  		}
    51  		ns := GetNameservers(candidateResolvConf, IP)
    52  		if len(ns) == 1 && ns[0] == "127.0.0.53" {
    53  			pathAfterSystemdDetection = alternatePath
    54  			logrus.Infof("detected 127.0.0.53 nameserver, assuming systemd-resolved, so using resolv.conf: %s", alternatePath)
    55  		}
    56  	})
    57  	return pathAfterSystemdDetection
    58  }
    59  
    60  const (
    61  	// ipLocalhost is a regex pattern for IPv4 or IPv6 loopback range.
    62  	ipLocalhost  = `((127\.([0-9]{1,3}\.){2}[0-9]{1,3})|(::1)$)`
    63  	ipv4NumBlock = `(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)`
    64  	ipv4Address  = `(` + ipv4NumBlock + `\.){3}` + ipv4NumBlock
    65  
    66  	// This is not an IPv6 address verifier as it will accept a super-set of IPv6, and also
    67  	// will *not match* IPv4-Embedded IPv6 Addresses (RFC6052), but that and other variants
    68  	// -- e.g. other link-local types -- either won't work in containers or are unnecessary.
    69  	// For readability and sufficiency for Docker purposes this seemed more reasonable than a
    70  	// 1000+ character regexp with exact and complete IPv6 validation
    71  	ipv6Address = `([0-9A-Fa-f]{0,4}:){2,7}([0-9A-Fa-f]{0,4})(%\w+)?`
    72  )
    73  
    74  var (
    75  	// Note: the default IPv4 & IPv6 resolvers are set to Google's Public DNS
    76  	defaultIPv4Dns = []string{"nameserver 8.8.8.8", "nameserver 8.8.4.4"}
    77  	defaultIPv6Dns = []string{"nameserver 2001:4860:4860::8888", "nameserver 2001:4860:4860::8844"}
    78  
    79  	localhostNSRegexp = regexp.MustCompile(`(?m)^nameserver\s+` + ipLocalhost + `\s*\n*`)
    80  	nsIPv6Regexp      = regexp.MustCompile(`(?m)^nameserver\s+` + ipv6Address + `\s*\n*`)
    81  	nsRegexp          = regexp.MustCompile(`^\s*nameserver\s*((` + ipv4Address + `)|(` + ipv6Address + `))\s*$`)
    82  	nsIPv6Regexpmatch = regexp.MustCompile(`^\s*nameserver\s*((` + ipv6Address + `))\s*$`)
    83  	nsIPv4Regexpmatch = regexp.MustCompile(`^\s*nameserver\s*((` + ipv4Address + `))\s*$`)
    84  	searchRegexp      = regexp.MustCompile(`^\s*search\s*(([^\s]+\s*)*)$`)
    85  	optionsRegexp     = regexp.MustCompile(`^\s*options\s*(([^\s]+\s*)*)$`)
    86  )
    87  
    88  var lastModified struct {
    89  	sync.Mutex
    90  	sha256   string
    91  	contents []byte
    92  }
    93  
    94  // File contains the resolv.conf content and its hash
    95  type File struct {
    96  	Content []byte
    97  	Hash    string
    98  }
    99  
   100  // Get returns the contents of /etc/resolv.conf and its hash
   101  func Get() (*File, error) {
   102  	return GetSpecific(Path())
   103  }
   104  
   105  // GetSpecific returns the contents of the user specified resolv.conf file and its hash
   106  func GetSpecific(path string) (*File, error) {
   107  	resolv, err := os.ReadFile(path)
   108  	if err != nil {
   109  		return nil, err
   110  	}
   111  	hash, err := hashData(bytes.NewReader(resolv))
   112  	if err != nil {
   113  		return nil, err
   114  	}
   115  	return &File{Content: resolv, Hash: hash}, nil
   116  }
   117  
   118  // GetIfChanged retrieves the host /etc/resolv.conf file, checks against the last hash
   119  // and, if modified since last check, returns the bytes and new hash.
   120  // This feature is used by the resolv.conf updater for containers
   121  func GetIfChanged() (*File, error) {
   122  	lastModified.Lock()
   123  	defer lastModified.Unlock()
   124  
   125  	resolv, err := os.ReadFile(Path())
   126  	if err != nil {
   127  		return nil, err
   128  	}
   129  	newHash, err := hashData(bytes.NewReader(resolv))
   130  	if err != nil {
   131  		return nil, err
   132  	}
   133  	if lastModified.sha256 != newHash {
   134  		lastModified.sha256 = newHash
   135  		lastModified.contents = resolv
   136  		return &File{Content: resolv, Hash: newHash}, nil
   137  	}
   138  	// nothing changed, so return no data
   139  	return nil, nil
   140  }
   141  
   142  // GetLastModified retrieves the last used contents and hash of the host resolv.conf.
   143  // Used by containers updating on restart
   144  func GetLastModified() *File {
   145  	lastModified.Lock()
   146  	defer lastModified.Unlock()
   147  
   148  	return &File{Content: lastModified.contents, Hash: lastModified.sha256}
   149  }
   150  
   151  // FilterResolvDNS cleans up the config in resolvConf.  It has two main jobs:
   152  // 1. It looks for localhost (127.*|::1) entries in the provided
   153  //    resolv.conf, removing local nameserver entries, and, if the resulting
   154  //    cleaned config has no defined nameservers left, adds default DNS entries
   155  // 2. Given the caller provides the enable/disable state of IPv6, the filter
   156  //    code will remove all IPv6 nameservers if it is not enabled for containers
   157  //
   158  func FilterResolvDNS(resolvConf []byte, ipv6Enabled bool) (*File, error) {
   159  	cleanedResolvConf := localhostNSRegexp.ReplaceAll(resolvConf, []byte{})
   160  	// if IPv6 is not enabled, also clean out any IPv6 address nameserver
   161  	if !ipv6Enabled {
   162  		cleanedResolvConf = nsIPv6Regexp.ReplaceAll(cleanedResolvConf, []byte{})
   163  	}
   164  	// if the resulting resolvConf has no more nameservers defined, add appropriate
   165  	// default DNS servers for IPv4 and (optionally) IPv6
   166  	if len(GetNameservers(cleanedResolvConf, IP)) == 0 {
   167  		logrus.Infof("No non-localhost DNS nameservers are left in resolv.conf. Using default external servers: %v", defaultIPv4Dns)
   168  		dns := defaultIPv4Dns
   169  		if ipv6Enabled {
   170  			logrus.Infof("IPv6 enabled; Adding default IPv6 external servers: %v", defaultIPv6Dns)
   171  			dns = append(dns, defaultIPv6Dns...)
   172  		}
   173  		cleanedResolvConf = append(cleanedResolvConf, []byte("\n"+strings.Join(dns, "\n"))...)
   174  	}
   175  	hash, err := hashData(bytes.NewReader(cleanedResolvConf))
   176  	if err != nil {
   177  		return nil, err
   178  	}
   179  	return &File{Content: cleanedResolvConf, Hash: hash}, nil
   180  }
   181  
   182  // getLines parses input into lines and strips away comments.
   183  func getLines(input []byte, commentMarker []byte) [][]byte {
   184  	lines := bytes.Split(input, []byte("\n"))
   185  	var output [][]byte
   186  	for _, currentLine := range lines {
   187  		var commentIndex = bytes.Index(currentLine, commentMarker)
   188  		if commentIndex == -1 {
   189  			output = append(output, currentLine)
   190  		} else {
   191  			output = append(output, currentLine[:commentIndex])
   192  		}
   193  	}
   194  	return output
   195  }
   196  
   197  // GetNameservers returns nameservers (if any) listed in /etc/resolv.conf
   198  func GetNameservers(resolvConf []byte, kind int) []string {
   199  	nameservers := []string{}
   200  	for _, line := range getLines(resolvConf, []byte("#")) {
   201  		var ns [][]byte
   202  		if kind == IP {
   203  			ns = nsRegexp.FindSubmatch(line)
   204  		} else if kind == IPv4 {
   205  			ns = nsIPv4Regexpmatch.FindSubmatch(line)
   206  		} else if kind == IPv6 {
   207  			ns = nsIPv6Regexpmatch.FindSubmatch(line)
   208  		}
   209  		if len(ns) > 0 {
   210  			nameservers = append(nameservers, string(ns[1]))
   211  		}
   212  	}
   213  	return nameservers
   214  }
   215  
   216  // GetNameserversAsCIDR returns nameservers (if any) listed in
   217  // /etc/resolv.conf as CIDR blocks (e.g., "1.2.3.4/32")
   218  // This function's output is intended for net.ParseCIDR
   219  func GetNameserversAsCIDR(resolvConf []byte) []string {
   220  	nameservers := []string{}
   221  	for _, nameserver := range GetNameservers(resolvConf, IP) {
   222  		var address string
   223  		// If IPv6, strip zone if present
   224  		if strings.Contains(nameserver, ":") {
   225  			address = strings.Split(nameserver, "%")[0] + "/128"
   226  		} else {
   227  			address = nameserver + "/32"
   228  		}
   229  		nameservers = append(nameservers, address)
   230  	}
   231  	return nameservers
   232  }
   233  
   234  // GetSearchDomains returns search domains (if any) listed in /etc/resolv.conf
   235  // If more than one search line is encountered, only the contents of the last
   236  // one is returned.
   237  func GetSearchDomains(resolvConf []byte) []string {
   238  	domains := []string{}
   239  	for _, line := range getLines(resolvConf, []byte("#")) {
   240  		match := searchRegexp.FindSubmatch(line)
   241  		if match == nil {
   242  			continue
   243  		}
   244  		domains = strings.Fields(string(match[1]))
   245  	}
   246  	return domains
   247  }
   248  
   249  // GetOptions returns options (if any) listed in /etc/resolv.conf
   250  // If more than one options line is encountered, only the contents of the last
   251  // one is returned.
   252  func GetOptions(resolvConf []byte) []string {
   253  	options := []string{}
   254  	for _, line := range getLines(resolvConf, []byte("#")) {
   255  		match := optionsRegexp.FindSubmatch(line)
   256  		if match == nil {
   257  			continue
   258  		}
   259  		options = strings.Fields(string(match[1]))
   260  	}
   261  	return options
   262  }
   263  
   264  // Build writes a configuration file to path containing a "nameserver" entry
   265  // for every element in dns, a "search" entry for every element in
   266  // dnsSearch, and an "options" entry for every element in dnsOptions.
   267  func Build(path string, dns, dnsSearch, dnsOptions []string) (*File, error) {
   268  	content := bytes.NewBuffer(nil)
   269  	if len(dnsSearch) > 0 {
   270  		if searchString := strings.Join(dnsSearch, " "); strings.Trim(searchString, " ") != "." {
   271  			if _, err := content.WriteString("search " + searchString + "\n"); err != nil {
   272  				return nil, err
   273  			}
   274  		}
   275  	}
   276  	for _, dns := range dns {
   277  		if _, err := content.WriteString("nameserver " + dns + "\n"); err != nil {
   278  			return nil, err
   279  		}
   280  	}
   281  	if len(dnsOptions) > 0 {
   282  		if optsString := strings.Join(dnsOptions, " "); strings.Trim(optsString, " ") != "" {
   283  			if _, err := content.WriteString("options " + optsString + "\n"); err != nil {
   284  				return nil, err
   285  			}
   286  		}
   287  	}
   288  
   289  	hash, err := hashData(bytes.NewReader(content.Bytes()))
   290  	if err != nil {
   291  		return nil, err
   292  	}
   293  
   294  	return &File{Content: content.Bytes(), Hash: hash}, os.WriteFile(path, content.Bytes(), 0644)
   295  }