github.com/pwn-term/docker@v0.0.0-20210616085119-6e977cce2565/moby/registry/endpoint_v1.go (about)

     1  package registry // import "github.com/docker/docker/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/docker/distribution/registry/client/transport"
    13  	registrytypes "github.com/docker/docker/api/types/registry"
    14  	"github.com/sirupsen/logrus"
    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 /data/data/hilled.pwnterm/files/usr/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 {
    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, Headers(userAgent, metaHeaders)...))
    81  	return endpoint
    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 := newV1Endpoint(*uri, tlsConfig, userAgent, metaHeaders)
   127  
   128  	return endpoint, nil
   129  }
   130  
   131  // Get the formatted URL for the root of this registry Endpoint
   132  func (e *V1Endpoint) String() string {
   133  	return e.URL.String() + "/v1/"
   134  }
   135  
   136  // Path returns a formatted string for the URL
   137  // of this endpoint with the given path appended.
   138  func (e *V1Endpoint) Path(path string) string {
   139  	return e.URL.String() + "/v1/" + path
   140  }
   141  
   142  // Ping returns a PingResult which indicates whether the registry is standalone or not.
   143  func (e *V1Endpoint) Ping() (PingResult, error) {
   144  	logrus.Debugf("attempting v1 ping for registry endpoint %s", e)
   145  
   146  	if e.String() == IndexServer {
   147  		// Skip the check, we know this one is valid
   148  		// (and we never want to fallback to http in case of error)
   149  		return PingResult{Standalone: false}, nil
   150  	}
   151  
   152  	req, err := http.NewRequest(http.MethodGet, e.Path("_ping"), nil)
   153  	if err != nil {
   154  		return PingResult{Standalone: false}, err
   155  	}
   156  
   157  	resp, err := e.client.Do(req)
   158  	if err != nil {
   159  		return PingResult{Standalone: false}, err
   160  	}
   161  
   162  	defer resp.Body.Close()
   163  
   164  	jsonString, err := ioutil.ReadAll(resp.Body)
   165  	if err != nil {
   166  		return PingResult{Standalone: false}, fmt.Errorf("error while reading the http response: %s", err)
   167  	}
   168  
   169  	// If the header is absent, we assume true for compatibility with earlier
   170  	// versions of the registry. default to true
   171  	info := PingResult{
   172  		Standalone: true,
   173  	}
   174  	if err := json.Unmarshal(jsonString, &info); err != nil {
   175  		logrus.Debugf("Error unmarshaling the _ping PingResult: %s", err)
   176  		// don't stop here. Just assume sane defaults
   177  	}
   178  	if hdr := resp.Header.Get("X-Docker-Registry-Version"); hdr != "" {
   179  		logrus.Debugf("Registry version header: '%s'", hdr)
   180  		info.Version = hdr
   181  	}
   182  	logrus.Debugf("PingResult.Version: %q", info.Version)
   183  
   184  	standalone := resp.Header.Get("X-Docker-Registry-Standalone")
   185  	logrus.Debugf("Registry standalone header: '%s'", standalone)
   186  	// Accepted values are "true" (case-insensitive) and "1".
   187  	if strings.EqualFold(standalone, "true") || standalone == "1" {
   188  		info.Standalone = true
   189  	} else if len(standalone) > 0 {
   190  		// there is a header set, and it is not "true" or "1", so assume fails
   191  		info.Standalone = false
   192  	}
   193  	logrus.Debugf("PingResult.Standalone: %t", info.Standalone)
   194  	return info, nil
   195  }