resolvconf.go 10.0 KB

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