sandbox_dns_unix.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. // +build !windows
  2. package libnetwork
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "path"
  8. "path/filepath"
  9. "strconv"
  10. "strings"
  11. "github.com/docker/libnetwork/etchosts"
  12. "github.com/docker/libnetwork/resolvconf"
  13. "github.com/docker/libnetwork/resolvconf/dns"
  14. "github.com/docker/libnetwork/types"
  15. "github.com/sirupsen/logrus"
  16. )
  17. const (
  18. defaultPrefix = "/var/lib/docker/network/files"
  19. dirPerm = 0755
  20. filePerm = 0644
  21. )
  22. func (sb *sandbox) startResolver(restore bool) {
  23. sb.resolverOnce.Do(func() {
  24. var err error
  25. sb.resolver = NewResolver(resolverIPSandbox, true, sb.Key(), sb)
  26. defer func() {
  27. if err != nil {
  28. sb.resolver = nil
  29. }
  30. }()
  31. // In the case of live restore container is already running with
  32. // right resolv.conf contents created before. Just update the
  33. // external DNS servers from the restored sandbox for embedded
  34. // server to use.
  35. if !restore {
  36. err = sb.rebuildDNS()
  37. if err != nil {
  38. logrus.Errorf("Updating resolv.conf failed for container %s, %q", sb.ContainerID(), err)
  39. return
  40. }
  41. }
  42. sb.resolver.SetExtServers(sb.extDNS)
  43. if err = sb.osSbox.InvokeFunc(sb.resolver.SetupFunc(0)); err != nil {
  44. logrus.Errorf("Resolver Setup function failed for container %s, %q", sb.ContainerID(), err)
  45. return
  46. }
  47. if err = sb.resolver.Start(); err != nil {
  48. logrus.Errorf("Resolver Start failed for container %s, %q", sb.ContainerID(), err)
  49. }
  50. })
  51. }
  52. func (sb *sandbox) setupResolutionFiles() error {
  53. if err := sb.buildHostsFile(); err != nil {
  54. return err
  55. }
  56. if err := sb.updateParentHosts(); err != nil {
  57. return err
  58. }
  59. return sb.setupDNS()
  60. }
  61. func (sb *sandbox) buildHostsFile() error {
  62. if sb.config.hostsPath == "" {
  63. sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
  64. }
  65. dir, _ := filepath.Split(sb.config.hostsPath)
  66. if err := createBasePath(dir); err != nil {
  67. return err
  68. }
  69. // This is for the host mode networking
  70. if sb.config.useDefaultSandBox && len(sb.config.extraHosts) == 0 {
  71. // We are working under the assumption that the origin file option had been properly expressed by the upper layer
  72. // if not here we are going to error out
  73. if err := copyFile(sb.config.originHostsPath, sb.config.hostsPath); err != nil && !os.IsNotExist(err) {
  74. return types.InternalErrorf("could not copy source hosts file %s to %s: %v", sb.config.originHostsPath, sb.config.hostsPath, err)
  75. }
  76. return nil
  77. }
  78. extraContent := make([]etchosts.Record, 0, len(sb.config.extraHosts))
  79. for _, extraHost := range sb.config.extraHosts {
  80. extraContent = append(extraContent, etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
  81. }
  82. return etchosts.Build(sb.config.hostsPath, "", sb.config.hostName, sb.config.domainName, extraContent)
  83. }
  84. func (sb *sandbox) updateHostsFile(ifaceIP string) error {
  85. if ifaceIP == "" {
  86. return nil
  87. }
  88. if sb.config.originHostsPath != "" {
  89. return nil
  90. }
  91. // User might have provided a FQDN in hostname or split it across hostname
  92. // and domainname. We want the FQDN and the bare hostname.
  93. fqdn := sb.config.hostName
  94. mhost := sb.config.hostName
  95. if sb.config.domainName != "" {
  96. fqdn = fmt.Sprintf("%s.%s", fqdn, sb.config.domainName)
  97. }
  98. parts := strings.SplitN(fqdn, ".", 2)
  99. if len(parts) == 2 {
  100. mhost = fmt.Sprintf("%s %s", fqdn, parts[0])
  101. }
  102. extraContent := []etchosts.Record{{Hosts: mhost, IP: ifaceIP}}
  103. sb.addHostsEntries(extraContent)
  104. return nil
  105. }
  106. func (sb *sandbox) addHostsEntries(recs []etchosts.Record) {
  107. if err := etchosts.Add(sb.config.hostsPath, recs); err != nil {
  108. logrus.Warnf("Failed adding service host entries to the running container: %v", err)
  109. }
  110. }
  111. func (sb *sandbox) deleteHostsEntries(recs []etchosts.Record) {
  112. if err := etchosts.Delete(sb.config.hostsPath, recs); err != nil {
  113. logrus.Warnf("Failed deleting service host entries to the running container: %v", err)
  114. }
  115. }
  116. func (sb *sandbox) updateParentHosts() error {
  117. var pSb Sandbox
  118. for _, update := range sb.config.parentUpdates {
  119. sb.controller.WalkSandboxes(SandboxContainerWalker(&pSb, update.cid))
  120. if pSb == nil {
  121. continue
  122. }
  123. if err := etchosts.Update(pSb.(*sandbox).config.hostsPath, update.ip, update.name); err != nil {
  124. return err
  125. }
  126. }
  127. return nil
  128. }
  129. func (sb *sandbox) restorePath() {
  130. if sb.config.resolvConfPath == "" {
  131. sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
  132. }
  133. sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
  134. if sb.config.hostsPath == "" {
  135. sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
  136. }
  137. }
  138. func (sb *sandbox) setExternalResolvers(content []byte, addrType int, checkLoopback bool) {
  139. servers := resolvconf.GetNameservers(content, addrType)
  140. for _, ip := range servers {
  141. hostLoopback := false
  142. if checkLoopback {
  143. hostLoopback = dns.IsIPv4Localhost(ip)
  144. }
  145. sb.extDNS = append(sb.extDNS, extDNSEntry{
  146. IPStr: ip,
  147. HostLoopback: hostLoopback,
  148. })
  149. }
  150. }
  151. func (sb *sandbox) setupDNS() error {
  152. var newRC *resolvconf.File
  153. if sb.config.resolvConfPath == "" {
  154. sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
  155. }
  156. sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
  157. dir, _ := filepath.Split(sb.config.resolvConfPath)
  158. if err := createBasePath(dir); err != nil {
  159. return err
  160. }
  161. // When the user specify a conainter in the host namespace and do no have any dns option specified
  162. // we just copy the host resolv.conf from the host itself
  163. if sb.config.useDefaultSandBox &&
  164. len(sb.config.dnsList) == 0 && len(sb.config.dnsSearchList) == 0 && len(sb.config.dnsOptionsList) == 0 {
  165. // We are working under the assumption that the origin file option had been properly expressed by the upper layer
  166. // if not here we are going to error out
  167. if err := copyFile(sb.config.originResolvConfPath, sb.config.resolvConfPath); err != nil {
  168. if !os.IsNotExist(err) {
  169. return fmt.Errorf("could not copy source resolv.conf file %s to %s: %v", sb.config.originResolvConfPath, sb.config.resolvConfPath, err)
  170. }
  171. logrus.Infof("%s does not exist, we create an empty resolv.conf for container", sb.config.originResolvConfPath)
  172. if err := createFile(sb.config.resolvConfPath); err != nil {
  173. return err
  174. }
  175. }
  176. return nil
  177. }
  178. originResolvConfPath := sb.config.originResolvConfPath
  179. if originResolvConfPath == "" {
  180. // fallback if not specified
  181. originResolvConfPath = resolvconf.Path()
  182. }
  183. currRC, err := resolvconf.GetSpecific(originResolvConfPath)
  184. if err != nil {
  185. if !os.IsNotExist(err) {
  186. return err
  187. }
  188. // it's ok to continue if /etc/resolv.conf doesn't exist, default resolvers (Google's Public DNS)
  189. // will be used
  190. currRC = &resolvconf.File{}
  191. logrus.Infof("/etc/resolv.conf does not exist")
  192. }
  193. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  194. var (
  195. err error
  196. dnsList = resolvconf.GetNameservers(currRC.Content, types.IP)
  197. dnsSearchList = resolvconf.GetSearchDomains(currRC.Content)
  198. dnsOptionsList = resolvconf.GetOptions(currRC.Content)
  199. )
  200. if len(sb.config.dnsList) > 0 {
  201. dnsList = sb.config.dnsList
  202. }
  203. if len(sb.config.dnsSearchList) > 0 {
  204. dnsSearchList = sb.config.dnsSearchList
  205. }
  206. if len(sb.config.dnsOptionsList) > 0 {
  207. dnsOptionsList = sb.config.dnsOptionsList
  208. }
  209. newRC, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
  210. if err != nil {
  211. return err
  212. }
  213. // After building the resolv.conf from the user config save the
  214. // external resolvers in the sandbox. Note that --dns 127.0.0.x
  215. // config refers to the loopback in the container namespace
  216. sb.setExternalResolvers(newRC.Content, types.IPv4, false)
  217. } else {
  218. // If the host resolv.conf file has 127.0.0.x container should
  219. // use the host resolver for queries. This is supported by the
  220. // docker embedded DNS server. Hence save the external resolvers
  221. // before filtering it out.
  222. sb.setExternalResolvers(currRC.Content, types.IPv4, true)
  223. // Replace any localhost/127.* (at this point we have no info about ipv6, pass it as true)
  224. if newRC, err = resolvconf.FilterResolvDNS(currRC.Content, true); err != nil {
  225. return err
  226. }
  227. // No contention on container resolv.conf file at sandbox creation
  228. if err := ioutil.WriteFile(sb.config.resolvConfPath, newRC.Content, filePerm); err != nil {
  229. return types.InternalErrorf("failed to write unhaltered resolv.conf file content when setting up dns for sandbox %s: %v", sb.ID(), err)
  230. }
  231. }
  232. // Write hash
  233. if err := ioutil.WriteFile(sb.config.resolvConfHashFile, []byte(newRC.Hash), filePerm); err != nil {
  234. return types.InternalErrorf("failed to write resolv.conf hash file when setting up dns for sandbox %s: %v", sb.ID(), err)
  235. }
  236. return nil
  237. }
  238. func (sb *sandbox) updateDNS(ipv6Enabled bool) error {
  239. var (
  240. currHash string
  241. hashFile = sb.config.resolvConfHashFile
  242. )
  243. // This is for the host mode networking
  244. if sb.config.useDefaultSandBox {
  245. return nil
  246. }
  247. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  248. return nil
  249. }
  250. currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
  251. if err != nil {
  252. if !os.IsNotExist(err) {
  253. return err
  254. }
  255. } else {
  256. h, err := ioutil.ReadFile(hashFile)
  257. if err != nil {
  258. if !os.IsNotExist(err) {
  259. return err
  260. }
  261. } else {
  262. currHash = string(h)
  263. }
  264. }
  265. if currHash != "" && currHash != currRC.Hash {
  266. // Seems the user has changed the container resolv.conf since the last time
  267. // we checked so return without doing anything.
  268. //logrus.Infof("Skipping update of resolv.conf file with ipv6Enabled: %t because file was touched by user", ipv6Enabled)
  269. return nil
  270. }
  271. // replace any localhost/127.* and remove IPv6 nameservers if IPv6 disabled.
  272. newRC, err := resolvconf.FilterResolvDNS(currRC.Content, ipv6Enabled)
  273. if err != nil {
  274. return err
  275. }
  276. err = ioutil.WriteFile(sb.config.resolvConfPath, newRC.Content, 0644)
  277. if err != nil {
  278. return err
  279. }
  280. // write the new hash in a temp file and rename it to make the update atomic
  281. dir := path.Dir(sb.config.resolvConfPath)
  282. tmpHashFile, err := ioutil.TempFile(dir, "hash")
  283. if err != nil {
  284. return err
  285. }
  286. if err = tmpHashFile.Chmod(filePerm); err != nil {
  287. tmpHashFile.Close()
  288. return err
  289. }
  290. _, err = tmpHashFile.Write([]byte(newRC.Hash))
  291. if err1 := tmpHashFile.Close(); err == nil {
  292. err = err1
  293. }
  294. if err != nil {
  295. return err
  296. }
  297. return os.Rename(tmpHashFile.Name(), hashFile)
  298. }
  299. // Embedded DNS server has to be enabled for this sandbox. Rebuild the container's
  300. // resolv.conf by doing the following
  301. // - Add only the embedded server's IP to container's resolv.conf
  302. // - If the embedded server needs any resolv.conf options add it to the current list
  303. func (sb *sandbox) rebuildDNS() error {
  304. currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
  305. if err != nil {
  306. return err
  307. }
  308. if len(sb.extDNS) == 0 {
  309. sb.setExternalResolvers(currRC.Content, types.IPv4, false)
  310. }
  311. var (
  312. dnsList = []string{sb.resolver.NameServer()}
  313. dnsOptionsList = resolvconf.GetOptions(currRC.Content)
  314. dnsSearchList = resolvconf.GetSearchDomains(currRC.Content)
  315. )
  316. // external v6 DNS servers has to be listed in resolv.conf
  317. dnsList = append(dnsList, resolvconf.GetNameservers(currRC.Content, types.IPv6)...)
  318. // If the user config and embedded DNS server both have ndots option set,
  319. // remember the user's config so that unqualified names not in the docker
  320. // domain can be dropped.
  321. resOptions := sb.resolver.ResolverOptions()
  322. dnsOpt:
  323. for _, resOpt := range resOptions {
  324. if strings.Contains(resOpt, "ndots") {
  325. for _, option := range dnsOptionsList {
  326. if strings.Contains(option, "ndots") {
  327. parts := strings.Split(option, ":")
  328. if len(parts) != 2 {
  329. return fmt.Errorf("invalid ndots option %v", option)
  330. }
  331. if num, err := strconv.Atoi(parts[1]); err != nil {
  332. return fmt.Errorf("invalid number for ndots option: %v", parts[1])
  333. } else if num >= 0 {
  334. // if the user sets ndots, use the user setting
  335. sb.ndotsSet = true
  336. break dnsOpt
  337. } else {
  338. return fmt.Errorf("invalid number for ndots option: %v", num)
  339. }
  340. }
  341. }
  342. }
  343. }
  344. if !sb.ndotsSet {
  345. // if the user did not set the ndots, set it to 0 to prioritize the service name resolution
  346. // Ref: https://linux.die.net/man/5/resolv.conf
  347. dnsOptionsList = append(dnsOptionsList, resOptions...)
  348. }
  349. _, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
  350. return err
  351. }
  352. func createBasePath(dir string) error {
  353. return os.MkdirAll(dir, dirPerm)
  354. }
  355. func createFile(path string) error {
  356. var f *os.File
  357. dir, _ := filepath.Split(path)
  358. err := createBasePath(dir)
  359. if err != nil {
  360. return err
  361. }
  362. f, err = os.Create(path)
  363. if err == nil {
  364. f.Close()
  365. }
  366. return err
  367. }
  368. func copyFile(src, dst string) error {
  369. sBytes, err := ioutil.ReadFile(src)
  370. if err != nil {
  371. return err
  372. }
  373. return ioutil.WriteFile(dst, sBytes, filePerm)
  374. }