sandbox_dns_unix.go 13 KB

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