sandbox_dns_unix.go 13 KB

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