github.com/zhouyu0/docker-note@v0.0.0-20190722021225-b8d3825084db/registry/config.go (about)

     1  package registry // import "github.com/docker/docker/registry"
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  	"net/url"
     7  	"regexp"
     8  	"strconv"
     9  	"strings"
    10  
    11  	"github.com/docker/distribution/reference"
    12  	registrytypes "github.com/docker/docker/api/types/registry"
    13  	"github.com/pkg/errors"
    14  	"github.com/sirupsen/logrus"
    15  )
    16  
    17  // ServiceOptions holds command line options.
    18  type ServiceOptions struct {
    19  	AllowNondistributableArtifacts []string `json:"allow-nondistributable-artifacts,omitempty"`
    20  	Mirrors                        []string `json:"registry-mirrors,omitempty"`
    21  	InsecureRegistries             []string `json:"insecure-registries,omitempty"`
    22  
    23  	// V2Only controls access to legacy registries.  If it is set to true via the
    24  	// command line flag the daemon will not attempt to contact v1 legacy registries
    25  	V2Only bool `json:"disable-legacy-registry,omitempty"`
    26  }
    27  
    28  // serviceConfig holds daemon configuration for the registry service.
    29  type serviceConfig struct {
    30  	registrytypes.ServiceConfig
    31  	V2Only bool
    32  }
    33  
    34  var (
    35  	// DefaultNamespace is the default namespace
    36  	DefaultNamespace = "docker.io"
    37  	// DefaultRegistryVersionHeader is the name of the default HTTP header
    38  	// that carries Registry version info
    39  	DefaultRegistryVersionHeader = "Docker-Distribution-Api-Version"
    40  
    41  	// IndexHostname is the index hostname
    42  	IndexHostname = "index.docker.io"
    43  	// IndexServer is used for user auth and image search
    44  	IndexServer = "https://" + IndexHostname + "/v1/"
    45  	// IndexName is the name of the index
    46  	IndexName = "docker.io"
    47  
    48  	// DefaultV2Registry is the URI of the default v2 registry
    49  	DefaultV2Registry = &url.URL{
    50  		Scheme: "https",
    51  		Host:   "registry-1.docker.io",
    52  	}
    53  )
    54  
    55  var (
    56  	// ErrInvalidRepositoryName is an error returned if the repository name did
    57  	// not have the correct form
    58  	ErrInvalidRepositoryName = errors.New("Invalid repository name (ex: \"registry.domain.tld/myrepos\")")
    59  
    60  	emptyServiceConfig, _ = newServiceConfig(ServiceOptions{})
    61  )
    62  
    63  var (
    64  	validHostPortRegex = regexp.MustCompile(`^` + reference.DomainRegexp.String() + `$`)
    65  )
    66  
    67  // for mocking in unit tests
    68  var lookupIP = net.LookupIP
    69  
    70  // newServiceConfig returns a new instance of ServiceConfig
    71  func newServiceConfig(options ServiceOptions) (*serviceConfig, error) {
    72  	config := &serviceConfig{
    73  		ServiceConfig: registrytypes.ServiceConfig{
    74  			InsecureRegistryCIDRs: make([]*registrytypes.NetIPNet, 0),
    75  			IndexConfigs:          make(map[string]*registrytypes.IndexInfo),
    76  			// Hack: Bypass setting the mirrors to IndexConfigs since they are going away
    77  			// and Mirrors are only for the official registry anyways.
    78  		},
    79  		V2Only: options.V2Only,
    80  	}
    81  	if err := config.LoadAllowNondistributableArtifacts(options.AllowNondistributableArtifacts); err != nil {
    82  		return nil, err
    83  	}
    84  	if err := config.LoadMirrors(options.Mirrors); err != nil {
    85  		return nil, err
    86  	}
    87  	if err := config.LoadInsecureRegistries(options.InsecureRegistries); err != nil {
    88  		return nil, err
    89  	}
    90  
    91  	return config, nil
    92  }
    93  
    94  // LoadAllowNondistributableArtifacts loads allow-nondistributable-artifacts registries into config.
    95  func (config *serviceConfig) LoadAllowNondistributableArtifacts(registries []string) error {
    96  	cidrs := map[string]*registrytypes.NetIPNet{}
    97  	hostnames := map[string]bool{}
    98  
    99  	for _, r := range registries {
   100  		if _, err := ValidateIndexName(r); err != nil {
   101  			return err
   102  		}
   103  		if validateNoScheme(r) != nil {
   104  			return fmt.Errorf("allow-nondistributable-artifacts registry %s should not contain '://'", r)
   105  		}
   106  
   107  		if _, ipnet, err := net.ParseCIDR(r); err == nil {
   108  			// Valid CIDR.
   109  			cidrs[ipnet.String()] = (*registrytypes.NetIPNet)(ipnet)
   110  		} else if err := validateHostPort(r); err == nil {
   111  			// Must be `host:port` if not CIDR.
   112  			hostnames[r] = true
   113  		} else {
   114  			return fmt.Errorf("allow-nondistributable-artifacts registry %s is not valid: %v", r, err)
   115  		}
   116  	}
   117  
   118  	config.AllowNondistributableArtifactsCIDRs = make([]*(registrytypes.NetIPNet), 0)
   119  	for _, c := range cidrs {
   120  		config.AllowNondistributableArtifactsCIDRs = append(config.AllowNondistributableArtifactsCIDRs, c)
   121  	}
   122  
   123  	config.AllowNondistributableArtifactsHostnames = make([]string, 0)
   124  	for h := range hostnames {
   125  		config.AllowNondistributableArtifactsHostnames = append(config.AllowNondistributableArtifactsHostnames, h)
   126  	}
   127  
   128  	return nil
   129  }
   130  
   131  // LoadMirrors loads mirrors to config, after removing duplicates.
   132  // Returns an error if mirrors contains an invalid mirror.
   133  func (config *serviceConfig) LoadMirrors(mirrors []string) error {
   134  	mMap := map[string]struct{}{}
   135  	unique := []string{}
   136  
   137  	for _, mirror := range mirrors {
   138  		m, err := ValidateMirror(mirror)
   139  		if err != nil {
   140  			return err
   141  		}
   142  		if _, exist := mMap[m]; !exist {
   143  			mMap[m] = struct{}{}
   144  			unique = append(unique, m)
   145  		}
   146  	}
   147  
   148  	config.Mirrors = unique
   149  
   150  	// Configure public registry since mirrors may have changed.
   151  	config.IndexConfigs[IndexName] = &registrytypes.IndexInfo{
   152  		Name:     IndexName,
   153  		Mirrors:  config.Mirrors,
   154  		Secure:   true,
   155  		Official: true,
   156  	}
   157  
   158  	return nil
   159  }
   160  
   161  // LoadInsecureRegistries loads insecure registries to config
   162  func (config *serviceConfig) LoadInsecureRegistries(registries []string) error {
   163  	// Localhost is by default considered as an insecure registry
   164  	// This is a stop-gap for people who are running a private registry on localhost (especially on Boot2docker).
   165  	//
   166  	// TODO: should we deprecate this once it is easier for people to set up a TLS registry or change
   167  	// daemon flags on boot2docker?
   168  	registries = append(registries, "127.0.0.0/8")
   169  
   170  	// Store original InsecureRegistryCIDRs and IndexConfigs
   171  	// Clean InsecureRegistryCIDRs and IndexConfigs in config, as passed registries has all insecure registry info.
   172  	originalCIDRs := config.ServiceConfig.InsecureRegistryCIDRs
   173  	originalIndexInfos := config.ServiceConfig.IndexConfigs
   174  
   175  	config.ServiceConfig.InsecureRegistryCIDRs = make([]*registrytypes.NetIPNet, 0)
   176  	config.ServiceConfig.IndexConfigs = make(map[string]*registrytypes.IndexInfo)
   177  
   178  skip:
   179  	for _, r := range registries {
   180  		// validate insecure registry
   181  		if _, err := ValidateIndexName(r); err != nil {
   182  			// before returning err, roll back to original data
   183  			config.ServiceConfig.InsecureRegistryCIDRs = originalCIDRs
   184  			config.ServiceConfig.IndexConfigs = originalIndexInfos
   185  			return err
   186  		}
   187  		if strings.HasPrefix(strings.ToLower(r), "http://") {
   188  			logrus.Warnf("insecure registry %s should not contain 'http://' and 'http://' has been removed from the insecure registry config", r)
   189  			r = r[7:]
   190  		} else if strings.HasPrefix(strings.ToLower(r), "https://") {
   191  			logrus.Warnf("insecure registry %s should not contain 'https://' and 'https://' has been removed from the insecure registry config", r)
   192  			r = r[8:]
   193  		} else if validateNoScheme(r) != nil {
   194  			// Insecure registry should not contain '://'
   195  			// before returning err, roll back to original data
   196  			config.ServiceConfig.InsecureRegistryCIDRs = originalCIDRs
   197  			config.ServiceConfig.IndexConfigs = originalIndexInfos
   198  			return fmt.Errorf("insecure registry %s should not contain '://'", r)
   199  		}
   200  		// Check if CIDR was passed to --insecure-registry
   201  		_, ipnet, err := net.ParseCIDR(r)
   202  		if err == nil {
   203  			// Valid CIDR. If ipnet is already in config.InsecureRegistryCIDRs, skip.
   204  			data := (*registrytypes.NetIPNet)(ipnet)
   205  			for _, value := range config.InsecureRegistryCIDRs {
   206  				if value.IP.String() == data.IP.String() && value.Mask.String() == data.Mask.String() {
   207  					continue skip
   208  				}
   209  			}
   210  			// ipnet is not found, add it in config.InsecureRegistryCIDRs
   211  			config.InsecureRegistryCIDRs = append(config.InsecureRegistryCIDRs, data)
   212  
   213  		} else {
   214  			if err := validateHostPort(r); err != nil {
   215  				config.ServiceConfig.InsecureRegistryCIDRs = originalCIDRs
   216  				config.ServiceConfig.IndexConfigs = originalIndexInfos
   217  				return fmt.Errorf("insecure registry %s is not valid: %v", r, err)
   218  
   219  			}
   220  			// Assume `host:port` if not CIDR.
   221  			config.IndexConfigs[r] = &registrytypes.IndexInfo{
   222  				Name:     r,
   223  				Mirrors:  make([]string, 0),
   224  				Secure:   false,
   225  				Official: false,
   226  			}
   227  		}
   228  	}
   229  
   230  	// Configure public registry.
   231  	config.IndexConfigs[IndexName] = &registrytypes.IndexInfo{
   232  		Name:     IndexName,
   233  		Mirrors:  config.Mirrors,
   234  		Secure:   true,
   235  		Official: true,
   236  	}
   237  
   238  	return nil
   239  }
   240  
   241  // allowNondistributableArtifacts returns true if the provided hostname is part of the list of registries
   242  // that allow push of nondistributable artifacts.
   243  //
   244  // The list can contain elements with CIDR notation to specify a whole subnet. If the subnet contains an IP
   245  // of the registry specified by hostname, true is returned.
   246  //
   247  // hostname should be a URL.Host (`host:port` or `host`) where the `host` part can be either a domain name
   248  // or an IP address. If it is a domain name, then it will be resolved to IP addresses for matching. If
   249  // resolution fails, CIDR matching is not performed.
   250  func allowNondistributableArtifacts(config *serviceConfig, hostname string) bool {
   251  	for _, h := range config.AllowNondistributableArtifactsHostnames {
   252  		if h == hostname {
   253  			return true
   254  		}
   255  	}
   256  
   257  	return isCIDRMatch(config.AllowNondistributableArtifactsCIDRs, hostname)
   258  }
   259  
   260  // isSecureIndex returns false if the provided indexName is part of the list of insecure registries
   261  // Insecure registries accept HTTP and/or accept HTTPS with certificates from unknown CAs.
   262  //
   263  // The list of insecure registries can contain an element with CIDR notation to specify a whole subnet.
   264  // If the subnet contains one of the IPs of the registry specified by indexName, the latter is considered
   265  // insecure.
   266  //
   267  // indexName should be a URL.Host (`host:port` or `host`) where the `host` part can be either a domain name
   268  // or an IP address. If it is a domain name, then it will be resolved in order to check if the IP is contained
   269  // in a subnet. If the resolving is not successful, isSecureIndex will only try to match hostname to any element
   270  // of insecureRegistries.
   271  func isSecureIndex(config *serviceConfig, indexName string) bool {
   272  	// Check for configured index, first.  This is needed in case isSecureIndex
   273  	// is called from anything besides newIndexInfo, in order to honor per-index configurations.
   274  	if index, ok := config.IndexConfigs[indexName]; ok {
   275  		return index.Secure
   276  	}
   277  
   278  	return !isCIDRMatch(config.InsecureRegistryCIDRs, indexName)
   279  }
   280  
   281  // isCIDRMatch returns true if URLHost matches an element of cidrs. URLHost is a URL.Host (`host:port` or `host`)
   282  // where the `host` part can be either a domain name or an IP address. If it is a domain name, then it will be
   283  // resolved to IP addresses for matching. If resolution fails, false is returned.
   284  func isCIDRMatch(cidrs []*registrytypes.NetIPNet, URLHost string) bool {
   285  	host, _, err := net.SplitHostPort(URLHost)
   286  	if err != nil {
   287  		// Assume URLHost is of the form `host` without the port and go on.
   288  		host = URLHost
   289  	}
   290  
   291  	addrs, err := lookupIP(host)
   292  	if err != nil {
   293  		ip := net.ParseIP(host)
   294  		if ip != nil {
   295  			addrs = []net.IP{ip}
   296  		}
   297  
   298  		// if ip == nil, then `host` is neither an IP nor it could be looked up,
   299  		// either because the index is unreachable, or because the index is behind an HTTP proxy.
   300  		// So, len(addrs) == 0 and we're not aborting.
   301  	}
   302  
   303  	// Try CIDR notation only if addrs has any elements, i.e. if `host`'s IP could be determined.
   304  	for _, addr := range addrs {
   305  		for _, ipnet := range cidrs {
   306  			// check if the addr falls in the subnet
   307  			if (*net.IPNet)(ipnet).Contains(addr) {
   308  				return true
   309  			}
   310  		}
   311  	}
   312  
   313  	return false
   314  }
   315  
   316  // ValidateMirror validates an HTTP(S) registry mirror
   317  func ValidateMirror(val string) (string, error) {
   318  	uri, err := url.Parse(val)
   319  	if err != nil {
   320  		return "", fmt.Errorf("invalid mirror: %q is not a valid URI", val)
   321  	}
   322  	if uri.Scheme != "http" && uri.Scheme != "https" {
   323  		return "", fmt.Errorf("invalid mirror: unsupported scheme %q in %q", uri.Scheme, uri)
   324  	}
   325  	if (uri.Path != "" && uri.Path != "/") || uri.RawQuery != "" || uri.Fragment != "" {
   326  		return "", fmt.Errorf("invalid mirror: path, query, or fragment at end of the URI %q", uri)
   327  	}
   328  	if uri.User != nil {
   329  		// strip password from output
   330  		uri.User = url.UserPassword(uri.User.Username(), "xxxxx")
   331  		return "", fmt.Errorf("invalid mirror: username/password not allowed in URI %q", uri)
   332  	}
   333  	return strings.TrimSuffix(val, "/") + "/", nil
   334  }
   335  
   336  // ValidateIndexName validates an index name.
   337  func ValidateIndexName(val string) (string, error) {
   338  	// TODO: upstream this to check to reference package
   339  	if val == "index.docker.io" {
   340  		val = "docker.io"
   341  	}
   342  	if strings.HasPrefix(val, "-") || strings.HasSuffix(val, "-") {
   343  		return "", fmt.Errorf("invalid index name (%s). Cannot begin or end with a hyphen", val)
   344  	}
   345  	return val, nil
   346  }
   347  
   348  func validateNoScheme(reposName string) error {
   349  	if strings.Contains(reposName, "://") {
   350  		// It cannot contain a scheme!
   351  		return ErrInvalidRepositoryName
   352  	}
   353  	return nil
   354  }
   355  
   356  func validateHostPort(s string) error {
   357  	// Split host and port, and in case s can not be splitted, assume host only
   358  	host, port, err := net.SplitHostPort(s)
   359  	if err != nil {
   360  		host = s
   361  		port = ""
   362  	}
   363  	// If match against the `host:port` pattern fails,
   364  	// it might be `IPv6:port`, which will be captured by net.ParseIP(host)
   365  	if !validHostPortRegex.MatchString(s) && net.ParseIP(host) == nil {
   366  		return fmt.Errorf("invalid host %q", host)
   367  	}
   368  	if port != "" {
   369  		v, err := strconv.Atoi(port)
   370  		if err != nil {
   371  			return err
   372  		}
   373  		if v < 0 || v > 65535 {
   374  			return fmt.Errorf("invalid port %q", port)
   375  		}
   376  	}
   377  	return nil
   378  }
   379  
   380  // newIndexInfo returns IndexInfo configuration from indexName
   381  func newIndexInfo(config *serviceConfig, indexName string) (*registrytypes.IndexInfo, error) {
   382  	var err error
   383  	indexName, err = ValidateIndexName(indexName)
   384  	if err != nil {
   385  		return nil, err
   386  	}
   387  
   388  	// Return any configured index info, first.
   389  	if index, ok := config.IndexConfigs[indexName]; ok {
   390  		return index, nil
   391  	}
   392  
   393  	// Construct a non-configured index info.
   394  	index := &registrytypes.IndexInfo{
   395  		Name:     indexName,
   396  		Mirrors:  make([]string, 0),
   397  		Official: false,
   398  	}
   399  	index.Secure = isSecureIndex(config, indexName)
   400  	return index, nil
   401  }
   402  
   403  // GetAuthConfigKey special-cases using the full index address of the official
   404  // index as the AuthConfig key, and uses the (host)name[:port] for private indexes.
   405  func GetAuthConfigKey(index *registrytypes.IndexInfo) string {
   406  	if index.Official {
   407  		return IndexServer
   408  	}
   409  	return index.Name
   410  }
   411  
   412  // newRepositoryInfo validates and breaks down a repository name into a RepositoryInfo
   413  func newRepositoryInfo(config *serviceConfig, name reference.Named) (*RepositoryInfo, error) {
   414  	index, err := newIndexInfo(config, reference.Domain(name))
   415  	if err != nil {
   416  		return nil, err
   417  	}
   418  	official := !strings.ContainsRune(reference.FamiliarName(name), '/')
   419  
   420  	return &RepositoryInfo{
   421  		Name:     reference.TrimNamed(name),
   422  		Index:    index,
   423  		Official: official,
   424  	}, nil
   425  }
   426  
   427  // ParseRepositoryInfo performs the breakdown of a repository name into a RepositoryInfo, but
   428  // lacks registry configuration.
   429  func ParseRepositoryInfo(reposName reference.Named) (*RepositoryInfo, error) {
   430  	return newRepositoryInfo(emptyServiceConfig, reposName)
   431  }
   432  
   433  // ParseSearchIndexInfo will use repository name to get back an indexInfo.
   434  func ParseSearchIndexInfo(reposName string) (*registrytypes.IndexInfo, error) {
   435  	indexName, _ := splitReposSearchTerm(reposName)
   436  
   437  	indexInfo, err := newIndexInfo(emptyServiceConfig, indexName)
   438  	if err != nil {
   439  		return nil, err
   440  	}
   441  	return indexInfo, nil
   442  }