github.com/resin-io/docker@v1.13.1/registry/endpoint_v1.go (about)

     1  package registry
     2  
     3  import (
     4  	"crypto/tls"
     5  	"encoding/json"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"net/http"
     9  	"net/url"
    10  	"strings"
    11  
    12  	"github.com/Sirupsen/logrus"
    13  	"github.com/docker/distribution/registry/client/transport"
    14  	registrytypes "github.com/docker/docker/api/types/registry"
    15  )
    16  
    17  // V1Endpoint stores basic information about a V1 registry endpoint.
    18  type V1Endpoint struct {
    19  	client   *http.Client
    20  	URL      *url.URL
    21  	IsSecure bool
    22  }
    23  
    24  // NewV1Endpoint parses the given address to return a registry endpoint.
    25  func NewV1Endpoint(index *registrytypes.IndexInfo, userAgent string, metaHeaders http.Header) (*V1Endpoint, error) {
    26  	tlsConfig, err := newTLSConfig(index.Name, index.Secure)
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  
    31  	endpoint, err := newV1EndpointFromStr(GetAuthConfigKey(index), tlsConfig, userAgent, metaHeaders)
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  
    36  	if err := validateEndpoint(endpoint); err != nil {
    37  		return nil, err
    38  	}
    39  
    40  	return endpoint, nil
    41  }
    42  
    43  func validateEndpoint(endpoint *V1Endpoint) error {
    44  	logrus.Debugf("pinging registry endpoint %s", endpoint)
    45  
    46  	// Try HTTPS ping to registry
    47  	endpoint.URL.Scheme = "https"
    48  	if _, err := endpoint.Ping(); err != nil {
    49  		if endpoint.IsSecure {
    50  			// If registry is secure and HTTPS failed, show user the error and tell them about `--insecure-registry`
    51  			// in case that's what they need. DO NOT accept unknown CA certificates, and DO NOT fallback to HTTP.
    52  			return fmt.Errorf("invalid registry endpoint %s: %v. If this private registry supports only HTTP or HTTPS with an unknown CA certificate, please add `--insecure-registry %s` to the daemon's arguments. In the case of HTTPS, if you have access to the registry's CA certificate, no need for the flag; simply place the CA certificate at /etc/docker/certs.d/%s/ca.crt", endpoint, err, endpoint.URL.Host, endpoint.URL.Host)
    53  		}
    54  
    55  		// If registry is insecure and HTTPS failed, fallback to HTTP.
    56  		logrus.Debugf("Error from registry %q marked as insecure: %v. Insecurely falling back to HTTP", endpoint, err)
    57  		endpoint.URL.Scheme = "http"
    58  
    59  		var err2 error
    60  		if _, err2 = endpoint.Ping(); err2 == nil {
    61  			return nil
    62  		}
    63  
    64  		return fmt.Errorf("invalid registry endpoint %q. HTTPS attempt: %v. HTTP attempt: %v", endpoint, err, err2)
    65  	}
    66  
    67  	return nil
    68  }
    69  
    70  func newV1Endpoint(address url.URL, tlsConfig *tls.Config, userAgent string, metaHeaders http.Header) (*V1Endpoint, error) {
    71  	endpoint := &V1Endpoint{
    72  		IsSecure: (tlsConfig == nil || !tlsConfig.InsecureSkipVerify),
    73  		URL:      new(url.URL),
    74  	}
    75  
    76  	*endpoint.URL = address
    77  
    78  	// TODO(tiborvass): make sure a ConnectTimeout transport is used
    79  	tr := NewTransport(tlsConfig)
    80  	endpoint.client = HTTPClient(transport.NewTransport(tr, DockerHeaders(userAgent, metaHeaders)...))
    81  	return endpoint, nil
    82  }
    83  
    84  // trimV1Address trims the version off the address and returns the
    85  // trimmed address or an error if there is a non-V1 version.
    86  func trimV1Address(address string) (string, error) {
    87  	var (
    88  		chunks        []string
    89  		apiVersionStr string
    90  	)
    91  
    92  	if strings.HasSuffix(address, "/") {
    93  		address = address[:len(address)-1]
    94  	}
    95  
    96  	chunks = strings.Split(address, "/")
    97  	apiVersionStr = chunks[len(chunks)-1]
    98  	if apiVersionStr == "v1" {
    99  		return strings.Join(chunks[:len(chunks)-1], "/"), nil
   100  	}
   101  
   102  	for k, v := range apiVersions {
   103  		if k != APIVersion1 && apiVersionStr == v {
   104  			return "", fmt.Errorf("unsupported V1 version path %s", apiVersionStr)
   105  		}
   106  	}
   107  
   108  	return address, nil
   109  }
   110  
   111  func newV1EndpointFromStr(address string, tlsConfig *tls.Config, userAgent string, metaHeaders http.Header) (*V1Endpoint, error) {
   112  	if !strings.HasPrefix(address, "http://") && !strings.HasPrefix(address, "https://") {
   113  		address = "https://" + address
   114  	}
   115  
   116  	address, err := trimV1Address(address)
   117  	if err != nil {
   118  		return nil, err
   119  	}
   120  
   121  	uri, err := url.Parse(address)
   122  	if err != nil {
   123  		return nil, err
   124  	}
   125  
   126  	endpoint, err := newV1Endpoint(*uri, tlsConfig, userAgent, metaHeaders)
   127  	if err != nil {
   128  		return nil, err
   129  	}
   130  
   131  	return endpoint, nil
   132  }
   133  
   134  // Get the formatted URL for the root of this registry Endpoint
   135  func (e *V1Endpoint) String() string {
   136  	return e.URL.String() + "/v1/"
   137  }
   138  
   139  // Path returns a formatted string for the URL
   140  // of this endpoint with the given path appended.
   141  func (e *V1Endpoint) Path(path string) string {
   142  	return e.URL.String() + "/v1/" + path
   143  }
   144  
   145  // Ping returns a PingResult which indicates whether the registry is standalone or not.
   146  func (e *V1Endpoint) Ping() (PingResult, error) {
   147  	logrus.Debugf("attempting v1 ping for registry endpoint %s", e)
   148  
   149  	if e.String() == IndexServer {
   150  		// Skip the check, we know this one is valid
   151  		// (and we never want to fallback to http in case of error)
   152  		return PingResult{Standalone: false}, nil
   153  	}
   154  
   155  	req, err := http.NewRequest("GET", e.Path("_ping"), nil)
   156  	if err != nil {
   157  		return PingResult{Standalone: false}, err
   158  	}
   159  
   160  	resp, err := e.client.Do(req)
   161  	if err != nil {
   162  		return PingResult{Standalone: false}, err
   163  	}
   164  
   165  	defer resp.Body.Close()
   166  
   167  	jsonString, err := ioutil.ReadAll(resp.Body)
   168  	if err != nil {
   169  		return PingResult{Standalone: false}, fmt.Errorf("error while reading the http response: %s", err)
   170  	}
   171  
   172  	// If the header is absent, we assume true for compatibility with earlier
   173  	// versions of the registry. default to true
   174  	info := PingResult{
   175  		Standalone: true,
   176  	}
   177  	if err := json.Unmarshal(jsonString, &info); err != nil {
   178  		logrus.Debugf("Error unmarshalling the _ping PingResult: %s", err)
   179  		// don't stop here. Just assume sane defaults
   180  	}
   181  	if hdr := resp.Header.Get("X-Docker-Registry-Version"); hdr != "" {
   182  		logrus.Debugf("Registry version header: '%s'", hdr)
   183  		info.Version = hdr
   184  	}
   185  	logrus.Debugf("PingResult.Version: %q", info.Version)
   186  
   187  	standalone := resp.Header.Get("X-Docker-Registry-Standalone")
   188  	logrus.Debugf("Registry standalone header: '%s'", standalone)
   189  	// Accepted values are "true" (case-insensitive) and "1".
   190  	if strings.EqualFold(standalone, "true") || standalone == "1" {
   191  		info.Standalone = true
   192  	} else if len(standalone) > 0 {
   193  		// there is a header set, and it is not "true" or "1", so assume fails
   194  		info.Standalone = false
   195  	}
   196  	logrus.Debugf("PingResult.Standalone: %t", info.Standalone)
   197  	return info, nil
   198  }