resolvconf.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. package resolvconf
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "regexp"
  6. "strings"
  7. "sync"
  8. log "github.com/Sirupsen/logrus"
  9. "github.com/docker/docker/utils"
  10. )
  11. var (
  12. defaultDns = []string{"8.8.8.8", "8.8.4.4"}
  13. localHostRegexp = regexp.MustCompile(`(?m)^nameserver 127[^\n]+\n*`)
  14. nsRegexp = regexp.MustCompile(`^\s*nameserver\s*(([0-9]+\.){3}([0-9]+))\s*$`)
  15. searchRegexp = regexp.MustCompile(`^\s*search\s*(([^\s]+\s*)*)$`)
  16. )
  17. var lastModified struct {
  18. sync.Mutex
  19. sha256 string
  20. contents []byte
  21. }
  22. func Get() ([]byte, error) {
  23. resolv, err := ioutil.ReadFile("/etc/resolv.conf")
  24. if err != nil {
  25. return nil, err
  26. }
  27. return resolv, nil
  28. }
  29. // Retrieves the host /etc/resolv.conf file, checks against the last hash
  30. // and, if modified since last check, returns the bytes and new hash.
  31. // This feature is used by the resolv.conf updater for containers
  32. func GetIfChanged() ([]byte, string, error) {
  33. lastModified.Lock()
  34. defer lastModified.Unlock()
  35. resolv, err := ioutil.ReadFile("/etc/resolv.conf")
  36. if err != nil {
  37. return nil, "", err
  38. }
  39. newHash, err := utils.HashData(bytes.NewReader(resolv))
  40. if err != nil {
  41. return nil, "", err
  42. }
  43. if lastModified.sha256 != newHash {
  44. lastModified.sha256 = newHash
  45. lastModified.contents = resolv
  46. return resolv, newHash, nil
  47. }
  48. // nothing changed, so return no data
  49. return nil, "", nil
  50. }
  51. // retrieve the last used contents and hash of the host resolv.conf
  52. // Used by containers updating on restart
  53. func GetLastModified() ([]byte, string) {
  54. lastModified.Lock()
  55. defer lastModified.Unlock()
  56. return lastModified.contents, lastModified.sha256
  57. }
  58. // RemoveReplaceLocalDns looks for localhost (127.*) entries in the provided
  59. // resolv.conf, removing local nameserver entries, and, if the resulting
  60. // cleaned config has no defined nameservers left, adds default DNS entries
  61. // It also returns a boolean to notify the caller if changes were made at all
  62. func RemoveReplaceLocalDns(resolvConf []byte) ([]byte, bool) {
  63. changed := false
  64. cleanedResolvConf := localHostRegexp.ReplaceAll(resolvConf, []byte{})
  65. // if the resulting resolvConf is empty, use defaultDns
  66. if !bytes.Contains(cleanedResolvConf, []byte("nameserver")) {
  67. log.Infof("No non-localhost DNS nameservers are left in resolv.conf. Using default external servers : %v", defaultDns)
  68. cleanedResolvConf = append(cleanedResolvConf, []byte("\nnameserver "+strings.Join(defaultDns, "\nnameserver "))...)
  69. }
  70. if !bytes.Equal(resolvConf, cleanedResolvConf) {
  71. changed = true
  72. }
  73. return cleanedResolvConf, changed
  74. }
  75. // getLines parses input into lines and strips away comments.
  76. func getLines(input []byte, commentMarker []byte) [][]byte {
  77. lines := bytes.Split(input, []byte("\n"))
  78. var output [][]byte
  79. for _, currentLine := range lines {
  80. var commentIndex = bytes.Index(currentLine, commentMarker)
  81. if commentIndex == -1 {
  82. output = append(output, currentLine)
  83. } else {
  84. output = append(output, currentLine[:commentIndex])
  85. }
  86. }
  87. return output
  88. }
  89. // GetNameservers returns nameservers (if any) listed in /etc/resolv.conf
  90. func GetNameservers(resolvConf []byte) []string {
  91. nameservers := []string{}
  92. for _, line := range getLines(resolvConf, []byte("#")) {
  93. var ns = nsRegexp.FindSubmatch(line)
  94. if len(ns) > 0 {
  95. nameservers = append(nameservers, string(ns[1]))
  96. }
  97. }
  98. return nameservers
  99. }
  100. // GetNameserversAsCIDR returns nameservers (if any) listed in
  101. // /etc/resolv.conf as CIDR blocks (e.g., "1.2.3.4/32")
  102. // This function's output is intended for net.ParseCIDR
  103. func GetNameserversAsCIDR(resolvConf []byte) []string {
  104. nameservers := []string{}
  105. for _, nameserver := range GetNameservers(resolvConf) {
  106. nameservers = append(nameservers, nameserver+"/32")
  107. }
  108. return nameservers
  109. }
  110. // GetSearchDomains returns search domains (if any) listed in /etc/resolv.conf
  111. // If more than one search line is encountered, only the contents of the last
  112. // one is returned.
  113. func GetSearchDomains(resolvConf []byte) []string {
  114. domains := []string{}
  115. for _, line := range getLines(resolvConf, []byte("#")) {
  116. match := searchRegexp.FindSubmatch(line)
  117. if match == nil {
  118. continue
  119. }
  120. domains = strings.Fields(string(match[1]))
  121. }
  122. return domains
  123. }
  124. func Build(path string, dns, dnsSearch []string) error {
  125. content := bytes.NewBuffer(nil)
  126. for _, dns := range dns {
  127. if _, err := content.WriteString("nameserver " + dns + "\n"); err != nil {
  128. return err
  129. }
  130. }
  131. if len(dnsSearch) > 0 {
  132. if searchString := strings.Join(dnsSearch, " "); strings.Trim(searchString, " ") != "." {
  133. if _, err := content.WriteString("search " + searchString + "\n"); err != nil {
  134. return err
  135. }
  136. }
  137. }
  138. return ioutil.WriteFile(path, content.Bytes(), 0644)
  139. }