github.com/torfuzx/docker@v1.8.1/registry/config.go (about)

     1  package registry
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"fmt"
     7  	"net"
     8  	"net/url"
     9  	"strings"
    10  
    11  	"github.com/docker/distribution/registry/api/v2"
    12  	"github.com/docker/docker/image"
    13  	"github.com/docker/docker/opts"
    14  	flag "github.com/docker/docker/pkg/mflag"
    15  )
    16  
    17  // Options holds command line options.
    18  type Options struct {
    19  	Mirrors            opts.ListOpts
    20  	InsecureRegistries opts.ListOpts
    21  }
    22  
    23  const (
    24  	// DefaultNamespace is the default namespace
    25  	DefaultNamespace = "docker.io"
    26  	// DefaultV2Registry is the URI of the default v2 registry
    27  	DefaultV2Registry = "https://registry-1.docker.io"
    28  	// DefaultRegistryVersionHeader is the name of the default HTTP header
    29  	// that carries Registry version info
    30  	DefaultRegistryVersionHeader = "Docker-Distribution-Api-Version"
    31  	// DefaultV1Registry is the URI of the default v1 registry
    32  	DefaultV1Registry = "https://index.docker.io"
    33  
    34  	// CertsDir is the directory where certificates are stored
    35  	CertsDir = "/etc/docker/certs.d"
    36  
    37  	// IndexServer is the v1 registry server used for user auth + account creation
    38  	IndexServer = DefaultV1Registry + "/v1/"
    39  	// IndexName is the name of the index
    40  	IndexName = "docker.io"
    41  	// NotaryServer is the endpoint serving the Notary trust server
    42  	NotaryServer = "https://notary.docker.io"
    43  )
    44  
    45  var (
    46  	// ErrInvalidRepositoryName is an error returned if the repository name did
    47  	// not have the correct form
    48  	ErrInvalidRepositoryName = errors.New("Invalid repository name (ex: \"registry.domain.tld/myrepos\")")
    49  
    50  	emptyServiceConfig = NewServiceConfig(nil)
    51  )
    52  
    53  // InstallFlags adds command-line options to the top-level flag parser for
    54  // the current process.
    55  func (options *Options) InstallFlags(cmd *flag.FlagSet, usageFn func(string) string) {
    56  	options.Mirrors = opts.NewListOpts(ValidateMirror)
    57  	cmd.Var(&options.Mirrors, []string{"-registry-mirror"}, usageFn("Preferred Docker registry mirror"))
    58  	options.InsecureRegistries = opts.NewListOpts(ValidateIndexName)
    59  	cmd.Var(&options.InsecureRegistries, []string{"-insecure-registry"}, usageFn("Enable insecure registry communication"))
    60  }
    61  
    62  type netIPNet net.IPNet
    63  
    64  func (ipnet *netIPNet) MarshalJSON() ([]byte, error) {
    65  	return json.Marshal((*net.IPNet)(ipnet).String())
    66  }
    67  
    68  func (ipnet *netIPNet) UnmarshalJSON(b []byte) (err error) {
    69  	var ipnetStr string
    70  	if err = json.Unmarshal(b, &ipnetStr); err == nil {
    71  		var cidr *net.IPNet
    72  		if _, cidr, err = net.ParseCIDR(ipnetStr); err == nil {
    73  			*ipnet = netIPNet(*cidr)
    74  		}
    75  	}
    76  	return
    77  }
    78  
    79  // ServiceConfig stores daemon registry services configuration.
    80  type ServiceConfig struct {
    81  	InsecureRegistryCIDRs []*netIPNet           `json:"InsecureRegistryCIDRs"`
    82  	IndexConfigs          map[string]*IndexInfo `json:"IndexConfigs"`
    83  	Mirrors               []string
    84  }
    85  
    86  // NewServiceConfig returns a new instance of ServiceConfig
    87  func NewServiceConfig(options *Options) *ServiceConfig {
    88  	if options == nil {
    89  		options = &Options{
    90  			Mirrors:            opts.NewListOpts(nil),
    91  			InsecureRegistries: opts.NewListOpts(nil),
    92  		}
    93  	}
    94  
    95  	// Localhost is by default considered as an insecure registry
    96  	// This is a stop-gap for people who are running a private registry on localhost (especially on Boot2docker).
    97  	//
    98  	// TODO: should we deprecate this once it is easier for people to set up a TLS registry or change
    99  	// daemon flags on boot2docker?
   100  	options.InsecureRegistries.Set("127.0.0.0/8")
   101  
   102  	config := &ServiceConfig{
   103  		InsecureRegistryCIDRs: make([]*netIPNet, 0),
   104  		IndexConfigs:          make(map[string]*IndexInfo, 0),
   105  		// Hack: Bypass setting the mirrors to IndexConfigs since they are going away
   106  		// and Mirrors are only for the official registry anyways.
   107  		Mirrors: options.Mirrors.GetAll(),
   108  	}
   109  	// Split --insecure-registry into CIDR and registry-specific settings.
   110  	for _, r := range options.InsecureRegistries.GetAll() {
   111  		// Check if CIDR was passed to --insecure-registry
   112  		_, ipnet, err := net.ParseCIDR(r)
   113  		if err == nil {
   114  			// Valid CIDR.
   115  			config.InsecureRegistryCIDRs = append(config.InsecureRegistryCIDRs, (*netIPNet)(ipnet))
   116  		} else {
   117  			// Assume `host:port` if not CIDR.
   118  			config.IndexConfigs[r] = &IndexInfo{
   119  				Name:     r,
   120  				Mirrors:  make([]string, 0),
   121  				Secure:   false,
   122  				Official: false,
   123  			}
   124  		}
   125  	}
   126  
   127  	// Configure public registry.
   128  	config.IndexConfigs[IndexName] = &IndexInfo{
   129  		Name:     IndexName,
   130  		Mirrors:  config.Mirrors,
   131  		Secure:   true,
   132  		Official: true,
   133  	}
   134  
   135  	return config
   136  }
   137  
   138  // isSecureIndex returns false if the provided indexName is part of the list of insecure registries
   139  // Insecure registries accept HTTP and/or accept HTTPS with certificates from unknown CAs.
   140  //
   141  // The list of insecure registries can contain an element with CIDR notation to specify a whole subnet.
   142  // If the subnet contains one of the IPs of the registry specified by indexName, the latter is considered
   143  // insecure.
   144  //
   145  // indexName should be a URL.Host (`host:port` or `host`) where the `host` part can be either a domain name
   146  // or an IP address. If it is a domain name, then it will be resolved in order to check if the IP is contained
   147  // in a subnet. If the resolving is not successful, isSecureIndex will only try to match hostname to any element
   148  // of insecureRegistries.
   149  func (config *ServiceConfig) isSecureIndex(indexName string) bool {
   150  	// Check for configured index, first.  This is needed in case isSecureIndex
   151  	// is called from anything besides NewIndexInfo, in order to honor per-index configurations.
   152  	if index, ok := config.IndexConfigs[indexName]; ok {
   153  		return index.Secure
   154  	}
   155  
   156  	host, _, err := net.SplitHostPort(indexName)
   157  	if err != nil {
   158  		// assume indexName is of the form `host` without the port and go on.
   159  		host = indexName
   160  	}
   161  
   162  	addrs, err := lookupIP(host)
   163  	if err != nil {
   164  		ip := net.ParseIP(host)
   165  		if ip != nil {
   166  			addrs = []net.IP{ip}
   167  		}
   168  
   169  		// if ip == nil, then `host` is neither an IP nor it could be looked up,
   170  		// either because the index is unreachable, or because the index is behind an HTTP proxy.
   171  		// So, len(addrs) == 0 and we're not aborting.
   172  	}
   173  
   174  	// Try CIDR notation only if addrs has any elements, i.e. if `host`'s IP could be determined.
   175  	for _, addr := range addrs {
   176  		for _, ipnet := range config.InsecureRegistryCIDRs {
   177  			// check if the addr falls in the subnet
   178  			if (*net.IPNet)(ipnet).Contains(addr) {
   179  				return false
   180  			}
   181  		}
   182  	}
   183  
   184  	return true
   185  }
   186  
   187  // ValidateMirror validates an HTTP(S) registry mirror
   188  func ValidateMirror(val string) (string, error) {
   189  	uri, err := url.Parse(val)
   190  	if err != nil {
   191  		return "", fmt.Errorf("%s is not a valid URI", val)
   192  	}
   193  
   194  	if uri.Scheme != "http" && uri.Scheme != "https" {
   195  		return "", fmt.Errorf("Unsupported scheme %s", uri.Scheme)
   196  	}
   197  
   198  	if uri.Path != "" || uri.RawQuery != "" || uri.Fragment != "" {
   199  		return "", fmt.Errorf("Unsupported path/query/fragment at end of the URI")
   200  	}
   201  
   202  	return fmt.Sprintf("%s://%s/", uri.Scheme, uri.Host), nil
   203  }
   204  
   205  // ValidateIndexName validates an index name.
   206  func ValidateIndexName(val string) (string, error) {
   207  	// 'index.docker.io' => 'docker.io'
   208  	if val == "index."+IndexName {
   209  		val = IndexName
   210  	}
   211  	if strings.HasPrefix(val, "-") || strings.HasSuffix(val, "-") {
   212  		return "", fmt.Errorf("Invalid index name (%s). Cannot begin or end with a hyphen.", val)
   213  	}
   214  	// *TODO: Check if valid hostname[:port]/ip[:port]?
   215  	return val, nil
   216  }
   217  
   218  func validateRemoteName(remoteName string) error {
   219  
   220  	if !strings.Contains(remoteName, "/") {
   221  
   222  		// the repository name must not be a valid image ID
   223  		if err := image.ValidateID(remoteName); err == nil {
   224  			return fmt.Errorf("Invalid repository name (%s), cannot specify 64-byte hexadecimal strings", remoteName)
   225  		}
   226  	}
   227  
   228  	return v2.ValidateRepositoryName(remoteName)
   229  }
   230  
   231  func validateNoSchema(reposName string) error {
   232  	if strings.Contains(reposName, "://") {
   233  		// It cannot contain a scheme!
   234  		return ErrInvalidRepositoryName
   235  	}
   236  	return nil
   237  }
   238  
   239  // ValidateRepositoryName validates a repository name
   240  func ValidateRepositoryName(reposName string) error {
   241  	var err error
   242  	if err = validateNoSchema(reposName); err != nil {
   243  		return err
   244  	}
   245  	indexName, remoteName := splitReposName(reposName)
   246  	if _, err = ValidateIndexName(indexName); err != nil {
   247  		return err
   248  	}
   249  	return validateRemoteName(remoteName)
   250  }
   251  
   252  // NewIndexInfo returns IndexInfo configuration from indexName
   253  func (config *ServiceConfig) NewIndexInfo(indexName string) (*IndexInfo, error) {
   254  	var err error
   255  	indexName, err = ValidateIndexName(indexName)
   256  	if err != nil {
   257  		return nil, err
   258  	}
   259  
   260  	// Return any configured index info, first.
   261  	if index, ok := config.IndexConfigs[indexName]; ok {
   262  		return index, nil
   263  	}
   264  
   265  	// Construct a non-configured index info.
   266  	index := &IndexInfo{
   267  		Name:     indexName,
   268  		Mirrors:  make([]string, 0),
   269  		Official: false,
   270  	}
   271  	index.Secure = config.isSecureIndex(indexName)
   272  	return index, nil
   273  }
   274  
   275  // GetAuthConfigKey special-cases using the full index address of the official
   276  // index as the AuthConfig key, and uses the (host)name[:port] for private indexes.
   277  func (index *IndexInfo) GetAuthConfigKey() string {
   278  	if index.Official {
   279  		return IndexServer
   280  	}
   281  	return index.Name
   282  }
   283  
   284  // splitReposName breaks a reposName into an index name and remote name
   285  func splitReposName(reposName string) (string, string) {
   286  	nameParts := strings.SplitN(reposName, "/", 2)
   287  	var indexName, remoteName string
   288  	if len(nameParts) == 1 || (!strings.Contains(nameParts[0], ".") &&
   289  		!strings.Contains(nameParts[0], ":") && nameParts[0] != "localhost") {
   290  		// This is a Docker Index repos (ex: samalba/hipache or ubuntu)
   291  		// 'docker.io'
   292  		indexName = IndexName
   293  		remoteName = reposName
   294  	} else {
   295  		indexName = nameParts[0]
   296  		remoteName = nameParts[1]
   297  	}
   298  	return indexName, remoteName
   299  }
   300  
   301  // NewRepositoryInfo validates and breaks down a repository name into a RepositoryInfo
   302  func (config *ServiceConfig) NewRepositoryInfo(reposName string) (*RepositoryInfo, error) {
   303  	if err := validateNoSchema(reposName); err != nil {
   304  		return nil, err
   305  	}
   306  
   307  	indexName, remoteName := splitReposName(reposName)
   308  	if err := validateRemoteName(remoteName); err != nil {
   309  		return nil, err
   310  	}
   311  
   312  	repoInfo := &RepositoryInfo{
   313  		RemoteName: remoteName,
   314  	}
   315  
   316  	var err error
   317  	repoInfo.Index, err = config.NewIndexInfo(indexName)
   318  	if err != nil {
   319  		return nil, err
   320  	}
   321  
   322  	if repoInfo.Index.Official {
   323  		normalizedName := repoInfo.RemoteName
   324  		if strings.HasPrefix(normalizedName, "library/") {
   325  			// If pull "library/foo", it's stored locally under "foo"
   326  			normalizedName = strings.SplitN(normalizedName, "/", 2)[1]
   327  		}
   328  
   329  		repoInfo.LocalName = normalizedName
   330  		repoInfo.RemoteName = normalizedName
   331  		// If the normalized name does not contain a '/' (e.g. "foo")
   332  		// then it is an official repo.
   333  		if strings.IndexRune(normalizedName, '/') == -1 {
   334  			repoInfo.Official = true
   335  			// Fix up remote name for official repos.
   336  			repoInfo.RemoteName = "library/" + normalizedName
   337  		}
   338  
   339  		repoInfo.CanonicalName = "docker.io/" + repoInfo.RemoteName
   340  	} else {
   341  		repoInfo.LocalName = repoInfo.Index.Name + "/" + repoInfo.RemoteName
   342  		repoInfo.CanonicalName = repoInfo.LocalName
   343  
   344  	}
   345  
   346  	return repoInfo, nil
   347  }
   348  
   349  // GetSearchTerm special-cases using local name for official index, and
   350  // remote name for private indexes.
   351  func (repoInfo *RepositoryInfo) GetSearchTerm() string {
   352  	if repoInfo.Index.Official {
   353  		return repoInfo.LocalName
   354  	}
   355  	return repoInfo.RemoteName
   356  }
   357  
   358  // ParseRepositoryInfo performs the breakdown of a repository name into a RepositoryInfo, but
   359  // lacks registry configuration.
   360  func ParseRepositoryInfo(reposName string) (*RepositoryInfo, error) {
   361  	return emptyServiceConfig.NewRepositoryInfo(reposName)
   362  }
   363  
   364  // NormalizeLocalName transforms a repository name into a normalize LocalName
   365  // Passes through the name without transformation on error (image id, etc)
   366  func NormalizeLocalName(name string) string {
   367  	repoInfo, err := ParseRepositoryInfo(name)
   368  	if err != nil {
   369  		return name
   370  	}
   371  	return repoInfo.LocalName
   372  }