sandbox_dns_unix.go 13 KB

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