resolvconf.go 8.6 KB

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