resolvconf.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. // Package resolvconf provides utility code to query and update DNS configuration in /etc/resolv.conf
  2. package resolvconf
  3. import (
  4. "bytes"
  5. "io/ioutil"
  6. "regexp"
  7. "strings"
  8. "sync"
  9. "github.com/Sirupsen/logrus"
  10. "github.com/docker/docker/pkg/ioutils"
  11. )
  12. var (
  13. // Note: the default IPv4 & IPv6 resolvers are set to Google's Public DNS
  14. defaultIPv4Dns = []string{"nameserver 8.8.8.8", "nameserver 8.8.4.4"}
  15. defaultIPv6Dns = []string{"nameserver 2001:4860:4860::8888", "nameserver 2001:4860:4860::8844"}
  16. ipv4NumBlock = `(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)`
  17. ipv4Address = `(` + ipv4NumBlock + `\.){3}` + ipv4NumBlock
  18. // This is not an IPv6 address verifier as it will accept a super-set of IPv6, and also
  19. // will *not match* IPv4-Embedded IPv6 Addresses (RFC6052), but that and other variants
  20. // -- e.g. other link-local types -- either won't work in containers or are unnecessary.
  21. // For readability and sufficiency for Docker purposes this seemed more reasonable than a
  22. // 1000+ character regexp with exact and complete IPv6 validation
  23. ipv6Address = `([0-9A-Fa-f]{0,4}:){2,7}([0-9A-Fa-f]{0,4})`
  24. ipLocalhost = `((127\.([0-9]{1,3}.){2}[0-9]{1,3})|(::1))`
  25. localhostIPRegexp = regexp.MustCompile(ipLocalhost)
  26. localhostNSRegexp = regexp.MustCompile(`(?m)^nameserver\s+` + ipLocalhost + `\s*\n*`)
  27. nsIPv6Regexp = regexp.MustCompile(`(?m)^nameserver\s+` + ipv6Address + `\s*\n*`)
  28. nsRegexp = regexp.MustCompile(`^\s*nameserver\s*((` + ipv4Address + `)|(` + ipv6Address + `))\s*$`)
  29. searchRegexp = regexp.MustCompile(`^\s*search\s*(([^\s]+\s*)*)$`)
  30. )
  31. var lastModified struct {
  32. sync.Mutex
  33. sha256 string
  34. contents []byte
  35. }
  36. // Get returns the contents of /etc/resolv.conf
  37. func Get() ([]byte, error) {
  38. resolv, err := ioutil.ReadFile("/etc/resolv.conf")
  39. if err != nil {
  40. return nil, err
  41. }
  42. return resolv, nil
  43. }
  44. // GetIfChanged retrieves the host /etc/resolv.conf file, checks against the last hash
  45. // and, if modified since last check, returns the bytes and new hash.
  46. // This feature is used by the resolv.conf updater for containers
  47. func GetIfChanged() ([]byte, string, error) {
  48. lastModified.Lock()
  49. defer lastModified.Unlock()
  50. resolv, err := ioutil.ReadFile("/etc/resolv.conf")
  51. if err != nil {
  52. return nil, "", err
  53. }
  54. newHash, err := ioutils.HashData(bytes.NewReader(resolv))
  55. if err != nil {
  56. return nil, "", err
  57. }
  58. if lastModified.sha256 != newHash {
  59. lastModified.sha256 = newHash
  60. lastModified.contents = resolv
  61. return resolv, newHash, nil
  62. }
  63. // nothing changed, so return no data
  64. return nil, "", nil
  65. }
  66. // GetLastModified retrieves the last used contents and hash of the host resolv.conf.
  67. // Used by containers updating on restart
  68. func GetLastModified() ([]byte, string) {
  69. lastModified.Lock()
  70. defer lastModified.Unlock()
  71. return lastModified.contents, lastModified.sha256
  72. }
  73. // FilterResolvDns cleans up the config in resolvConf. It has two main jobs:
  74. // 1. It looks for localhost (127.*|::1) entries in the provided
  75. // resolv.conf, removing local nameserver entries, and, if the resulting
  76. // cleaned config has no defined nameservers left, adds default DNS entries
  77. // 2. Given the caller provides the enable/disable state of IPv6, the filter
  78. // code will remove all IPv6 nameservers if it is not enabled for containers
  79. //
  80. // It returns a boolean to notify the caller if changes were made at all
  81. func FilterResolvDns(resolvConf []byte, ipv6Enabled bool) ([]byte, bool) {
  82. changed := false
  83. cleanedResolvConf := localhostNSRegexp.ReplaceAll(resolvConf, []byte{})
  84. // if IPv6 is not enabled, also clean out any IPv6 address nameserver
  85. if !ipv6Enabled {
  86. cleanedResolvConf = nsIPv6Regexp.ReplaceAll(cleanedResolvConf, []byte{})
  87. }
  88. // if the resulting resolvConf has no more nameservers defined, add appropriate
  89. // default DNS servers for IPv4 and (optionally) IPv6
  90. if len(GetNameservers(cleanedResolvConf)) == 0 {
  91. logrus.Infof("No non-localhost DNS nameservers are left in resolv.conf. Using default external servers : %v", defaultIPv4Dns)
  92. dns := defaultIPv4Dns
  93. if ipv6Enabled {
  94. logrus.Infof("IPv6 enabled; Adding default IPv6 external servers : %v", defaultIPv6Dns)
  95. dns = append(dns, defaultIPv6Dns...)
  96. }
  97. cleanedResolvConf = append(cleanedResolvConf, []byte("\n"+strings.Join(dns, "\n"))...)
  98. }
  99. if !bytes.Equal(resolvConf, cleanedResolvConf) {
  100. changed = true
  101. }
  102. return cleanedResolvConf, changed
  103. }
  104. // getLines parses input into lines and strips away comments.
  105. func getLines(input []byte, commentMarker []byte) [][]byte {
  106. lines := bytes.Split(input, []byte("\n"))
  107. var output [][]byte
  108. for _, currentLine := range lines {
  109. var commentIndex = bytes.Index(currentLine, commentMarker)
  110. if commentIndex == -1 {
  111. output = append(output, currentLine)
  112. } else {
  113. output = append(output, currentLine[:commentIndex])
  114. }
  115. }
  116. return output
  117. }
  118. // IsLocalhost returns true if ip matches the localhost IP regular expression.
  119. // Used for determining if nameserver settings are being passed which are
  120. // localhost addresses
  121. func IsLocalhost(ip string) bool {
  122. return localhostIPRegexp.MatchString(ip)
  123. }
  124. // GetNameservers returns nameservers (if any) listed in /etc/resolv.conf
  125. func GetNameservers(resolvConf []byte) []string {
  126. nameservers := []string{}
  127. for _, line := range getLines(resolvConf, []byte("#")) {
  128. var ns = nsRegexp.FindSubmatch(line)
  129. if len(ns) > 0 {
  130. nameservers = append(nameservers, string(ns[1]))
  131. }
  132. }
  133. return nameservers
  134. }
  135. // GetNameserversAsCIDR returns nameservers (if any) listed in
  136. // /etc/resolv.conf as CIDR blocks (e.g., "1.2.3.4/32")
  137. // This function's output is intended for net.ParseCIDR
  138. func GetNameserversAsCIDR(resolvConf []byte) []string {
  139. nameservers := []string{}
  140. for _, nameserver := range GetNameservers(resolvConf) {
  141. nameservers = append(nameservers, nameserver+"/32")
  142. }
  143. return nameservers
  144. }
  145. // GetSearchDomains returns search domains (if any) listed in /etc/resolv.conf
  146. // If more than one search line is encountered, only the contents of the last
  147. // one is returned.
  148. func GetSearchDomains(resolvConf []byte) []string {
  149. domains := []string{}
  150. for _, line := range getLines(resolvConf, []byte("#")) {
  151. match := searchRegexp.FindSubmatch(line)
  152. if match == nil {
  153. continue
  154. }
  155. domains = strings.Fields(string(match[1]))
  156. }
  157. return domains
  158. }
  159. // Build writes a configuration file to path containing a "nameserver" entry
  160. // for every element in dns, and a "search" entry for every element in
  161. // dnsSearch.
  162. func Build(path string, dns, dnsSearch []string) error {
  163. content := bytes.NewBuffer(nil)
  164. for _, dns := range dns {
  165. if _, err := content.WriteString("nameserver " + dns + "\n"); err != nil {
  166. return err
  167. }
  168. }
  169. if len(dnsSearch) > 0 {
  170. if searchString := strings.Join(dnsSearch, " "); strings.Trim(searchString, " ") != "." {
  171. if _, err := content.WriteString("search " + searchString + "\n"); err != nil {
  172. return err
  173. }
  174. }
  175. }
  176. return ioutil.WriteFile(path, content.Bytes(), 0644)
  177. }