resolvconf.go 10 KB

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