github.com/moby/docker@v26.1.3+incompatible/libnetwork/internal/resolvconf/resolvconf_path.go (about)

     1  package resolvconf
     2  
     3  import (
     4  	"context"
     5  	"net/netip"
     6  	"sync"
     7  
     8  	"github.com/containerd/log"
     9  )
    10  
    11  const (
    12  	// defaultPath is the default path to the resolv.conf that contains information to resolve DNS. See Path().
    13  	defaultPath = "/etc/resolv.conf"
    14  	// alternatePath is a path different from defaultPath, that may be used to resolve DNS. See Path().
    15  	alternatePath = "/run/systemd/resolve/resolv.conf"
    16  )
    17  
    18  // For Path to detect systemd (only needed for legacy networking).
    19  var (
    20  	detectSystemdResolvConfOnce sync.Once
    21  	pathAfterSystemdDetection   = defaultPath
    22  )
    23  
    24  // Path returns the path to the resolv.conf file that libnetwork should use.
    25  //
    26  // When /etc/resolv.conf contains 127.0.0.53 as the only nameserver, then
    27  // it is assumed systemd-resolved manages DNS. Because inside the container 127.0.0.53
    28  // is not a valid DNS server, Path() returns /run/systemd/resolve/resolv.conf
    29  // which is the resolv.conf that systemd-resolved generates and manages.
    30  // Otherwise Path() returns /etc/resolv.conf.
    31  //
    32  // Errors are silenced as they will inevitably resurface at future open/read calls.
    33  //
    34  // More information at https://www.freedesktop.org/software/systemd/man/systemd-resolved.service.html#/etc/resolv.conf
    35  //
    36  // TODO(robmry) - alternatePath is only needed for legacy networking ...
    37  //
    38  //	Host networking can use the host's resolv.conf as-is, and with an internal
    39  //	resolver it's also possible to use nameservers on the host's loopback
    40  //	interface. Once legacy networking is removed, this can always return
    41  //	defaultPath.
    42  func Path() string {
    43  	detectSystemdResolvConfOnce.Do(func() {
    44  		rc, err := Load(defaultPath)
    45  		if err != nil {
    46  			// silencing error as it will resurface at next calls trying to read defaultPath
    47  			return
    48  		}
    49  		ns := rc.nameServers
    50  		if len(ns) == 1 && ns[0] == netip.MustParseAddr("127.0.0.53") {
    51  			pathAfterSystemdDetection = alternatePath
    52  			log.G(context.TODO()).Infof("detected 127.0.0.53 nameserver, assuming systemd-resolved, so using resolv.conf: %s", alternatePath)
    53  		}
    54  	})
    55  	return pathAfterSystemdDetection
    56  }