sandbox_dns_unix.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. //go:build !windows
  2. package libnetwork
  3. import (
  4. "context"
  5. "io/fs"
  6. "net/netip"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "github.com/containerd/log"
  11. "github.com/docker/docker/errdefs"
  12. "github.com/docker/docker/libnetwork/etchosts"
  13. "github.com/docker/docker/libnetwork/internal/resolvconf"
  14. "github.com/docker/docker/libnetwork/types"
  15. "github.com/pkg/errors"
  16. )
  17. const (
  18. defaultPrefix = "/var/lib/docker/network/files"
  19. dirPerm = 0o755
  20. filePerm = 0o644
  21. resolverIPSandbox = "127.0.0.11"
  22. )
  23. // finishInitDNS is to be called after the container namespace has been created,
  24. // before it the user process is started. The container's support for IPv6 can be
  25. // determined at this point.
  26. func (sb *Sandbox) finishInitDNS() error {
  27. if err := sb.buildHostsFile(); err != nil {
  28. return errdefs.System(err)
  29. }
  30. for _, ep := range sb.Endpoints() {
  31. if err := sb.updateHostsFile(ep.getEtcHostsAddrs()); err != nil {
  32. return errdefs.System(err)
  33. }
  34. }
  35. return nil
  36. }
  37. func (sb *Sandbox) startResolver(restore bool) {
  38. sb.resolverOnce.Do(func() {
  39. var err error
  40. // The resolver is started with proxyDNS=false if the sandbox does not currently
  41. // have a gateway. So, if the Sandbox is only connected to an 'internal' network,
  42. // it will not forward DNS requests to external resolvers. The resolver's
  43. // proxyDNS setting is then updated as network Endpoints are added/removed.
  44. sb.resolver = NewResolver(resolverIPSandbox, sb.getGatewayEndpoint() != nil, sb)
  45. defer func() {
  46. if err != nil {
  47. sb.resolver = nil
  48. }
  49. }()
  50. // In the case of live restore container is already running with
  51. // right resolv.conf contents created before. Just update the
  52. // external DNS servers from the restored sandbox for embedded
  53. // server to use.
  54. if !restore {
  55. err = sb.rebuildDNS()
  56. if err != nil {
  57. log.G(context.TODO()).Errorf("Updating resolv.conf failed for container %s, %q", sb.ContainerID(), err)
  58. return
  59. }
  60. }
  61. sb.resolver.SetExtServers(sb.extDNS)
  62. if err = sb.osSbox.InvokeFunc(sb.resolver.SetupFunc(0)); err != nil {
  63. log.G(context.TODO()).Errorf("Resolver Setup function failed for container %s, %q", sb.ContainerID(), err)
  64. return
  65. }
  66. if err = sb.resolver.Start(); err != nil {
  67. log.G(context.TODO()).Errorf("Resolver Start failed for container %s, %q", sb.ContainerID(), err)
  68. }
  69. })
  70. }
  71. func (sb *Sandbox) setupResolutionFiles() error {
  72. // Create a hosts file that can be mounted during container setup. For most
  73. // networking modes (not host networking) it will be re-created before the
  74. // container start, once its support for IPv6 is known.
  75. if sb.config.hostsPath == "" {
  76. sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
  77. }
  78. dir, _ := filepath.Split(sb.config.hostsPath)
  79. if err := createBasePath(dir); err != nil {
  80. return err
  81. }
  82. if err := sb.buildHostsFile(); err != nil {
  83. return err
  84. }
  85. return sb.setupDNS()
  86. }
  87. func (sb *Sandbox) buildHostsFile() error {
  88. sb.restoreHostsPath()
  89. dir, _ := filepath.Split(sb.config.hostsPath)
  90. if err := createBasePath(dir); err != nil {
  91. return err
  92. }
  93. // This is for the host mode networking
  94. if sb.config.useDefaultSandBox && len(sb.config.extraHosts) == 0 {
  95. // We are working under the assumption that the origin file option had been properly expressed by the upper layer
  96. // if not here we are going to error out
  97. if err := copyFile(sb.config.originHostsPath, sb.config.hostsPath); err != nil && !os.IsNotExist(err) {
  98. return types.InternalErrorf("could not copy source hosts file %s to %s: %v", sb.config.originHostsPath, sb.config.hostsPath, err)
  99. }
  100. return nil
  101. }
  102. extraContent := make([]etchosts.Record, 0, len(sb.config.extraHosts))
  103. for _, extraHost := range sb.config.extraHosts {
  104. extraContent = append(extraContent, etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
  105. }
  106. // Assume IPv6 support, unless it's definitely disabled.
  107. buildf := etchosts.Build
  108. if en, ok := sb.ipv6Enabled(); ok && !en {
  109. buildf = etchosts.BuildNoIPv6
  110. }
  111. if err := buildf(sb.config.hostsPath, extraContent); err != nil {
  112. return err
  113. }
  114. return sb.updateParentHosts()
  115. }
  116. func (sb *Sandbox) updateHostsFile(ifaceIPs []string) error {
  117. if len(ifaceIPs) == 0 {
  118. return nil
  119. }
  120. if sb.config.originHostsPath != "" {
  121. return nil
  122. }
  123. // User might have provided a FQDN in hostname or split it across hostname
  124. // and domainname. We want the FQDN and the bare hostname.
  125. fqdn := sb.config.hostName
  126. if sb.config.domainName != "" {
  127. fqdn += "." + sb.config.domainName
  128. }
  129. hosts := fqdn
  130. if hostName, _, ok := strings.Cut(fqdn, "."); ok {
  131. hosts += " " + hostName
  132. }
  133. var extraContent []etchosts.Record
  134. for _, ip := range ifaceIPs {
  135. extraContent = append(extraContent, etchosts.Record{Hosts: hosts, IP: ip})
  136. }
  137. sb.addHostsEntries(extraContent)
  138. return nil
  139. }
  140. func (sb *Sandbox) addHostsEntries(recs []etchosts.Record) {
  141. // Assume IPv6 support, unless it's definitely disabled.
  142. if en, ok := sb.ipv6Enabled(); ok && !en {
  143. var filtered []etchosts.Record
  144. for _, rec := range recs {
  145. if addr, err := netip.ParseAddr(rec.IP); err == nil && !addr.Is6() {
  146. filtered = append(filtered, rec)
  147. }
  148. }
  149. recs = filtered
  150. }
  151. if err := etchosts.Add(sb.config.hostsPath, recs); err != nil {
  152. log.G(context.TODO()).Warnf("Failed adding service host entries to the running container: %v", err)
  153. }
  154. }
  155. func (sb *Sandbox) deleteHostsEntries(recs []etchosts.Record) {
  156. if err := etchosts.Delete(sb.config.hostsPath, recs); err != nil {
  157. log.G(context.TODO()).Warnf("Failed deleting service host entries to the running container: %v", err)
  158. }
  159. }
  160. func (sb *Sandbox) updateParentHosts() error {
  161. var pSb *Sandbox
  162. for _, update := range sb.config.parentUpdates {
  163. // 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.
  164. if s, _ := sb.controller.GetSandbox(update.cid); s != nil {
  165. pSb = s
  166. }
  167. if pSb == nil {
  168. continue
  169. }
  170. // TODO(robmry) - filter out IPv6 addresses here if !sb.ipv6Enabled() but...
  171. // - this is part of the implementation of '--link', which will be removed along
  172. // with the rest of legacy networking.
  173. // - IPv6 addresses shouldn't be allocated if IPv6 is not available in a container,
  174. // and that change will come along later.
  175. // - I think this may be dead code, it's not possible to start a parent container with
  176. // '--link child' unless the child has already started ("Error response from daemon:
  177. // Cannot link to a non running container"). So, when the child starts and this method
  178. // is called with updates for parents, the parents aren't running and GetSandbox()
  179. // returns nil.)
  180. if err := etchosts.Update(pSb.config.hostsPath, update.ip, update.name); err != nil {
  181. return err
  182. }
  183. }
  184. return nil
  185. }
  186. func (sb *Sandbox) restoreResolvConfPath() {
  187. if sb.config.resolvConfPath == "" {
  188. sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
  189. }
  190. sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
  191. }
  192. func (sb *Sandbox) restoreHostsPath() {
  193. if sb.config.hostsPath == "" {
  194. sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
  195. }
  196. }
  197. func (sb *Sandbox) setExternalResolvers(entries []resolvconf.ExtDNSEntry) {
  198. sb.extDNS = make([]extDNSEntry, 0, len(entries))
  199. for _, entry := range entries {
  200. sb.extDNS = append(sb.extDNS, extDNSEntry{
  201. IPStr: entry.Addr.String(),
  202. HostLoopback: entry.HostLoopback,
  203. })
  204. }
  205. }
  206. func (c *containerConfig) getOriginResolvConfPath() string {
  207. if c.originResolvConfPath != "" {
  208. return c.originResolvConfPath
  209. }
  210. // Fallback if not specified.
  211. return resolvconf.Path()
  212. }
  213. // loadResolvConf reads the resolv.conf file at path, and merges in overrides for
  214. // nameservers, options, and search domains.
  215. func (sb *Sandbox) loadResolvConf(path string) (*resolvconf.ResolvConf, error) {
  216. rc, err := resolvconf.Load(path)
  217. if err != nil && !errors.Is(err, fs.ErrNotExist) {
  218. return nil, err
  219. }
  220. // Proceed with rc, which might be zero-valued if path does not exist.
  221. rc.SetHeader(`# Generated by Docker Engine.
  222. # This file can be edited; Docker Engine will not make further changes once it
  223. # has been modified.`)
  224. if len(sb.config.dnsList) > 0 {
  225. var dnsAddrs []netip.Addr
  226. for _, ns := range sb.config.dnsList {
  227. addr, err := netip.ParseAddr(ns)
  228. if err != nil {
  229. return nil, errors.Wrapf(err, "bad nameserver address %s", ns)
  230. }
  231. dnsAddrs = append(dnsAddrs, addr)
  232. }
  233. rc.OverrideNameServers(dnsAddrs)
  234. }
  235. if len(sb.config.dnsSearchList) > 0 {
  236. rc.OverrideSearch(sb.config.dnsSearchList)
  237. }
  238. if len(sb.config.dnsOptionsList) > 0 {
  239. rc.OverrideOptions(sb.config.dnsOptionsList)
  240. }
  241. return &rc, nil
  242. }
  243. // For a new sandbox, write an initial version of the container's resolv.conf. It'll
  244. // be a copy of the host's file, with overrides for nameservers, options and search
  245. // domains applied.
  246. func (sb *Sandbox) setupDNS() error {
  247. // Make sure the directory exists.
  248. sb.restoreResolvConfPath()
  249. dir, _ := filepath.Split(sb.config.resolvConfPath)
  250. if err := createBasePath(dir); err != nil {
  251. return err
  252. }
  253. rc, err := sb.loadResolvConf(sb.config.getOriginResolvConfPath())
  254. if err != nil {
  255. return err
  256. }
  257. return rc.WriteFile(sb.config.resolvConfPath, sb.config.resolvConfHashFile, filePerm)
  258. }
  259. // Called when an endpoint has joined the sandbox.
  260. func (sb *Sandbox) updateDNS(ipv6Enabled bool) error {
  261. if mod, err := resolvconf.UserModified(sb.config.resolvConfPath, sb.config.resolvConfHashFile); err != nil || mod {
  262. return err
  263. }
  264. // Load the host's resolv.conf as a starting point.
  265. rc, err := sb.loadResolvConf(sb.config.getOriginResolvConfPath())
  266. if err != nil {
  267. return err
  268. }
  269. // For host-networking, no further change is needed.
  270. if !sb.config.useDefaultSandBox {
  271. // The legacy bridge network has no internal nameserver. So, strip localhost
  272. // nameservers from the host's config, then add default nameservers if there
  273. // are none remaining.
  274. rc.TransformForLegacyNw(ipv6Enabled)
  275. }
  276. return rc.WriteFile(sb.config.resolvConfPath, sb.config.resolvConfHashFile, filePerm)
  277. }
  278. // Embedded DNS server has to be enabled for this sandbox. Rebuild the container's resolv.conf.
  279. func (sb *Sandbox) rebuildDNS() error {
  280. // Don't touch the file if the user has modified it.
  281. if mod, err := resolvconf.UserModified(sb.config.resolvConfPath, sb.config.resolvConfHashFile); err != nil || mod {
  282. return err
  283. }
  284. // Load the host's resolv.conf as a starting point.
  285. rc, err := sb.loadResolvConf(sb.config.getOriginResolvConfPath())
  286. if err != nil {
  287. return err
  288. }
  289. // Check for IPv6 endpoints in this sandbox. If there are any, and the container has
  290. // IPv6 enabled, upstream requests from the internal DNS resolver can be made from
  291. // the container's namespace.
  292. // TODO(robmry) - this can only check networks connected when the resolver is set up,
  293. // the configuration won't be updated if the container gets an IPv6 address later.
  294. ipv6 := false
  295. for _, ep := range sb.endpoints {
  296. if ep.network.enableIPv6 {
  297. if en, ok := sb.ipv6Enabled(); ok {
  298. ipv6 = en
  299. }
  300. break
  301. }
  302. }
  303. intNS, err := netip.ParseAddr(sb.resolver.NameServer())
  304. if err != nil {
  305. return err
  306. }
  307. // Work out whether ndots has been set from host config or overrides.
  308. _, sb.ndotsSet = rc.Option("ndots")
  309. // Swap nameservers for the internal one, and make sure the required options are set.
  310. var extNameServers []resolvconf.ExtDNSEntry
  311. extNameServers, err = rc.TransformForIntNS(ipv6, intNS, sb.resolver.ResolverOptions())
  312. if err != nil {
  313. return err
  314. }
  315. // Extract the list of nameservers that just got swapped out, and store them as
  316. // upstream nameservers.
  317. sb.setExternalResolvers(extNameServers)
  318. // Write the file for the container - preserving old behaviour, not updating the
  319. // hash file (so, no further updates will be made).
  320. // TODO(robmry) - I think that's probably accidental, I can't find a reason for it,
  321. // and the old resolvconf.Build() function wrote the file but not the hash, which
  322. // is surprising. But, before fixing it, a guard/flag needs to be added to
  323. // sb.updateDNS() to make sure that when an endpoint joins a sandbox that already
  324. // has an internal resolver, the container's resolv.conf is still (re)configured
  325. // for an internal resolver.
  326. return rc.WriteFile(sb.config.resolvConfPath, "", filePerm)
  327. }
  328. func createBasePath(dir string) error {
  329. return os.MkdirAll(dir, dirPerm)
  330. }
  331. func copyFile(src, dst string) error {
  332. sBytes, err := os.ReadFile(src)
  333. if err != nil {
  334. return err
  335. }
  336. return os.WriteFile(dst, sBytes, filePerm)
  337. }