resolvconf.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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/libnetwork/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. optionsRegexp = regexp.MustCompile(`^\s*options\s*(([^\s]+\s*)*)$`)
  30. )
  31. var lastModified struct {
  32. sync.Mutex
  33. sha256 string
  34. contents []byte
  35. }
  36. // File contains the resolv.conf content and its hash
  37. type File struct {
  38. Content []byte
  39. Hash string
  40. }
  41. // Get returns the contents of /etc/resolv.conf and its hash
  42. func Get() (*File, error) {
  43. resolv, err := ioutil.ReadFile("/etc/resolv.conf")
  44. if err != nil {
  45. return nil, err
  46. }
  47. hash, err := ioutils.HashData(bytes.NewReader(resolv))
  48. if err != nil {
  49. return nil, err
  50. }
  51. return &File{Content: resolv, Hash: hash}, nil
  52. }
  53. // GetSpecific returns the contents of the user specified resolv.conf file and its hash
  54. func GetSpecific(path string) (*File, error) {
  55. resolv, err := ioutil.ReadFile(path)
  56. if err != nil {
  57. return nil, err
  58. }
  59. hash, err := ioutils.HashData(bytes.NewReader(resolv))
  60. if err != nil {
  61. return nil, err
  62. }
  63. return &File{Content: resolv, Hash: hash}, nil
  64. }
  65. // GetIfChanged retrieves the host /etc/resolv.conf file, checks against the last hash
  66. // and, if modified since last check, returns the bytes and new hash.
  67. // This feature is used by the resolv.conf updater for containers
  68. func GetIfChanged() (*File, error) {
  69. lastModified.Lock()
  70. defer lastModified.Unlock()
  71. resolv, err := ioutil.ReadFile("/etc/resolv.conf")
  72. if err != nil {
  73. return nil, err
  74. }
  75. newHash, err := ioutils.HashData(bytes.NewReader(resolv))
  76. if err != nil {
  77. return nil, err
  78. }
  79. if lastModified.sha256 != newHash {
  80. lastModified.sha256 = newHash
  81. lastModified.contents = resolv
  82. return &File{Content: resolv, Hash: newHash}, nil
  83. }
  84. // nothing changed, so return no data
  85. return nil, nil
  86. }
  87. // GetLastModified retrieves the last used contents and hash of the host resolv.conf.
  88. // Used by containers updating on restart
  89. func GetLastModified() *File {
  90. lastModified.Lock()
  91. defer lastModified.Unlock()
  92. return &File{Content: lastModified.contents, Hash: lastModified.sha256}
  93. }
  94. // FilterResolvDNS cleans up the config in resolvConf. It has two main jobs:
  95. // 1. It looks for localhost (127.*|::1) entries in the provided
  96. // resolv.conf, removing local nameserver entries, and, if the resulting
  97. // cleaned config has no defined nameservers left, adds default DNS entries
  98. // 2. Given the caller provides the enable/disable state of IPv6, the filter
  99. // code will remove all IPv6 nameservers if it is not enabled for containers
  100. //
  101. func FilterResolvDNS(resolvConf []byte, ipv6Enabled bool) (*File, error) {
  102. cleanedResolvConf := localhostNSRegexp.ReplaceAll(resolvConf, []byte{})
  103. // if IPv6 is not enabled, also clean out any IPv6 address nameserver
  104. if !ipv6Enabled {
  105. cleanedResolvConf = nsIPv6Regexp.ReplaceAll(cleanedResolvConf, []byte{})
  106. }
  107. // if the resulting resolvConf has no more nameservers defined, add appropriate
  108. // default DNS servers for IPv4 and (optionally) IPv6
  109. if len(GetNameservers(cleanedResolvConf)) == 0 {
  110. logrus.Infof("No non-localhost DNS nameservers are left in resolv.conf. Using default external servers : %v", defaultIPv4Dns)
  111. dns := defaultIPv4Dns
  112. if ipv6Enabled {
  113. logrus.Infof("IPv6 enabled; Adding default IPv6 external servers : %v", defaultIPv6Dns)
  114. dns = append(dns, defaultIPv6Dns...)
  115. }
  116. cleanedResolvConf = append(cleanedResolvConf, []byte("\n"+strings.Join(dns, "\n"))...)
  117. }
  118. hash, err := ioutils.HashData(bytes.NewReader(cleanedResolvConf))
  119. if err != nil {
  120. return nil, err
  121. }
  122. return &File{Content: cleanedResolvConf, Hash: hash}, nil
  123. }
  124. // getLines parses input into lines and strips away comments.
  125. func getLines(input []byte, commentMarker []byte) [][]byte {
  126. lines := bytes.Split(input, []byte("\n"))
  127. var output [][]byte
  128. for _, currentLine := range lines {
  129. var commentIndex = bytes.Index(currentLine, commentMarker)
  130. if commentIndex == -1 {
  131. output = append(output, currentLine)
  132. } else {
  133. output = append(output, currentLine[:commentIndex])
  134. }
  135. }
  136. return output
  137. }
  138. // GetNameservers returns nameservers (if any) listed in /etc/resolv.conf
  139. func GetNameservers(resolvConf []byte) []string {
  140. nameservers := []string{}
  141. for _, line := range getLines(resolvConf, []byte("#")) {
  142. var ns = nsRegexp.FindSubmatch(line)
  143. if len(ns) > 0 {
  144. nameservers = append(nameservers, string(ns[1]))
  145. }
  146. }
  147. return nameservers
  148. }
  149. // GetNameserversAsCIDR returns nameservers (if any) listed in
  150. // /etc/resolv.conf as CIDR blocks (e.g., "1.2.3.4/32")
  151. // This function's output is intended for net.ParseCIDR
  152. func GetNameserversAsCIDR(resolvConf []byte) []string {
  153. nameservers := []string{}
  154. for _, nameserver := range GetNameservers(resolvConf) {
  155. nameservers = append(nameservers, nameserver+"/32")
  156. }
  157. return nameservers
  158. }
  159. // GetSearchDomains returns search domains (if any) listed in /etc/resolv.conf
  160. // If more than one search line is encountered, only the contents of the last
  161. // one is returned.
  162. func GetSearchDomains(resolvConf []byte) []string {
  163. domains := []string{}
  164. for _, line := range getLines(resolvConf, []byte("#")) {
  165. match := searchRegexp.FindSubmatch(line)
  166. if match == nil {
  167. continue
  168. }
  169. domains = strings.Fields(string(match[1]))
  170. }
  171. return domains
  172. }
  173. // GetOptions returns options (if any) listed in /etc/resolv.conf
  174. // If more than one options line is encountered, only the contents of the last
  175. // one is returned.
  176. func GetOptions(resolvConf []byte) []string {
  177. options := []string{}
  178. for _, line := range getLines(resolvConf, []byte("#")) {
  179. match := optionsRegexp.FindSubmatch(line)
  180. if match == nil {
  181. continue
  182. }
  183. options = strings.Fields(string(match[1]))
  184. }
  185. return options
  186. }
  187. // Build writes a configuration file to path containing a "nameserver" entry
  188. // for every element in dns, a "search" entry for every element in
  189. // dnsSearch, and an "options" entry for every element in dnsOptions.
  190. func Build(path string, dns, dnsSearch, dnsOptions []string) (*File, error) {
  191. content := bytes.NewBuffer(nil)
  192. if len(dnsSearch) > 0 {
  193. if searchString := strings.Join(dnsSearch, " "); strings.Trim(searchString, " ") != "." {
  194. if _, err := content.WriteString("search " + searchString + "\n"); err != nil {
  195. return nil, err
  196. }
  197. }
  198. }
  199. for _, dns := range dns {
  200. if _, err := content.WriteString("nameserver " + dns + "\n"); err != nil {
  201. return nil, err
  202. }
  203. }
  204. if len(dnsOptions) > 0 {
  205. if optsString := strings.Join(dnsOptions, " "); strings.Trim(optsString, " ") != "" {
  206. if _, err := content.WriteString("options " + optsString + "\n"); err != nil {
  207. return nil, err
  208. }
  209. }
  210. }
  211. hash, err := ioutils.HashData(bytes.NewReader(content.Bytes()))
  212. if err != nil {
  213. return nil, err
  214. }
  215. return &File{Content: content.Bytes(), Hash: hash}, ioutil.WriteFile(path, content.Bytes(), 0644)
  216. }