github.com/endocode/docker@v1.4.2-0.20160113120958-46eb4700391e/registry/config.go (about)

     1  package registry
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"net"
     7  	"net/url"
     8  	"strings"
     9  
    10  	"github.com/docker/docker/opts"
    11  	flag "github.com/docker/docker/pkg/mflag"
    12  	"github.com/docker/docker/reference"
    13  	registrytypes "github.com/docker/engine-api/types/registry"
    14  )
    15  
    16  // Options holds command line options.
    17  type Options struct {
    18  	Mirrors            opts.ListOpts
    19  	InsecureRegistries opts.ListOpts
    20  }
    21  
    22  const (
    23  	// DefaultNamespace is the default namespace
    24  	DefaultNamespace = "docker.io"
    25  	// DefaultRegistryVersionHeader is the name of the default HTTP header
    26  	// that carries Registry version info
    27  	DefaultRegistryVersionHeader = "Docker-Distribution-Api-Version"
    28  
    29  	// IndexServer is the v1 registry server used for user auth + account creation
    30  	IndexServer = DefaultV1Registry + "/v1/"
    31  	// IndexName is the name of the index
    32  	IndexName = "docker.io"
    33  
    34  	// NotaryServer is the endpoint serving the Notary trust server
    35  	NotaryServer = "https://notary.docker.io"
    36  
    37  	// IndexServer = "https://registry-stage.hub.docker.com/v1/"
    38  )
    39  
    40  var (
    41  	// ErrInvalidRepositoryName is an error returned if the repository name did
    42  	// not have the correct form
    43  	ErrInvalidRepositoryName = errors.New("Invalid repository name (ex: \"registry.domain.tld/myrepos\")")
    44  
    45  	emptyServiceConfig = NewServiceConfig(nil)
    46  
    47  	// V2Only controls access to legacy registries.  If it is set to true via the
    48  	// command line flag the daemon will not attempt to contact v1 legacy registries
    49  	V2Only = false
    50  )
    51  
    52  // InstallFlags adds command-line options to the top-level flag parser for
    53  // the current process.
    54  func (options *Options) InstallFlags(cmd *flag.FlagSet, usageFn func(string) string) {
    55  	options.Mirrors = opts.NewListOpts(ValidateMirror)
    56  	cmd.Var(&options.Mirrors, []string{"-registry-mirror"}, usageFn("Preferred Docker registry mirror"))
    57  	options.InsecureRegistries = opts.NewListOpts(ValidateIndexName)
    58  	cmd.Var(&options.InsecureRegistries, []string{"-insecure-registry"}, usageFn("Enable insecure registry communication"))
    59  	cmd.BoolVar(&V2Only, []string{"-disable-legacy-registry"}, false, usageFn("Do not contact legacy registries"))
    60  }
    61  
    62  // NewServiceConfig returns a new instance of ServiceConfig
    63  func NewServiceConfig(options *Options) *registrytypes.ServiceConfig {
    64  	if options == nil {
    65  		options = &Options{
    66  			Mirrors:            opts.NewListOpts(nil),
    67  			InsecureRegistries: opts.NewListOpts(nil),
    68  		}
    69  	}
    70  
    71  	// Localhost is by default considered as an insecure registry
    72  	// This is a stop-gap for people who are running a private registry on localhost (especially on Boot2docker).
    73  	//
    74  	// TODO: should we deprecate this once it is easier for people to set up a TLS registry or change
    75  	// daemon flags on boot2docker?
    76  	options.InsecureRegistries.Set("127.0.0.0/8")
    77  
    78  	config := &registrytypes.ServiceConfig{
    79  		InsecureRegistryCIDRs: make([]*registrytypes.NetIPNet, 0),
    80  		IndexConfigs:          make(map[string]*registrytypes.IndexInfo, 0),
    81  		// Hack: Bypass setting the mirrors to IndexConfigs since they are going away
    82  		// and Mirrors are only for the official registry anyways.
    83  		Mirrors: options.Mirrors.GetAll(),
    84  	}
    85  	// Split --insecure-registry into CIDR and registry-specific settings.
    86  	for _, r := range options.InsecureRegistries.GetAll() {
    87  		// Check if CIDR was passed to --insecure-registry
    88  		_, ipnet, err := net.ParseCIDR(r)
    89  		if err == nil {
    90  			// Valid CIDR.
    91  			config.InsecureRegistryCIDRs = append(config.InsecureRegistryCIDRs, (*registrytypes.NetIPNet)(ipnet))
    92  		} else {
    93  			// Assume `host:port` if not CIDR.
    94  			config.IndexConfigs[r] = &registrytypes.IndexInfo{
    95  				Name:     r,
    96  				Mirrors:  make([]string, 0),
    97  				Secure:   false,
    98  				Official: false,
    99  			}
   100  		}
   101  	}
   102  
   103  	// Configure public registry.
   104  	config.IndexConfigs[IndexName] = &registrytypes.IndexInfo{
   105  		Name:     IndexName,
   106  		Mirrors:  config.Mirrors,
   107  		Secure:   true,
   108  		Official: true,
   109  	}
   110  
   111  	return config
   112  }
   113  
   114  // isSecureIndex returns false if the provided indexName is part of the list of insecure registries
   115  // Insecure registries accept HTTP and/or accept HTTPS with certificates from unknown CAs.
   116  //
   117  // The list of insecure registries can contain an element with CIDR notation to specify a whole subnet.
   118  // If the subnet contains one of the IPs of the registry specified by indexName, the latter is considered
   119  // insecure.
   120  //
   121  // indexName should be a URL.Host (`host:port` or `host`) where the `host` part can be either a domain name
   122  // or an IP address. If it is a domain name, then it will be resolved in order to check if the IP is contained
   123  // in a subnet. If the resolving is not successful, isSecureIndex will only try to match hostname to any element
   124  // of insecureRegistries.
   125  func isSecureIndex(config *registrytypes.ServiceConfig, indexName string) bool {
   126  	// Check for configured index, first.  This is needed in case isSecureIndex
   127  	// is called from anything besides newIndexInfo, in order to honor per-index configurations.
   128  	if index, ok := config.IndexConfigs[indexName]; ok {
   129  		return index.Secure
   130  	}
   131  
   132  	host, _, err := net.SplitHostPort(indexName)
   133  	if err != nil {
   134  		// assume indexName is of the form `host` without the port and go on.
   135  		host = indexName
   136  	}
   137  
   138  	addrs, err := lookupIP(host)
   139  	if err != nil {
   140  		ip := net.ParseIP(host)
   141  		if ip != nil {
   142  			addrs = []net.IP{ip}
   143  		}
   144  
   145  		// if ip == nil, then `host` is neither an IP nor it could be looked up,
   146  		// either because the index is unreachable, or because the index is behind an HTTP proxy.
   147  		// So, len(addrs) == 0 and we're not aborting.
   148  	}
   149  
   150  	// Try CIDR notation only if addrs has any elements, i.e. if `host`'s IP could be determined.
   151  	for _, addr := range addrs {
   152  		for _, ipnet := range config.InsecureRegistryCIDRs {
   153  			// check if the addr falls in the subnet
   154  			if (*net.IPNet)(ipnet).Contains(addr) {
   155  				return false
   156  			}
   157  		}
   158  	}
   159  
   160  	return true
   161  }
   162  
   163  // ValidateMirror validates an HTTP(S) registry mirror
   164  func ValidateMirror(val string) (string, error) {
   165  	uri, err := url.Parse(val)
   166  	if err != nil {
   167  		return "", fmt.Errorf("%s is not a valid URI", val)
   168  	}
   169  
   170  	if uri.Scheme != "http" && uri.Scheme != "https" {
   171  		return "", fmt.Errorf("Unsupported scheme %s", uri.Scheme)
   172  	}
   173  
   174  	if uri.Path != "" || uri.RawQuery != "" || uri.Fragment != "" {
   175  		return "", fmt.Errorf("Unsupported path/query/fragment at end of the URI")
   176  	}
   177  
   178  	return fmt.Sprintf("%s://%s/", uri.Scheme, uri.Host), nil
   179  }
   180  
   181  // ValidateIndexName validates an index name.
   182  func ValidateIndexName(val string) (string, error) {
   183  	if val == reference.LegacyDefaultHostname {
   184  		val = reference.DefaultHostname
   185  	}
   186  	if strings.HasPrefix(val, "-") || strings.HasSuffix(val, "-") {
   187  		return "", fmt.Errorf("Invalid index name (%s). Cannot begin or end with a hyphen.", val)
   188  	}
   189  	return val, nil
   190  }
   191  
   192  func validateNoSchema(reposName string) error {
   193  	if strings.Contains(reposName, "://") {
   194  		// It cannot contain a scheme!
   195  		return ErrInvalidRepositoryName
   196  	}
   197  	return nil
   198  }
   199  
   200  // newIndexInfo returns IndexInfo configuration from indexName
   201  func newIndexInfo(config *registrytypes.ServiceConfig, indexName string) (*registrytypes.IndexInfo, error) {
   202  	var err error
   203  	indexName, err = ValidateIndexName(indexName)
   204  	if err != nil {
   205  		return nil, err
   206  	}
   207  
   208  	// Return any configured index info, first.
   209  	if index, ok := config.IndexConfigs[indexName]; ok {
   210  		return index, nil
   211  	}
   212  
   213  	// Construct a non-configured index info.
   214  	index := &registrytypes.IndexInfo{
   215  		Name:     indexName,
   216  		Mirrors:  make([]string, 0),
   217  		Official: false,
   218  	}
   219  	index.Secure = isSecureIndex(config, indexName)
   220  	return index, nil
   221  }
   222  
   223  // GetAuthConfigKey special-cases using the full index address of the official
   224  // index as the AuthConfig key, and uses the (host)name[:port] for private indexes.
   225  func GetAuthConfigKey(index *registrytypes.IndexInfo) string {
   226  	if index.Official {
   227  		return IndexServer
   228  	}
   229  	return index.Name
   230  }
   231  
   232  // newRepositoryInfo validates and breaks down a repository name into a RepositoryInfo
   233  func newRepositoryInfo(config *registrytypes.ServiceConfig, name reference.Named) (*RepositoryInfo, error) {
   234  	index, err := newIndexInfo(config, name.Hostname())
   235  	if err != nil {
   236  		return nil, err
   237  	}
   238  	official := !strings.ContainsRune(name.Name(), '/')
   239  	return &RepositoryInfo{name, index, official}, nil
   240  }
   241  
   242  // ParseRepositoryInfo performs the breakdown of a repository name into a RepositoryInfo, but
   243  // lacks registry configuration.
   244  func ParseRepositoryInfo(reposName reference.Named) (*RepositoryInfo, error) {
   245  	return newRepositoryInfo(emptyServiceConfig, reposName)
   246  }
   247  
   248  // ParseSearchIndexInfo will use repository name to get back an indexInfo.
   249  func ParseSearchIndexInfo(reposName string) (*registrytypes.IndexInfo, error) {
   250  	indexName, _ := splitReposSearchTerm(reposName)
   251  
   252  	indexInfo, err := newIndexInfo(emptyServiceConfig, indexName)
   253  	if err != nil {
   254  		return nil, err
   255  	}
   256  	return indexInfo, nil
   257  }