sandbox_dns_unix.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. //go:build !windows
  2. package libnetwork
  3. import (
  4. "bytes"
  5. "context"
  6. "fmt"
  7. "net"
  8. "os"
  9. "path"
  10. "path/filepath"
  11. "strconv"
  12. "strings"
  13. "github.com/containerd/log"
  14. "github.com/docker/docker/libnetwork/etchosts"
  15. "github.com/docker/docker/libnetwork/resolvconf"
  16. "github.com/docker/docker/libnetwork/types"
  17. )
  18. const (
  19. defaultPrefix = "/var/lib/docker/network/files"
  20. dirPerm = 0o755
  21. filePerm = 0o644
  22. resolverIPSandbox = "127.0.0.11"
  23. )
  24. func (sb *Sandbox) startResolver(restore bool) {
  25. sb.resolverOnce.Do(func() {
  26. var err error
  27. // The resolver is started with proxyDNS=false if the sandbox does not currently
  28. // have a gateway. So, if the Sandbox is only connected to an 'internal' network,
  29. // it will not forward DNS requests to external resolvers. The resolver's
  30. // proxyDNS setting is then updated as network Endpoints are added/removed.
  31. sb.resolver = NewResolver(resolverIPSandbox, sb.getGatewayEndpoint() != nil, sb)
  32. defer func() {
  33. if err != nil {
  34. sb.resolver = nil
  35. }
  36. }()
  37. // In the case of live restore container is already running with
  38. // right resolv.conf contents created before. Just update the
  39. // external DNS servers from the restored sandbox for embedded
  40. // server to use.
  41. if !restore {
  42. err = sb.rebuildDNS()
  43. if err != nil {
  44. log.G(context.TODO()).Errorf("Updating resolv.conf failed for container %s, %q", sb.ContainerID(), err)
  45. return
  46. }
  47. }
  48. sb.resolver.SetExtServers(sb.extDNS)
  49. if err = sb.osSbox.InvokeFunc(sb.resolver.SetupFunc(0)); err != nil {
  50. log.G(context.TODO()).Errorf("Resolver Setup function failed for container %s, %q", sb.ContainerID(), err)
  51. return
  52. }
  53. if err = sb.resolver.Start(); err != nil {
  54. log.G(context.TODO()).Errorf("Resolver Start failed for container %s, %q", sb.ContainerID(), err)
  55. }
  56. })
  57. }
  58. func (sb *Sandbox) setupResolutionFiles() error {
  59. if err := sb.buildHostsFile(); err != nil {
  60. return err
  61. }
  62. if err := sb.updateParentHosts(); err != nil {
  63. return err
  64. }
  65. return sb.setupDNS()
  66. }
  67. func (sb *Sandbox) buildHostsFile() error {
  68. if sb.config.hostsPath == "" {
  69. sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
  70. }
  71. dir, _ := filepath.Split(sb.config.hostsPath)
  72. if err := createBasePath(dir); err != nil {
  73. return err
  74. }
  75. // This is for the host mode networking
  76. if sb.config.useDefaultSandBox && len(sb.config.extraHosts) == 0 {
  77. // We are working under the assumption that the origin file option had been properly expressed by the upper layer
  78. // if not here we are going to error out
  79. if err := copyFile(sb.config.originHostsPath, sb.config.hostsPath); err != nil && !os.IsNotExist(err) {
  80. return types.InternalErrorf("could not copy source hosts file %s to %s: %v", sb.config.originHostsPath, sb.config.hostsPath, err)
  81. }
  82. return nil
  83. }
  84. extraContent := make([]etchosts.Record, 0, len(sb.config.extraHosts))
  85. for _, extraHost := range sb.config.extraHosts {
  86. extraContent = append(extraContent, etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
  87. }
  88. return etchosts.Build(sb.config.hostsPath, "", sb.config.hostName, sb.config.domainName, extraContent)
  89. }
  90. func (sb *Sandbox) updateHostsFile(ifaceIPs []string) error {
  91. if len(ifaceIPs) == 0 {
  92. return nil
  93. }
  94. if sb.config.originHostsPath != "" {
  95. return nil
  96. }
  97. // User might have provided a FQDN in hostname or split it across hostname
  98. // and domainname. We want the FQDN and the bare hostname.
  99. fqdn := sb.config.hostName
  100. if sb.config.domainName != "" {
  101. fqdn += "." + sb.config.domainName
  102. }
  103. hosts := fqdn
  104. if hostName, _, ok := strings.Cut(fqdn, "."); ok {
  105. hosts += " " + hostName
  106. }
  107. var extraContent []etchosts.Record
  108. for _, ip := range ifaceIPs {
  109. extraContent = append(extraContent, etchosts.Record{Hosts: hosts, IP: ip})
  110. }
  111. sb.addHostsEntries(extraContent)
  112. return nil
  113. }
  114. func (sb *Sandbox) addHostsEntries(recs []etchosts.Record) {
  115. if err := etchosts.Add(sb.config.hostsPath, recs); err != nil {
  116. log.G(context.TODO()).Warnf("Failed adding service host entries to the running container: %v", err)
  117. }
  118. }
  119. func (sb *Sandbox) deleteHostsEntries(recs []etchosts.Record) {
  120. if err := etchosts.Delete(sb.config.hostsPath, recs); err != nil {
  121. log.G(context.TODO()).Warnf("Failed deleting service host entries to the running container: %v", err)
  122. }
  123. }
  124. func (sb *Sandbox) updateParentHosts() error {
  125. var pSb *Sandbox
  126. for _, update := range sb.config.parentUpdates {
  127. // 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.
  128. if s, _ := sb.controller.GetSandbox(update.cid); s != nil {
  129. pSb = s
  130. }
  131. if pSb == nil {
  132. continue
  133. }
  134. if err := etchosts.Update(pSb.config.hostsPath, update.ip, update.name); err != nil {
  135. return err
  136. }
  137. }
  138. return nil
  139. }
  140. func (sb *Sandbox) restorePath() {
  141. if sb.config.resolvConfPath == "" {
  142. sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
  143. }
  144. sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
  145. if sb.config.hostsPath == "" {
  146. sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
  147. }
  148. }
  149. func (sb *Sandbox) setExternalResolvers(content []byte, addrType int, checkLoopback bool) {
  150. servers := resolvconf.GetNameservers(content, addrType)
  151. for _, ip := range servers {
  152. hostLoopback := false
  153. if checkLoopback && isIPv4Loopback(ip) {
  154. hostLoopback = true
  155. }
  156. sb.extDNS = append(sb.extDNS, extDNSEntry{
  157. IPStr: ip,
  158. HostLoopback: hostLoopback,
  159. })
  160. }
  161. }
  162. // isIPv4Loopback checks if the given IP address is an IPv4 loopback address.
  163. // It's based on the logic in Go's net.IP.IsLoopback(), but only the IPv4 part:
  164. // https://github.com/golang/go/blob/go1.16.6/src/net/ip.go#L120-L126
  165. func isIPv4Loopback(ipAddress string) bool {
  166. if ip := net.ParseIP(ipAddress); ip != nil {
  167. if ip4 := ip.To4(); ip4 != nil {
  168. return ip4[0] == 127
  169. }
  170. }
  171. return false
  172. }
  173. func (sb *Sandbox) setupDNS() error {
  174. if sb.config.resolvConfPath == "" {
  175. sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
  176. }
  177. sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
  178. dir, _ := filepath.Split(sb.config.resolvConfPath)
  179. if err := createBasePath(dir); err != nil {
  180. return err
  181. }
  182. // When the user specify a conainter in the host namespace and do no have any dns option specified
  183. // we just copy the host resolv.conf from the host itself
  184. if sb.config.useDefaultSandBox && len(sb.config.dnsList) == 0 && len(sb.config.dnsSearchList) == 0 && len(sb.config.dnsOptionsList) == 0 {
  185. // We are working under the assumption that the origin file option had been properly expressed by the upper layer
  186. // if not here we are going to error out
  187. if err := copyFile(sb.config.originResolvConfPath, sb.config.resolvConfPath); err != nil {
  188. if !os.IsNotExist(err) {
  189. return fmt.Errorf("could not copy source resolv.conf file %s to %s: %v", sb.config.originResolvConfPath, sb.config.resolvConfPath, err)
  190. }
  191. log.G(context.TODO()).Infof("%s does not exist, we create an empty resolv.conf for container", sb.config.originResolvConfPath)
  192. if err := createFile(sb.config.resolvConfPath); err != nil {
  193. return err
  194. }
  195. }
  196. return nil
  197. }
  198. originResolvConfPath := sb.config.originResolvConfPath
  199. if originResolvConfPath == "" {
  200. // fallback if not specified
  201. originResolvConfPath = resolvconf.Path()
  202. }
  203. currRC, err := os.ReadFile(originResolvConfPath)
  204. if err != nil {
  205. if !os.IsNotExist(err) {
  206. return err
  207. }
  208. // No /etc/resolv.conf found: we'll use the default resolvers (Google's Public DNS).
  209. log.G(context.TODO()).WithField("path", originResolvConfPath).Infof("no resolv.conf found, falling back to defaults")
  210. }
  211. var newRC *resolvconf.File
  212. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  213. var (
  214. dnsList = sb.config.dnsList
  215. dnsSearchList = sb.config.dnsSearchList
  216. dnsOptionsList = sb.config.dnsOptionsList
  217. )
  218. if len(sb.config.dnsList) == 0 {
  219. dnsList = resolvconf.GetNameservers(currRC, resolvconf.IP)
  220. }
  221. if len(sb.config.dnsSearchList) == 0 {
  222. dnsSearchList = resolvconf.GetSearchDomains(currRC)
  223. }
  224. if len(sb.config.dnsOptionsList) == 0 {
  225. dnsOptionsList = resolvconf.GetOptions(currRC)
  226. }
  227. newRC, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
  228. if err != nil {
  229. return err
  230. }
  231. // After building the resolv.conf from the user config save the
  232. // external resolvers in the sandbox. Note that --dns 127.0.0.x
  233. // config refers to the loopback in the container namespace
  234. sb.setExternalResolvers(newRC.Content, resolvconf.IPv4, len(sb.config.dnsList) == 0)
  235. } else {
  236. // If the host resolv.conf file has 127.0.0.x container should
  237. // use the host resolver for queries. This is supported by the
  238. // docker embedded DNS server. Hence save the external resolvers
  239. // before filtering it out.
  240. sb.setExternalResolvers(currRC, resolvconf.IPv4, true)
  241. // Replace any localhost/127.* (at this point we have no info about ipv6, pass it as true)
  242. newRC, err = resolvconf.FilterResolvDNS(currRC, true)
  243. if err != nil {
  244. return err
  245. }
  246. // No contention on container resolv.conf file at sandbox creation
  247. err = os.WriteFile(sb.config.resolvConfPath, newRC.Content, filePerm)
  248. if err != nil {
  249. return types.InternalErrorf("failed to write unhaltered resolv.conf file content when setting up dns for sandbox %s: %v", sb.ID(), err)
  250. }
  251. }
  252. // Write hash
  253. err = os.WriteFile(sb.config.resolvConfHashFile, newRC.Hash, filePerm)
  254. if err != nil {
  255. return types.InternalErrorf("failed to write resolv.conf hash file when setting up dns for sandbox %s: %v", sb.ID(), err)
  256. }
  257. return nil
  258. }
  259. func (sb *Sandbox) updateDNS(ipv6Enabled bool) error {
  260. // This is for the host mode networking
  261. if sb.config.useDefaultSandBox {
  262. return nil
  263. }
  264. if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
  265. return nil
  266. }
  267. var currHash []byte
  268. currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
  269. if err != nil {
  270. if !os.IsNotExist(err) {
  271. return err
  272. }
  273. } else {
  274. currHash, err = os.ReadFile(sb.config.resolvConfHashFile)
  275. if err != nil && !os.IsNotExist(err) {
  276. return err
  277. }
  278. }
  279. if len(currHash) > 0 && !bytes.Equal(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. // log.G(ctx).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, filePerm)
  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(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(), sb.config.resolvConfHashFile)
  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 := os.ReadFile(sb.config.resolvConfPath)
  319. if err != nil {
  320. return err
  321. }
  322. // If the user config and embedded DNS server both have ndots option set,
  323. // remember the user's config so that unqualified names not in the docker
  324. // domain can be dropped.
  325. resOptions := sb.resolver.ResolverOptions()
  326. dnsOptionsList := resolvconf.GetOptions(currRC)
  327. dnsOpt:
  328. for _, resOpt := range resOptions {
  329. if strings.Contains(resOpt, "ndots") {
  330. for _, option := range dnsOptionsList {
  331. if strings.Contains(option, "ndots") {
  332. parts := strings.Split(option, ":")
  333. if len(parts) != 2 {
  334. return fmt.Errorf("invalid ndots option %v", option)
  335. }
  336. if num, err := strconv.Atoi(parts[1]); err != nil {
  337. return fmt.Errorf("invalid number for ndots option: %v", parts[1])
  338. } else if num >= 0 {
  339. // if the user sets ndots, use the user setting
  340. sb.ndotsSet = true
  341. break dnsOpt
  342. } else {
  343. return fmt.Errorf("invalid number for ndots option: %v", num)
  344. }
  345. }
  346. }
  347. }
  348. }
  349. if !sb.ndotsSet {
  350. // if the user did not set the ndots, set it to 0 to prioritize the service name resolution
  351. // Ref: https://linux.die.net/man/5/resolv.conf
  352. dnsOptionsList = append(dnsOptionsList, resOptions...)
  353. }
  354. if len(sb.extDNS) == 0 {
  355. sb.setExternalResolvers(currRC, resolvconf.IPv4, false)
  356. }
  357. var (
  358. // external v6 DNS servers have to be listed in resolv.conf
  359. dnsList = append([]string{sb.resolver.NameServer()}, resolvconf.GetNameservers(currRC, resolvconf.IPv6)...)
  360. dnsSearchList = resolvconf.GetSearchDomains(currRC)
  361. )
  362. _, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
  363. return err
  364. }
  365. func createBasePath(dir string) error {
  366. return os.MkdirAll(dir, dirPerm)
  367. }
  368. func createFile(path string) error {
  369. var f *os.File
  370. dir, _ := filepath.Split(path)
  371. err := createBasePath(dir)
  372. if err != nil {
  373. return err
  374. }
  375. f, err = os.Create(path)
  376. if err == nil {
  377. f.Close()
  378. }
  379. return err
  380. }
  381. func copyFile(src, dst string) error {
  382. sBytes, err := os.ReadFile(src)
  383. if err != nil {
  384. return err
  385. }
  386. return os.WriteFile(dst, sBytes, filePerm)
  387. }