resolvconf.go 6.5 KB

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