sandbox_dns_unix.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. //go:build !windows
  2. // +build !windows
  3. package libnetwork
  4. import (
  5. "fmt"
  6. "net"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "github.com/docker/docker/libnetwork/etchosts"
  13. "github.com/docker/docker/libnetwork/resolvconf"
  14. "github.com/docker/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(ifaceIPs []string) error {
  85. if len(ifaceIPs) == 0 {
  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. var extraContent []etchosts.Record
  103. for _, ip := range ifaceIPs {
  104. extraContent = append(extraContent, etchosts.Record{Hosts: mhost, IP: ip})
  105. }
  106. sb.addHostsEntries(extraContent)
  107. return nil
  108. }
  109. func (sb *sandbox) addHostsEntries(recs []etchosts.Record) {
  110. if err := etchosts.Add(sb.config.hostsPath, recs); err != nil {
  111. logrus.Warnf("Failed adding service host entries to the running container: %v", err)
  112. }
  113. }
  114. func (sb *sandbox) deleteHostsEntries(recs []etchosts.Record) {
  115. if err := etchosts.Delete(sb.config.hostsPath, recs); err != nil {
  116. logrus.Warnf("Failed deleting service host entries to the running container: %v", err)
  117. }
  118. }
  119. func (sb *sandbox) updateParentHosts() error {
  120. var pSb Sandbox
  121. for _, update := range sb.config.parentUpdates {
  122. sb.controller.WalkSandboxes(SandboxContainerWalker(&pSb, update.cid))
  123. if pSb == nil {
  124. continue
  125. }
  126. if err := etchosts.Update(pSb.(*sandbox).config.hostsPath, update.ip, update.name); err != nil {
  127. return err
  128. }
  129. }
  130. return nil
  131. }
  132. func (sb *sandbox) restorePath() {
  133. if sb.config.resolvConfPath == "" {
  134. sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
  135. }
  136. sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
  137. if sb.config.hostsPath == "" {
  138. sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
  139. }
  140. }
  141. func (sb *sandbox) setExternalResolvers(content []byte, addrType int, checkLoopback bool) {
  142. servers := resolvconf.GetNameservers(content, addrType)
  143. for _, ip := range servers {
  144. hostLoopback := false
  145. if checkLoopback && isIPv4Loopback(ip) {
  146. hostLoopback = true
  147. }
  148. sb.extDNS = append(sb.extDNS, extDNSEntry{
  149. IPStr: ip,
  150. HostLoopback: hostLoopback,
  151. })
  152. }
  153. }
  154. // isIPv4Loopback checks if the given IP address is an IPv4 loopback address.
  155. // It's based on the logic in Go's net.IP.IsLoopback(), but only the IPv4 part:
  156. // https://github.com/golang/go/blob/go1.16.6/src/net/ip.go#L120-L126
  157. func isIPv4Loopback(ipAddress string) bool {
  158. if ip := net.ParseIP(ipAddress); ip != nil {
  159. if ip4 := ip.To4(); ip4 != nil {
  160. return ip4[0] == 127
  161. }
  162. }
  163. return false
  164. }
  165. func (sb *sandbox) setupDNS() error {
  166. var newRC *resolvconf.File
  167. if sb.config.resolvConfPath == "" {
  168. sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
  169. }
  170. sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
  171. dir, _ := filepath.Split(sb.config.resolvConfPath)
  172. if err := createBasePath(dir); err != nil {
  173. return err
  174. }
  175. // When the user specify a conainter in the host namespace and do no have any dns option specified
  176. // we just copy the host resolv.conf from the host itself
  177. if sb.config.useDefaultSandBox &&
  178. len(sb.config.dnsList) == 0 && len(sb.config.dnsSearchList) == 0 && len(sb.config.dnsOptionsList) == 0 {
  179. // We are working under the assumption that the origin file option had been properly expressed by the upper layer
  180. // if not here we are going to error out
  181. if err := copyFile(sb.config.originResolvConfPath, sb.config.resolvConfPath); err != nil {
  182. if !os.IsNotExist(err) {
  183. return fmt.Errorf("could not copy source resolv.conf file %s to %s: %v", sb.config.originResolvConfPath, sb.config.resolvConfPath, err)
  184. }
  185. logrus.Infof("%s does not exist, we create an empty resolv.conf for container", sb.config.originResolvConfPath)
  186. if err := createFile(sb.config.resolvConfPath); err != nil {
  187. return err
  188. }
  189. }
  190. return nil
  191. }
  192. originResolvConfPath := sb.config.originResolvConfPath
  193. if originResolvConfPath == "" {
  194. // fallback if not specified
  195. originResolvConfPath = resolvconf.Path()
  196. }
  197. currRC, err := resolvconf.GetSpecific(originResolvConfPath)
  198. if err != nil {
  199. if !os.IsNotExist(err) {
  200. return err
  201. }
  202. // it's ok to continue if /etc/resolv.conf doesn't exist, default resolvers (Google's Public DNS)
  203. // will be used
  204. currRC = &resolvconf.File{}
  205. logrus.Infof("/etc/resolv.conf does not exist")
  206. }
  207. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  208. var (
  209. err error
  210. dnsList = resolvconf.GetNameservers(currRC.Content, resolvconf.IP)
  211. dnsSearchList = resolvconf.GetSearchDomains(currRC.Content)
  212. dnsOptionsList = resolvconf.GetOptions(currRC.Content)
  213. )
  214. if len(sb.config.dnsList) > 0 {
  215. dnsList = sb.config.dnsList
  216. }
  217. if len(sb.config.dnsSearchList) > 0 {
  218. dnsSearchList = sb.config.dnsSearchList
  219. }
  220. if len(sb.config.dnsOptionsList) > 0 {
  221. dnsOptionsList = sb.config.dnsOptionsList
  222. }
  223. newRC, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
  224. if err != nil {
  225. return err
  226. }
  227. // After building the resolv.conf from the user config save the
  228. // external resolvers in the sandbox. Note that --dns 127.0.0.x
  229. // config refers to the loopback in the container namespace
  230. sb.setExternalResolvers(newRC.Content, resolvconf.IPv4, false)
  231. } else {
  232. // If the host resolv.conf file has 127.0.0.x container should
  233. // use the host resolver for queries. This is supported by the
  234. // docker embedded DNS server. Hence save the external resolvers
  235. // before filtering it out.
  236. sb.setExternalResolvers(currRC.Content, resolvconf.IPv4, true)
  237. // Replace any localhost/127.* (at this point we have no info about ipv6, pass it as true)
  238. if newRC, err = resolvconf.FilterResolvDNS(currRC.Content, true); err != nil {
  239. return err
  240. }
  241. // No contention on container resolv.conf file at sandbox creation
  242. if err := os.WriteFile(sb.config.resolvConfPath, newRC.Content, filePerm); err != nil {
  243. return types.InternalErrorf("failed to write unhaltered resolv.conf file content when setting up dns for sandbox %s: %v", sb.ID(), err)
  244. }
  245. }
  246. // Write hash
  247. if err := os.WriteFile(sb.config.resolvConfHashFile, []byte(newRC.Hash), filePerm); err != nil {
  248. return types.InternalErrorf("failed to write resolv.conf hash file when setting up dns for sandbox %s: %v", sb.ID(), err)
  249. }
  250. return nil
  251. }
  252. func (sb *sandbox) updateDNS(ipv6Enabled bool) error {
  253. var (
  254. currHash string
  255. hashFile = sb.config.resolvConfHashFile
  256. )
  257. // This is for the host mode networking
  258. if sb.config.useDefaultSandBox {
  259. return nil
  260. }
  261. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  262. return nil
  263. }
  264. currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
  265. if err != nil {
  266. if !os.IsNotExist(err) {
  267. return err
  268. }
  269. } else {
  270. h, err := os.ReadFile(hashFile)
  271. if err != nil {
  272. if !os.IsNotExist(err) {
  273. return err
  274. }
  275. } else {
  276. currHash = string(h)
  277. }
  278. }
  279. if currHash != "" && currHash != currRC.Hash {
  280. // Seems the user has changed the container resolv.conf since the last time
  281. // we checked so return without doing anything.
  282. //logrus.Infof("Skipping update of resolv.conf file with ipv6Enabled: %t because file was touched by user", ipv6Enabled)
  283. return nil
  284. }
  285. // replace any localhost/127.* and remove IPv6 nameservers if IPv6 disabled.
  286. newRC, err := resolvconf.FilterResolvDNS(currRC.Content, ipv6Enabled)
  287. if err != nil {
  288. return err
  289. }
  290. err = os.WriteFile(sb.config.resolvConfPath, newRC.Content, 0644) //nolint:gosec // gosec complains about perms here, which must be 0644 in this case
  291. if err != nil {
  292. return err
  293. }
  294. // write the new hash in a temp file and rename it to make the update atomic
  295. dir := path.Dir(sb.config.resolvConfPath)
  296. tmpHashFile, err := os.CreateTemp(dir, "hash")
  297. if err != nil {
  298. return err
  299. }
  300. if err = tmpHashFile.Chmod(filePerm); err != nil {
  301. tmpHashFile.Close()
  302. return err
  303. }
  304. _, err = tmpHashFile.Write([]byte(newRC.Hash))
  305. if err1 := tmpHashFile.Close(); err == nil {
  306. err = err1
  307. }
  308. if err != nil {
  309. return err
  310. }
  311. return os.Rename(tmpHashFile.Name(), hashFile)
  312. }
  313. // Embedded DNS server has to be enabled for this sandbox. Rebuild the container's
  314. // resolv.conf by doing the following
  315. // - Add only the embedded server's IP to container's resolv.conf
  316. // - If the embedded server needs any resolv.conf options add it to the current list
  317. func (sb *sandbox) rebuildDNS() error {
  318. currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
  319. if err != nil {
  320. return err
  321. }
  322. if len(sb.extDNS) == 0 {
  323. sb.setExternalResolvers(currRC.Content, resolvconf.IPv4, false)
  324. }
  325. var (
  326. dnsList = []string{sb.resolver.NameServer()}
  327. dnsOptionsList = resolvconf.GetOptions(currRC.Content)
  328. dnsSearchList = resolvconf.GetSearchDomains(currRC.Content)
  329. )
  330. // external v6 DNS servers has to be listed in resolv.conf
  331. dnsList = append(dnsList, resolvconf.GetNameservers(currRC.Content, resolvconf.IPv6)...)
  332. // If the user config and embedded DNS server both have ndots option set,
  333. // remember the user's config so that unqualified names not in the docker
  334. // domain can be dropped.
  335. resOptions := sb.resolver.ResolverOptions()
  336. dnsOpt:
  337. for _, resOpt := range resOptions {
  338. if strings.Contains(resOpt, "ndots") {
  339. for _, option := range dnsOptionsList {
  340. if strings.Contains(option, "ndots") {
  341. parts := strings.Split(option, ":")
  342. if len(parts) != 2 {
  343. return fmt.Errorf("invalid ndots option %v", option)
  344. }
  345. if num, err := strconv.Atoi(parts[1]); err != nil {
  346. return fmt.Errorf("invalid number for ndots option: %v", parts[1])
  347. } else if num >= 0 {
  348. // if the user sets ndots, use the user setting
  349. sb.ndotsSet = true
  350. break dnsOpt
  351. } else {
  352. return fmt.Errorf("invalid number for ndots option: %v", num)
  353. }
  354. }
  355. }
  356. }
  357. }
  358. if !sb.ndotsSet {
  359. // if the user did not set the ndots, set it to 0 to prioritize the service name resolution
  360. // Ref: https://linux.die.net/man/5/resolv.conf
  361. dnsOptionsList = append(dnsOptionsList, resOptions...)
  362. }
  363. _, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
  364. return err
  365. }
  366. func createBasePath(dir string) error {
  367. return os.MkdirAll(dir, dirPerm)
  368. }
  369. func createFile(path string) error {
  370. var f *os.File
  371. dir, _ := filepath.Split(path)
  372. err := createBasePath(dir)
  373. if err != nil {
  374. return err
  375. }
  376. f, err = os.Create(path)
  377. if err == nil {
  378. f.Close()
  379. }
  380. return err
  381. }
  382. func copyFile(src, dst string) error {
  383. sBytes, err := os.ReadFile(src)
  384. if err != nil {
  385. return err
  386. }
  387. return os.WriteFile(dst, sBytes, filePerm)
  388. }