github.com/Heebron/moby@v0.0.0-20221111184709-6eab4f55faf7/daemon/config/config.go (about)

     1  package config // import "github.com/docker/docker/daemon/config"
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"fmt"
     7  	"net"
     8  	"net/url"
     9  	"os"
    10  	"path/filepath"
    11  	"strings"
    12  	"sync"
    13  
    14  	"github.com/containerd/containerd/runtime/v2/shim"
    15  	"github.com/docker/docker/opts"
    16  	"github.com/docker/docker/pkg/authorization"
    17  	"github.com/docker/docker/registry"
    18  	"github.com/imdario/mergo"
    19  	"github.com/pkg/errors"
    20  	"github.com/sirupsen/logrus"
    21  	"github.com/spf13/pflag"
    22  )
    23  
    24  const (
    25  	// DefaultMaxConcurrentDownloads is the default value for
    26  	// maximum number of downloads that
    27  	// may take place at a time.
    28  	DefaultMaxConcurrentDownloads = 3
    29  	// DefaultMaxConcurrentUploads is the default value for
    30  	// maximum number of uploads that
    31  	// may take place at a time.
    32  	DefaultMaxConcurrentUploads = 5
    33  	// DefaultDownloadAttempts is the default value for
    34  	// maximum number of attempts that
    35  	// may take place at a time for each pull when the connection is lost.
    36  	DefaultDownloadAttempts = 5
    37  	// DefaultShmSize is the default value for container's shm size (64 MiB)
    38  	DefaultShmSize int64 = 64 * 1024 * 1024
    39  	// DefaultNetworkMtu is the default value for network MTU
    40  	DefaultNetworkMtu = 1500
    41  	// DisableNetworkBridge is the default value of the option to disable network bridge
    42  	DisableNetworkBridge = "none"
    43  	// DefaultShutdownTimeout is the default shutdown timeout (in seconds) for
    44  	// the daemon for containers to stop when it is shutting down.
    45  	DefaultShutdownTimeout = 15
    46  	// DefaultInitBinary is the name of the default init binary
    47  	DefaultInitBinary = "docker-init"
    48  	// DefaultRuntimeBinary is the default runtime to be used by
    49  	// containerd if none is specified
    50  	DefaultRuntimeBinary = "runc"
    51  	// DefaultContainersNamespace is the name of the default containerd namespace used for users containers.
    52  	DefaultContainersNamespace = "moby"
    53  	// DefaultPluginNamespace is the name of the default containerd namespace used for plugins.
    54  	DefaultPluginNamespace = "plugins.moby"
    55  
    56  	// LinuxV2RuntimeName is the runtime used to specify the containerd v2 runc shim
    57  	LinuxV2RuntimeName = "io.containerd.runc.v2"
    58  
    59  	// SeccompProfileDefault is the built-in default seccomp profile.
    60  	SeccompProfileDefault = "builtin"
    61  	// SeccompProfileUnconfined is a special profile name for seccomp to use an
    62  	// "unconfined" seccomp profile.
    63  	SeccompProfileUnconfined = "unconfined"
    64  )
    65  
    66  var builtinRuntimes = map[string]bool{
    67  	StockRuntimeName:   true,
    68  	LinuxV2RuntimeName: true,
    69  }
    70  
    71  // flatOptions contains configuration keys
    72  // that MUST NOT be parsed as deep structures.
    73  // Use this to differentiate these options
    74  // with others like the ones in CommonTLSOptions.
    75  var flatOptions = map[string]bool{
    76  	"cluster-store-opts": true,
    77  	"log-opts":           true,
    78  	"runtimes":           true,
    79  	"default-ulimits":    true,
    80  	"features":           true,
    81  	"builder":            true,
    82  }
    83  
    84  // skipValidateOptions contains configuration keys
    85  // that will be skipped from findConfigurationConflicts
    86  // for unknown flag validation.
    87  var skipValidateOptions = map[string]bool{
    88  	"features": true,
    89  	"builder":  true,
    90  	// Corresponding flag has been removed because it was already unusable
    91  	"deprecated-key-path": true,
    92  }
    93  
    94  // skipDuplicates contains configuration keys that
    95  // will be skipped when checking duplicated
    96  // configuration field defined in both daemon
    97  // config file and from dockerd cli flags.
    98  // This allows some configurations to be merged
    99  // during the parsing.
   100  var skipDuplicates = map[string]bool{
   101  	"runtimes": true,
   102  }
   103  
   104  // LogConfig represents the default log configuration.
   105  // It includes json tags to deserialize configuration from a file
   106  // using the same names that the flags in the command line use.
   107  type LogConfig struct {
   108  	Type   string            `json:"log-driver,omitempty"`
   109  	Config map[string]string `json:"log-opts,omitempty"`
   110  }
   111  
   112  // commonBridgeConfig stores all the platform-common bridge driver specific
   113  // configuration.
   114  type commonBridgeConfig struct {
   115  	Iface     string `json:"bridge,omitempty"`
   116  	FixedCIDR string `json:"fixed-cidr,omitempty"`
   117  }
   118  
   119  // NetworkConfig stores the daemon-wide networking configurations
   120  type NetworkConfig struct {
   121  	// Default address pools for docker networks
   122  	DefaultAddressPools opts.PoolsOpt `json:"default-address-pools,omitempty"`
   123  	// NetworkControlPlaneMTU allows to specify the control plane MTU, this will allow to optimize the network use in some components
   124  	NetworkControlPlaneMTU int `json:"network-control-plane-mtu,omitempty"`
   125  }
   126  
   127  // CommonTLSOptions defines TLS configuration for the daemon server.
   128  // It includes json tags to deserialize configuration from a file
   129  // using the same names that the flags in the command line use.
   130  type CommonTLSOptions struct {
   131  	CAFile   string `json:"tlscacert,omitempty"`
   132  	CertFile string `json:"tlscert,omitempty"`
   133  	KeyFile  string `json:"tlskey,omitempty"`
   134  }
   135  
   136  // DNSConfig defines the DNS configurations.
   137  type DNSConfig struct {
   138  	DNS           []string `json:"dns,omitempty"`
   139  	DNSOptions    []string `json:"dns-opts,omitempty"`
   140  	DNSSearch     []string `json:"dns-search,omitempty"`
   141  	HostGatewayIP net.IP   `json:"host-gateway-ip,omitempty"`
   142  }
   143  
   144  // CommonConfig defines the configuration of a docker daemon which is
   145  // common across platforms.
   146  // It includes json tags to deserialize configuration from a file
   147  // using the same names that the flags in the command line use.
   148  type CommonConfig struct {
   149  	AuthzMiddleware       *authorization.Middleware `json:"-"`
   150  	AuthorizationPlugins  []string                  `json:"authorization-plugins,omitempty"` // AuthorizationPlugins holds list of authorization plugins
   151  	AutoRestart           bool                      `json:"-"`
   152  	Context               map[string][]string       `json:"-"`
   153  	DisableBridge         bool                      `json:"-"`
   154  	ExecOptions           []string                  `json:"exec-opts,omitempty"`
   155  	GraphDriver           string                    `json:"storage-driver,omitempty"`
   156  	GraphOptions          []string                  `json:"storage-opts,omitempty"`
   157  	Labels                []string                  `json:"labels,omitempty"`
   158  	Mtu                   int                       `json:"mtu,omitempty"`
   159  	NetworkDiagnosticPort int                       `json:"network-diagnostic-port,omitempty"`
   160  	Pidfile               string                    `json:"pidfile,omitempty"`
   161  	RawLogs               bool                      `json:"raw-logs,omitempty"`
   162  	RootDeprecated        string                    `json:"graph,omitempty"` // Deprecated: use Root instead. TODO(thaJeztah): remove in next release.
   163  	Root                  string                    `json:"data-root,omitempty"`
   164  	ExecRoot              string                    `json:"exec-root,omitempty"`
   165  	SocketGroup           string                    `json:"group,omitempty"`
   166  	CorsHeaders           string                    `json:"api-cors-header,omitempty"`
   167  
   168  	// Proxies holds the proxies that are configured for the daemon.
   169  	Proxies `json:"proxies"`
   170  
   171  	// TrustKeyPath is used to generate the daemon ID and for signing schema 1 manifests
   172  	// when pushing to a registry which does not support schema 2. This field is marked as
   173  	// deprecated because schema 1 manifests are deprecated in favor of schema 2 and the
   174  	// daemon ID will use a dedicated identifier not shared with exported signatures.
   175  	TrustKeyPath string `json:"deprecated-key-path,omitempty"`
   176  
   177  	// LiveRestoreEnabled determines whether we should keep containers
   178  	// alive upon daemon shutdown/start
   179  	LiveRestoreEnabled bool `json:"live-restore,omitempty"`
   180  
   181  	// MaxConcurrentDownloads is the maximum number of downloads that
   182  	// may take place at a time for each pull.
   183  	MaxConcurrentDownloads int `json:"max-concurrent-downloads,omitempty"`
   184  
   185  	// MaxConcurrentUploads is the maximum number of uploads that
   186  	// may take place at a time for each push.
   187  	MaxConcurrentUploads int `json:"max-concurrent-uploads,omitempty"`
   188  
   189  	// MaxDownloadAttempts is the maximum number of attempts that
   190  	// may take place at a time for each push.
   191  	MaxDownloadAttempts int `json:"max-download-attempts,omitempty"`
   192  
   193  	// ShutdownTimeout is the timeout value (in seconds) the daemon will wait for the container
   194  	// to stop when daemon is being shutdown
   195  	ShutdownTimeout int `json:"shutdown-timeout,omitempty"`
   196  
   197  	Debug     bool     `json:"debug,omitempty"`
   198  	Hosts     []string `json:"hosts,omitempty"`
   199  	LogLevel  string   `json:"log-level,omitempty"`
   200  	TLS       *bool    `json:"tls,omitempty"`
   201  	TLSVerify *bool    `json:"tlsverify,omitempty"`
   202  
   203  	// Embedded structs that allow config
   204  	// deserialization without the full struct.
   205  	CommonTLSOptions
   206  
   207  	// SwarmDefaultAdvertiseAddr is the default host/IP or network interface
   208  	// to use if a wildcard address is specified in the ListenAddr value
   209  	// given to the /swarm/init endpoint and no advertise address is
   210  	// specified.
   211  	SwarmDefaultAdvertiseAddr string `json:"swarm-default-advertise-addr"`
   212  
   213  	// SwarmRaftHeartbeatTick is the number of ticks in time for swarm mode raft quorum heartbeat
   214  	// Typical value is 1
   215  	SwarmRaftHeartbeatTick uint32 `json:"swarm-raft-heartbeat-tick"`
   216  
   217  	// SwarmRaftElectionTick is the number of ticks to elapse before followers in the quorum can propose
   218  	// a new round of leader election.  Default, recommended value is at least 10X that of Heartbeat tick.
   219  	// Higher values can make the quorum less sensitive to transient faults in the environment, but this also
   220  	// means it takes longer for the managers to detect a down leader.
   221  	SwarmRaftElectionTick uint32 `json:"swarm-raft-election-tick"`
   222  
   223  	MetricsAddress string `json:"metrics-addr"`
   224  
   225  	DNSConfig
   226  	LogConfig
   227  	BridgeConfig // BridgeConfig holds bridge network specific configuration.
   228  	NetworkConfig
   229  	registry.ServiceOptions
   230  
   231  	sync.Mutex
   232  	// FIXME(vdemeester) This part is not that clear and is mainly dependent on cli flags
   233  	// It should probably be handled outside this package.
   234  	ValuesSet map[string]interface{} `json:"-"`
   235  
   236  	Experimental bool `json:"experimental"` // Experimental indicates whether experimental features should be exposed or not
   237  
   238  	// Exposed node Generic Resources
   239  	// e.g: ["orange=red", "orange=green", "orange=blue", "apple=3"]
   240  	NodeGenericResources []string `json:"node-generic-resources,omitempty"`
   241  
   242  	// ContainerAddr is the address used to connect to containerd if we're
   243  	// not starting it ourselves
   244  	ContainerdAddr string `json:"containerd,omitempty"`
   245  
   246  	// CriContainerd determines whether a supervised containerd instance
   247  	// should be configured with the CRI plugin enabled. This allows using
   248  	// Docker's containerd instance directly with a Kubernetes kubelet.
   249  	CriContainerd bool `json:"cri-containerd,omitempty"`
   250  
   251  	// Features contains a list of feature key value pairs indicating what features are enabled or disabled.
   252  	// If a certain feature doesn't appear in this list then it's unset (i.e. neither true nor false).
   253  	Features map[string]bool `json:"features,omitempty"`
   254  
   255  	Builder BuilderConfig `json:"builder,omitempty"`
   256  
   257  	ContainerdNamespace       string `json:"containerd-namespace,omitempty"`
   258  	ContainerdPluginNamespace string `json:"containerd-plugin-namespace,omitempty"`
   259  
   260  	DefaultRuntime string `json:"default-runtime,omitempty"`
   261  }
   262  
   263  // Proxies holds the proxies that are configured for the daemon.
   264  type Proxies struct {
   265  	HTTPProxy  string `json:"http-proxy,omitempty"`
   266  	HTTPSProxy string `json:"https-proxy,omitempty"`
   267  	NoProxy    string `json:"no-proxy,omitempty"`
   268  }
   269  
   270  // IsValueSet returns true if a configuration value
   271  // was explicitly set in the configuration file.
   272  func (conf *Config) IsValueSet(name string) bool {
   273  	if conf.ValuesSet == nil {
   274  		return false
   275  	}
   276  	_, ok := conf.ValuesSet[name]
   277  	return ok
   278  }
   279  
   280  // New returns a new fully initialized Config struct with default values set.
   281  func New() (*Config, error) {
   282  	// platform-agnostic default values for the Config.
   283  	cfg := &Config{
   284  		CommonConfig: CommonConfig{
   285  			ShutdownTimeout: DefaultShutdownTimeout,
   286  			LogConfig: LogConfig{
   287  				Config: make(map[string]string),
   288  			},
   289  			MaxConcurrentDownloads: DefaultMaxConcurrentDownloads,
   290  			MaxConcurrentUploads:   DefaultMaxConcurrentUploads,
   291  			MaxDownloadAttempts:    DefaultDownloadAttempts,
   292  			Mtu:                    DefaultNetworkMtu,
   293  			NetworkConfig: NetworkConfig{
   294  				NetworkControlPlaneMTU: DefaultNetworkMtu,
   295  			},
   296  			ContainerdNamespace:       DefaultContainersNamespace,
   297  			ContainerdPluginNamespace: DefaultPluginNamespace,
   298  			DefaultRuntime:            StockRuntimeName,
   299  		},
   300  	}
   301  
   302  	if err := setPlatformDefaults(cfg); err != nil {
   303  		return nil, err
   304  	}
   305  
   306  	return cfg, nil
   307  }
   308  
   309  // GetConflictFreeLabels validates Labels for conflict
   310  // In swarm the duplicates for labels are removed
   311  // so we only take same values here, no conflict values
   312  // If the key-value is the same we will only take the last label
   313  func GetConflictFreeLabels(labels []string) ([]string, error) {
   314  	labelMap := map[string]string{}
   315  	for _, label := range labels {
   316  		stringSlice := strings.SplitN(label, "=", 2)
   317  		if len(stringSlice) > 1 {
   318  			// If there is a conflict we will return an error
   319  			if v, ok := labelMap[stringSlice[0]]; ok && v != stringSlice[1] {
   320  				return nil, errors.Errorf("conflict labels for %s=%s and %s=%s", stringSlice[0], stringSlice[1], stringSlice[0], v)
   321  			}
   322  			labelMap[stringSlice[0]] = stringSlice[1]
   323  		}
   324  	}
   325  
   326  	newLabels := []string{}
   327  	for k, v := range labelMap {
   328  		newLabels = append(newLabels, k+"="+v)
   329  	}
   330  	return newLabels, nil
   331  }
   332  
   333  // Reload reads the configuration in the host and reloads the daemon and server.
   334  func Reload(configFile string, flags *pflag.FlagSet, reload func(*Config)) error {
   335  	logrus.Infof("Got signal to reload configuration, reloading from: %s", configFile)
   336  	newConfig, err := getConflictFreeConfiguration(configFile, flags)
   337  	if err != nil {
   338  		if flags.Changed("config-file") || !os.IsNotExist(err) {
   339  			return errors.Wrapf(err, "unable to configure the Docker daemon with file %s", configFile)
   340  		}
   341  		newConfig, err = New()
   342  		if err != nil {
   343  			return err
   344  		}
   345  	}
   346  
   347  	// Check if duplicate label-keys with different values are found
   348  	newLabels, err := GetConflictFreeLabels(newConfig.Labels)
   349  	if err != nil {
   350  		return err
   351  	}
   352  	newConfig.Labels = newLabels
   353  
   354  	// TODO(thaJeztah) This logic is problematic and needs a rewrite;
   355  	// This is validating newConfig before the "reload()" callback is executed.
   356  	// At this point, newConfig may be a partial configuration, to be merged
   357  	// with the existing configuration in the "reload()" callback. Validating
   358  	// this config before it's merged can result in incorrect validation errors.
   359  	//
   360  	// However, the current "reload()" callback we use is DaemonCli.reloadConfig(),
   361  	// which includes a call to Daemon.Reload(), which both performs "merging"
   362  	// and validation, as well as actually updating the daemon configuration.
   363  	// Calling DaemonCli.reloadConfig() *before* validation, could thus lead to
   364  	// a failure in that function (making the reload non-atomic).
   365  	//
   366  	// While *some* errors could always occur when applying/updating the config,
   367  	// we should make it more atomic, and;
   368  	//
   369  	// 1. get (a copy of) the active configuration
   370  	// 2. get the new configuration
   371  	// 3. apply the (reloadable) options from the new configuration
   372  	// 4. validate the merged results
   373  	// 5. apply the new configuration.
   374  	if err := Validate(newConfig); err != nil {
   375  		return errors.Wrap(err, "file configuration validation failed")
   376  	}
   377  
   378  	reload(newConfig)
   379  	return nil
   380  }
   381  
   382  // boolValue is an interface that boolean value flags implement
   383  // to tell the command line how to make -name equivalent to -name=true.
   384  type boolValue interface {
   385  	IsBoolFlag() bool
   386  }
   387  
   388  // MergeDaemonConfigurations reads a configuration file,
   389  // loads the file configuration in an isolated structure,
   390  // and merges the configuration provided from flags on top
   391  // if there are no conflicts.
   392  func MergeDaemonConfigurations(flagsConfig *Config, flags *pflag.FlagSet, configFile string) (*Config, error) {
   393  	fileConfig, err := getConflictFreeConfiguration(configFile, flags)
   394  	if err != nil {
   395  		return nil, err
   396  	}
   397  
   398  	// merge flags configuration on top of the file configuration
   399  	if err := mergo.Merge(fileConfig, flagsConfig); err != nil {
   400  		return nil, err
   401  	}
   402  
   403  	// validate the merged fileConfig and flagsConfig
   404  	if err := Validate(fileConfig); err != nil {
   405  		return nil, errors.Wrap(err, "merged configuration validation from file and command line flags failed")
   406  	}
   407  
   408  	return fileConfig, nil
   409  }
   410  
   411  // getConflictFreeConfiguration loads the configuration from a JSON file.
   412  // It compares that configuration with the one provided by the flags,
   413  // and returns an error if there are conflicts.
   414  func getConflictFreeConfiguration(configFile string, flags *pflag.FlagSet) (*Config, error) {
   415  	b, err := os.ReadFile(configFile)
   416  	if err != nil {
   417  		return nil, err
   418  	}
   419  
   420  	var config Config
   421  
   422  	b = bytes.TrimSpace(b)
   423  	if len(b) == 0 {
   424  		// empty config file
   425  		return &config, nil
   426  	}
   427  
   428  	if flags != nil {
   429  		var jsonConfig map[string]interface{}
   430  		if err := json.Unmarshal(b, &jsonConfig); err != nil {
   431  			return nil, err
   432  		}
   433  
   434  		configSet := configValuesSet(jsonConfig)
   435  
   436  		if err := findConfigurationConflicts(configSet, flags); err != nil {
   437  			return nil, err
   438  		}
   439  
   440  		// Override flag values to make sure the values set in the config file with nullable values, like `false`,
   441  		// are not overridden by default truthy values from the flags that were not explicitly set.
   442  		// See https://github.com/docker/docker/issues/20289 for an example.
   443  		//
   444  		// TODO: Rewrite configuration logic to avoid same issue with other nullable values, like numbers.
   445  		namedOptions := make(map[string]interface{})
   446  		for key, value := range configSet {
   447  			f := flags.Lookup(key)
   448  			if f == nil { // ignore named flags that don't match
   449  				namedOptions[key] = value
   450  				continue
   451  			}
   452  
   453  			if _, ok := f.Value.(boolValue); ok {
   454  				f.Value.Set(fmt.Sprintf("%v", value))
   455  			}
   456  		}
   457  		if len(namedOptions) > 0 {
   458  			// set also default for mergeVal flags that are boolValue at the same time.
   459  			flags.VisitAll(func(f *pflag.Flag) {
   460  				if opt, named := f.Value.(opts.NamedOption); named {
   461  					v, set := namedOptions[opt.Name()]
   462  					_, boolean := f.Value.(boolValue)
   463  					if set && boolean {
   464  						f.Value.Set(fmt.Sprintf("%v", v))
   465  					}
   466  				}
   467  			})
   468  		}
   469  
   470  		config.ValuesSet = configSet
   471  	}
   472  
   473  	if err := json.Unmarshal(b, &config); err != nil {
   474  		return nil, err
   475  	}
   476  
   477  	return &config, nil
   478  }
   479  
   480  // configValuesSet returns the configuration values explicitly set in the file.
   481  func configValuesSet(config map[string]interface{}) map[string]interface{} {
   482  	flatten := make(map[string]interface{})
   483  	for k, v := range config {
   484  		if m, isMap := v.(map[string]interface{}); isMap && !flatOptions[k] {
   485  			for km, vm := range m {
   486  				flatten[km] = vm
   487  			}
   488  			continue
   489  		}
   490  
   491  		flatten[k] = v
   492  	}
   493  	return flatten
   494  }
   495  
   496  // findConfigurationConflicts iterates over the provided flags searching for
   497  // duplicated configurations and unknown keys. It returns an error with all the conflicts if
   498  // it finds any.
   499  func findConfigurationConflicts(config map[string]interface{}, flags *pflag.FlagSet) error {
   500  	// 1. Search keys from the file that we don't recognize as flags.
   501  	unknownKeys := make(map[string]interface{})
   502  	for key, value := range config {
   503  		if flag := flags.Lookup(key); flag == nil && !skipValidateOptions[key] {
   504  			unknownKeys[key] = value
   505  		}
   506  	}
   507  
   508  	// 2. Discard values that implement NamedOption.
   509  	// Their configuration name differs from their flag name, like `labels` and `label`.
   510  	if len(unknownKeys) > 0 {
   511  		unknownNamedConflicts := func(f *pflag.Flag) {
   512  			if namedOption, ok := f.Value.(opts.NamedOption); ok {
   513  				delete(unknownKeys, namedOption.Name())
   514  			}
   515  		}
   516  		flags.VisitAll(unknownNamedConflicts)
   517  	}
   518  
   519  	if len(unknownKeys) > 0 {
   520  		var unknown []string
   521  		for key := range unknownKeys {
   522  			unknown = append(unknown, key)
   523  		}
   524  		return errors.Errorf("the following directives don't match any configuration option: %s", strings.Join(unknown, ", "))
   525  	}
   526  
   527  	var conflicts []string
   528  	printConflict := func(name string, flagValue, fileValue interface{}) string {
   529  		switch name {
   530  		case "http-proxy", "https-proxy":
   531  			flagValue = MaskCredentials(flagValue.(string))
   532  			fileValue = MaskCredentials(fileValue.(string))
   533  		}
   534  		return fmt.Sprintf("%s: (from flag: %v, from file: %v)", name, flagValue, fileValue)
   535  	}
   536  
   537  	// 3. Search keys that are present as a flag and as a file option.
   538  	duplicatedConflicts := func(f *pflag.Flag) {
   539  		// search option name in the json configuration payload if the value is a named option
   540  		if namedOption, ok := f.Value.(opts.NamedOption); ok {
   541  			if optsValue, ok := config[namedOption.Name()]; ok && !skipDuplicates[namedOption.Name()] {
   542  				conflicts = append(conflicts, printConflict(namedOption.Name(), f.Value.String(), optsValue))
   543  			}
   544  		} else {
   545  			// search flag name in the json configuration payload
   546  			for _, name := range []string{f.Name, f.Shorthand} {
   547  				if value, ok := config[name]; ok && !skipDuplicates[name] {
   548  					conflicts = append(conflicts, printConflict(name, f.Value.String(), value))
   549  					break
   550  				}
   551  			}
   552  		}
   553  	}
   554  
   555  	flags.Visit(duplicatedConflicts)
   556  
   557  	if len(conflicts) > 0 {
   558  		return errors.Errorf("the following directives are specified both as a flag and in the configuration file: %s", strings.Join(conflicts, ", "))
   559  	}
   560  	return nil
   561  }
   562  
   563  // Validate validates some specific configs.
   564  // such as config.DNS, config.Labels, config.DNSSearch,
   565  // as well as config.MaxConcurrentDownloads, config.MaxConcurrentUploads and config.MaxDownloadAttempts.
   566  func Validate(config *Config) error {
   567  	//nolint:staticcheck // TODO(thaJeztah): remove in next release.
   568  	if config.RootDeprecated != "" {
   569  		return errors.New(`the "graph" config file option is deprecated; use "data-root" instead`)
   570  	}
   571  
   572  	// validate log-level
   573  	if config.LogLevel != "" {
   574  		if _, err := logrus.ParseLevel(config.LogLevel); err != nil {
   575  			return errors.Errorf("invalid logging level: %s", config.LogLevel)
   576  		}
   577  	}
   578  
   579  	// validate DNS
   580  	for _, dns := range config.DNS {
   581  		if _, err := opts.ValidateIPAddress(dns); err != nil {
   582  			return err
   583  		}
   584  	}
   585  
   586  	// validate DNSSearch
   587  	for _, dnsSearch := range config.DNSSearch {
   588  		if _, err := opts.ValidateDNSSearch(dnsSearch); err != nil {
   589  			return err
   590  		}
   591  	}
   592  
   593  	// validate Labels
   594  	for _, label := range config.Labels {
   595  		if _, err := opts.ValidateLabel(label); err != nil {
   596  			return err
   597  		}
   598  	}
   599  
   600  	// TODO(thaJeztah) Validations below should not accept "0" to be valid; see Validate() for a more in-depth description of this problem
   601  	if config.Mtu < 0 {
   602  		return errors.Errorf("invalid default MTU: %d", config.Mtu)
   603  	}
   604  	if config.MaxConcurrentDownloads < 0 {
   605  		return errors.Errorf("invalid max concurrent downloads: %d", config.MaxConcurrentDownloads)
   606  	}
   607  	if config.MaxConcurrentUploads < 0 {
   608  		return errors.Errorf("invalid max concurrent uploads: %d", config.MaxConcurrentUploads)
   609  	}
   610  	if config.MaxDownloadAttempts < 0 {
   611  		return errors.Errorf("invalid max download attempts: %d", config.MaxDownloadAttempts)
   612  	}
   613  
   614  	// validate that "default" runtime is not reset
   615  	if runtimes := config.GetAllRuntimes(); len(runtimes) > 0 {
   616  		if _, ok := runtimes[StockRuntimeName]; ok {
   617  			return errors.Errorf("runtime name '%s' is reserved", StockRuntimeName)
   618  		}
   619  	}
   620  
   621  	if _, err := ParseGenericResources(config.NodeGenericResources); err != nil {
   622  		return err
   623  	}
   624  
   625  	if defaultRuntime := config.GetDefaultRuntimeName(); defaultRuntime != "" {
   626  		if !builtinRuntimes[defaultRuntime] {
   627  			runtimes := config.GetAllRuntimes()
   628  			if _, ok := runtimes[defaultRuntime]; !ok && !IsPermissibleC8dRuntimeName(defaultRuntime) {
   629  				return errors.Errorf("specified default runtime '%s' does not exist", defaultRuntime)
   630  			}
   631  		}
   632  	}
   633  
   634  	for _, h := range config.Hosts {
   635  		if _, err := opts.ValidateHost(h); err != nil {
   636  			return err
   637  		}
   638  	}
   639  
   640  	// validate platform-specific settings
   641  	return config.ValidatePlatformConfig()
   642  }
   643  
   644  // GetDefaultRuntimeName returns the current default runtime
   645  func (conf *Config) GetDefaultRuntimeName() string {
   646  	conf.Lock()
   647  	rt := conf.DefaultRuntime
   648  	conf.Unlock()
   649  
   650  	return rt
   651  }
   652  
   653  // MaskCredentials masks credentials that are in an URL.
   654  func MaskCredentials(rawURL string) string {
   655  	parsedURL, err := url.Parse(rawURL)
   656  	if err != nil || parsedURL.User == nil {
   657  		return rawURL
   658  	}
   659  	parsedURL.User = url.UserPassword("xxxxx", "xxxxx")
   660  	return parsedURL.String()
   661  }
   662  
   663  // IsPermissibleC8dRuntimeName tests whether name is safe to pass into
   664  // containerd as a runtime name, and whether the name is well-formed.
   665  // It does not check if the runtime is installed.
   666  //
   667  // A runtime name containing slash characters is interpreted by containerd as
   668  // the path to a runtime binary. If we allowed this, anyone with Engine API
   669  // access could get containerd to execute an arbitrary binary as root. Although
   670  // Engine API access is already equivalent to root on the host, the runtime name
   671  // has not historically been a vector to run arbitrary code as root so users are
   672  // not expecting it to become one.
   673  //
   674  // This restriction is not configurable. There are viable workarounds for
   675  // legitimate use cases: administrators and runtime developers can make runtimes
   676  // available for use with Docker by installing them onto PATH following the
   677  // [binary naming convention] for containerd Runtime v2.
   678  //
   679  // [binary naming convention]: https://github.com/containerd/containerd/blob/main/runtime/v2/README.md#binary-naming
   680  func IsPermissibleC8dRuntimeName(name string) bool {
   681  	// containerd uses a rather permissive test to validate runtime names:
   682  	//
   683  	//   - Any name for which filepath.IsAbs(name) is interpreted as the absolute
   684  	//     path to a shim binary. We want to block this behaviour.
   685  	//   - Any name which contains at least one '.' character and no '/' characters
   686  	//     and does not begin with a '.' character is a valid runtime name. The shim
   687  	//     binary name is derived from the final two components of the name and
   688  	//     searched for on the PATH. The name "a.." is technically valid per
   689  	//     containerd's implementation: it would resolve to a binary named
   690  	//     "containerd-shim---".
   691  	//
   692  	// https://github.com/containerd/containerd/blob/11ded166c15f92450958078cd13c6d87131ec563/runtime/v2/manager.go#L297-L317
   693  	// https://github.com/containerd/containerd/blob/11ded166c15f92450958078cd13c6d87131ec563/runtime/v2/shim/util.go#L83-L93
   694  	return !filepath.IsAbs(name) && !strings.ContainsRune(name, '/') && shim.BinaryName(name) != ""
   695  }