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