sandbox_dns_unix.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. //go:build !windows
  2. package libnetwork
  3. import (
  4. "bytes"
  5. "context"
  6. "fmt"
  7. "net"
  8. "net/netip"
  9. "os"
  10. "path"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "github.com/containerd/log"
  15. "github.com/docker/docker/errdefs"
  16. "github.com/docker/docker/libnetwork/etchosts"
  17. "github.com/docker/docker/libnetwork/resolvconf"
  18. "github.com/docker/docker/libnetwork/types"
  19. )
  20. const (
  21. defaultPrefix = "/var/lib/docker/network/files"
  22. dirPerm = 0o755
  23. filePerm = 0o644
  24. resolverIPSandbox = "127.0.0.11"
  25. )
  26. // finishInitDNS is to be called after the container namespace has been created,
  27. // before it the user process is started. The container's support for IPv6 can be
  28. // determined at this point.
  29. func (sb *Sandbox) finishInitDNS() error {
  30. if err := sb.buildHostsFile(); err != nil {
  31. return errdefs.System(err)
  32. }
  33. for _, ep := range sb.Endpoints() {
  34. if err := sb.updateHostsFile(ep.getEtcHostsAddrs()); err != nil {
  35. return errdefs.System(err)
  36. }
  37. }
  38. return nil
  39. }
  40. func (sb *Sandbox) startResolver(restore bool) {
  41. sb.resolverOnce.Do(func() {
  42. var err error
  43. // The embedded resolver is always started with proxyDNS set as true, even when the sandbox is only attached to
  44. // an internal network. This way, it's the driver responsibility to make sure `connect` syscall fails fast when
  45. // no external connectivity is available (eg. by not setting a default gateway).
  46. sb.resolver = NewResolver(resolverIPSandbox, true, sb)
  47. defer func() {
  48. if err != nil {
  49. sb.resolver = nil
  50. }
  51. }()
  52. // In the case of live restore container is already running with
  53. // right resolv.conf contents created before. Just update the
  54. // external DNS servers from the restored sandbox for embedded
  55. // server to use.
  56. if !restore {
  57. err = sb.rebuildDNS()
  58. if err != nil {
  59. log.G(context.TODO()).Errorf("Updating resolv.conf failed for container %s, %q", sb.ContainerID(), err)
  60. return
  61. }
  62. }
  63. sb.resolver.SetExtServers(sb.extDNS)
  64. if err = sb.osSbox.InvokeFunc(sb.resolver.SetupFunc(0)); err != nil {
  65. log.G(context.TODO()).Errorf("Resolver Setup function failed for container %s, %q", sb.ContainerID(), err)
  66. return
  67. }
  68. if err = sb.resolver.Start(); err != nil {
  69. log.G(context.TODO()).Errorf("Resolver Start failed for container %s, %q", sb.ContainerID(), err)
  70. }
  71. })
  72. }
  73. func (sb *Sandbox) setupResolutionFiles() error {
  74. // Create a hosts file that can be mounted during container setup. For most
  75. // networking modes (not host networking) it will be re-created before the
  76. // container start, once its support for IPv6 is known.
  77. if sb.config.hostsPath == "" {
  78. sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
  79. }
  80. dir, _ := filepath.Split(sb.config.hostsPath)
  81. if err := createBasePath(dir); err != nil {
  82. return err
  83. }
  84. if err := sb.buildHostsFile(); err != nil {
  85. return err
  86. }
  87. return sb.setupDNS()
  88. }
  89. func (sb *Sandbox) buildHostsFile() error {
  90. // This is for the host mode networking
  91. if sb.config.useDefaultSandBox && len(sb.config.extraHosts) == 0 {
  92. // We are working under the assumption that the origin file option had been properly expressed by the upper layer
  93. // if not here we are going to error out
  94. if err := copyFile(sb.config.originHostsPath, sb.config.hostsPath); err != nil && !os.IsNotExist(err) {
  95. return types.InternalErrorf("could not copy source hosts file %s to %s: %v", sb.config.originHostsPath, sb.config.hostsPath, err)
  96. }
  97. return nil
  98. }
  99. extraContent := make([]etchosts.Record, 0, len(sb.config.extraHosts))
  100. for _, extraHost := range sb.config.extraHosts {
  101. extraContent = append(extraContent, etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
  102. }
  103. // Assume IPv6 support, unless it's definitely disabled.
  104. buildf := etchosts.Build
  105. if en, ok := sb.ipv6Enabled(); ok && !en {
  106. buildf = etchosts.BuildNoIPv6
  107. }
  108. if err := buildf(sb.config.hostsPath, extraContent); err != nil {
  109. return err
  110. }
  111. return sb.updateParentHosts()
  112. }
  113. func (sb *Sandbox) updateHostsFile(ifaceIPs []string) error {
  114. if len(ifaceIPs) == 0 {
  115. return nil
  116. }
  117. if sb.config.originHostsPath != "" {
  118. return nil
  119. }
  120. // User might have provided a FQDN in hostname or split it across hostname
  121. // and domainname. We want the FQDN and the bare hostname.
  122. fqdn := sb.config.hostName
  123. if sb.config.domainName != "" {
  124. fqdn += "." + sb.config.domainName
  125. }
  126. hosts := fqdn
  127. if hostName, _, ok := strings.Cut(fqdn, "."); ok {
  128. hosts += " " + hostName
  129. }
  130. var extraContent []etchosts.Record
  131. for _, ip := range ifaceIPs {
  132. extraContent = append(extraContent, etchosts.Record{Hosts: hosts, IP: ip})
  133. }
  134. sb.addHostsEntries(extraContent)
  135. return nil
  136. }
  137. func (sb *Sandbox) addHostsEntries(recs []etchosts.Record) {
  138. // Assume IPv6 support, unless it's definitely disabled.
  139. if en, ok := sb.ipv6Enabled(); ok && !en {
  140. var filtered []etchosts.Record
  141. for _, rec := range recs {
  142. if addr, err := netip.ParseAddr(rec.IP); err == nil && !addr.Is6() {
  143. filtered = append(filtered, rec)
  144. }
  145. }
  146. recs = filtered
  147. }
  148. if err := etchosts.Add(sb.config.hostsPath, recs); err != nil {
  149. log.G(context.TODO()).Warnf("Failed adding service host entries to the running container: %v", err)
  150. }
  151. }
  152. func (sb *Sandbox) deleteHostsEntries(recs []etchosts.Record) {
  153. if err := etchosts.Delete(sb.config.hostsPath, recs); err != nil {
  154. log.G(context.TODO()).Warnf("Failed deleting service host entries to the running container: %v", err)
  155. }
  156. }
  157. func (sb *Sandbox) updateParentHosts() error {
  158. var pSb *Sandbox
  159. for _, update := range sb.config.parentUpdates {
  160. // TODO(thaJeztah): was it intentional for this loop to re-use prior results of pSB? If not, we should make pSb local and always replace here.
  161. if s, _ := sb.controller.GetSandbox(update.cid); s != nil {
  162. pSb = s
  163. }
  164. if pSb == nil {
  165. continue
  166. }
  167. // TODO(robmry) - filter out IPv6 addresses here if !sb.ipv6Enabled() but...
  168. // - this is part of the implementation of '--link', which will be removed along
  169. // with the rest of legacy networking.
  170. // - IPv6 addresses shouldn't be allocated if IPv6 is not available in a container,
  171. // and that change will come along later.
  172. // - I think this may be dead code, it's not possible to start a parent container with
  173. // '--link child' unless the child has already started ("Error response from daemon:
  174. // Cannot link to a non running container"). So, when the child starts and this method
  175. // is called with updates for parents, the parents aren't running and GetSandbox()
  176. // returns nil.)
  177. if err := etchosts.Update(pSb.config.hostsPath, update.ip, update.name); err != nil {
  178. return err
  179. }
  180. }
  181. return nil
  182. }
  183. func (sb *Sandbox) restorePath() {
  184. if sb.config.resolvConfPath == "" {
  185. sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
  186. }
  187. sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
  188. if sb.config.hostsPath == "" {
  189. sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
  190. }
  191. }
  192. func (sb *Sandbox) setExternalResolvers(content []byte, addrType int, checkLoopback bool) {
  193. servers := resolvconf.GetNameservers(content, addrType)
  194. for _, ip := range servers {
  195. hostLoopback := false
  196. if checkLoopback && isIPv4Loopback(ip) {
  197. hostLoopback = true
  198. }
  199. sb.extDNS = append(sb.extDNS, extDNSEntry{
  200. IPStr: ip,
  201. HostLoopback: hostLoopback,
  202. })
  203. }
  204. }
  205. // isIPv4Loopback checks if the given IP address is an IPv4 loopback address.
  206. // It's based on the logic in Go's net.IP.IsLoopback(), but only the IPv4 part:
  207. // https://github.com/golang/go/blob/go1.16.6/src/net/ip.go#L120-L126
  208. func isIPv4Loopback(ipAddress string) bool {
  209. if ip := net.ParseIP(ipAddress); ip != nil {
  210. if ip4 := ip.To4(); ip4 != nil {
  211. return ip4[0] == 127
  212. }
  213. }
  214. return false
  215. }
  216. func (sb *Sandbox) setupDNS() error {
  217. if sb.config.resolvConfPath == "" {
  218. sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
  219. }
  220. sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
  221. dir, _ := filepath.Split(sb.config.resolvConfPath)
  222. if err := createBasePath(dir); err != nil {
  223. return err
  224. }
  225. // When the user specify a conainter in the host namespace and do no have any dns option specified
  226. // we just copy the host resolv.conf from the host itself
  227. if sb.config.useDefaultSandBox && len(sb.config.dnsList) == 0 && len(sb.config.dnsSearchList) == 0 && len(sb.config.dnsOptionsList) == 0 {
  228. // We are working under the assumption that the origin file option had been properly expressed by the upper layer
  229. // if not here we are going to error out
  230. if err := copyFile(sb.config.originResolvConfPath, sb.config.resolvConfPath); err != nil {
  231. if !os.IsNotExist(err) {
  232. return fmt.Errorf("could not copy source resolv.conf file %s to %s: %v", sb.config.originResolvConfPath, sb.config.resolvConfPath, err)
  233. }
  234. log.G(context.TODO()).Infof("%s does not exist, we create an empty resolv.conf for container", sb.config.originResolvConfPath)
  235. if err := createFile(sb.config.resolvConfPath); err != nil {
  236. return err
  237. }
  238. }
  239. return nil
  240. }
  241. originResolvConfPath := sb.config.originResolvConfPath
  242. if originResolvConfPath == "" {
  243. // fallback if not specified
  244. originResolvConfPath = resolvconf.Path()
  245. }
  246. currRC, err := os.ReadFile(originResolvConfPath)
  247. if err != nil {
  248. if !os.IsNotExist(err) {
  249. return err
  250. }
  251. // No /etc/resolv.conf found: we'll use the default resolvers (Google's Public DNS).
  252. log.G(context.TODO()).WithField("path", originResolvConfPath).Infof("no resolv.conf found, falling back to defaults")
  253. }
  254. var newRC *resolvconf.File
  255. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  256. var (
  257. dnsList = sb.config.dnsList
  258. dnsSearchList = sb.config.dnsSearchList
  259. dnsOptionsList = sb.config.dnsOptionsList
  260. )
  261. if len(sb.config.dnsList) == 0 {
  262. dnsList = resolvconf.GetNameservers(currRC, resolvconf.IP)
  263. }
  264. if len(sb.config.dnsSearchList) == 0 {
  265. dnsSearchList = resolvconf.GetSearchDomains(currRC)
  266. }
  267. if len(sb.config.dnsOptionsList) == 0 {
  268. dnsOptionsList = resolvconf.GetOptions(currRC)
  269. }
  270. newRC, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
  271. if err != nil {
  272. return err
  273. }
  274. // After building the resolv.conf from the user config save the
  275. // external resolvers in the sandbox. Note that --dns 127.0.0.x
  276. // config refers to the loopback in the container namespace
  277. sb.setExternalResolvers(newRC.Content, resolvconf.IPv4, len(sb.config.dnsList) == 0)
  278. } else {
  279. // If the host resolv.conf file has 127.0.0.x container should
  280. // use the host resolver for queries. This is supported by the
  281. // docker embedded DNS server. Hence save the external resolvers
  282. // before filtering it out.
  283. sb.setExternalResolvers(currRC, resolvconf.IPv4, true)
  284. // Replace any localhost/127.* (at this point we have no info about ipv6, pass it as true)
  285. newRC, err = resolvconf.FilterResolvDNS(currRC, true)
  286. if err != nil {
  287. return err
  288. }
  289. // No contention on container resolv.conf file at sandbox creation
  290. err = os.WriteFile(sb.config.resolvConfPath, newRC.Content, filePerm)
  291. if err != nil {
  292. return types.InternalErrorf("failed to write unhaltered resolv.conf file content when setting up dns for sandbox %s: %v", sb.ID(), err)
  293. }
  294. }
  295. // Write hash
  296. err = os.WriteFile(sb.config.resolvConfHashFile, newRC.Hash, filePerm)
  297. if err != nil {
  298. return types.InternalErrorf("failed to write resolv.conf hash file when setting up dns for sandbox %s: %v", sb.ID(), err)
  299. }
  300. return nil
  301. }
  302. func (sb *Sandbox) updateDNS(ipv6Enabled bool) error {
  303. // This is for the host mode networking
  304. if sb.config.useDefaultSandBox {
  305. return nil
  306. }
  307. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  308. return nil
  309. }
  310. var currHash []byte
  311. currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
  312. if err != nil {
  313. if !os.IsNotExist(err) {
  314. return err
  315. }
  316. } else {
  317. currHash, err = os.ReadFile(sb.config.resolvConfHashFile)
  318. if err != nil && !os.IsNotExist(err) {
  319. return err
  320. }
  321. }
  322. if len(currHash) > 0 && !bytes.Equal(currHash, currRC.Hash) {
  323. // Seems the user has changed the container resolv.conf since the last time
  324. // we checked so return without doing anything.
  325. // log.G(ctx).Infof("Skipping update of resolv.conf file with ipv6Enabled: %t because file was touched by user", ipv6Enabled)
  326. return nil
  327. }
  328. // replace any localhost/127.* and remove IPv6 nameservers if IPv6 disabled.
  329. newRC, err := resolvconf.FilterResolvDNS(currRC.Content, ipv6Enabled)
  330. if err != nil {
  331. return err
  332. }
  333. err = os.WriteFile(sb.config.resolvConfPath, newRC.Content, filePerm)
  334. if err != nil {
  335. return err
  336. }
  337. // write the new hash in a temp file and rename it to make the update atomic
  338. dir := path.Dir(sb.config.resolvConfPath)
  339. tmpHashFile, err := os.CreateTemp(dir, "hash")
  340. if err != nil {
  341. return err
  342. }
  343. if err = tmpHashFile.Chmod(filePerm); err != nil {
  344. tmpHashFile.Close()
  345. return err
  346. }
  347. _, err = tmpHashFile.Write(newRC.Hash)
  348. if err1 := tmpHashFile.Close(); err == nil {
  349. err = err1
  350. }
  351. if err != nil {
  352. return err
  353. }
  354. return os.Rename(tmpHashFile.Name(), sb.config.resolvConfHashFile)
  355. }
  356. // Embedded DNS server has to be enabled for this sandbox. Rebuild the container's
  357. // resolv.conf by doing the following
  358. // - Add only the embedded server's IP to container's resolv.conf
  359. // - If the embedded server needs any resolv.conf options add it to the current list
  360. func (sb *Sandbox) rebuildDNS() error {
  361. currRC, err := os.ReadFile(sb.config.resolvConfPath)
  362. if err != nil {
  363. return err
  364. }
  365. // If the user config and embedded DNS server both have ndots option set,
  366. // remember the user's config so that unqualified names not in the docker
  367. // domain can be dropped.
  368. resOptions := sb.resolver.ResolverOptions()
  369. dnsOptionsList := resolvconf.GetOptions(currRC)
  370. dnsOpt:
  371. for _, resOpt := range resOptions {
  372. if strings.Contains(resOpt, "ndots") {
  373. for _, option := range dnsOptionsList {
  374. if strings.Contains(option, "ndots") {
  375. parts := strings.Split(option, ":")
  376. if len(parts) != 2 {
  377. return fmt.Errorf("invalid ndots option %v", option)
  378. }
  379. if num, err := strconv.Atoi(parts[1]); err != nil {
  380. return fmt.Errorf("invalid number for ndots option: %v", parts[1])
  381. } else if num >= 0 {
  382. // if the user sets ndots, use the user setting
  383. sb.ndotsSet = true
  384. break dnsOpt
  385. } else {
  386. return fmt.Errorf("invalid number for ndots option: %v", num)
  387. }
  388. }
  389. }
  390. }
  391. }
  392. if !sb.ndotsSet {
  393. // if the user did not set the ndots, set it to 0 to prioritize the service name resolution
  394. // Ref: https://linux.die.net/man/5/resolv.conf
  395. dnsOptionsList = append(dnsOptionsList, resOptions...)
  396. }
  397. if len(sb.extDNS) == 0 {
  398. sb.setExternalResolvers(currRC, resolvconf.IPv4, false)
  399. }
  400. var (
  401. // external v6 DNS servers have to be listed in resolv.conf
  402. dnsList = append([]string{sb.resolver.NameServer()}, resolvconf.GetNameservers(currRC, resolvconf.IPv6)...)
  403. dnsSearchList = resolvconf.GetSearchDomains(currRC)
  404. )
  405. _, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
  406. return err
  407. }
  408. func createBasePath(dir string) error {
  409. return os.MkdirAll(dir, dirPerm)
  410. }
  411. func createFile(path string) error {
  412. var f *os.File
  413. dir, _ := filepath.Split(path)
  414. err := createBasePath(dir)
  415. if err != nil {
  416. return err
  417. }
  418. f, err = os.Create(path)
  419. if err == nil {
  420. f.Close()
  421. }
  422. return err
  423. }
  424. func copyFile(src, dst string) error {
  425. sBytes, err := os.ReadFile(src)
  426. if err != nil {
  427. return err
  428. }
  429. return os.WriteFile(dst, sBytes, filePerm)
  430. }