github.com/sijibomii/docker@v0.0.0-20231230191044-5cf6ca554647/registry/registry.go (about)

     1  // Package registry contains client primitives to interact with a remote Docker registry.
     2  package registry
     3  
     4  import (
     5  	"crypto/tls"
     6  	"crypto/x509"
     7  	"errors"
     8  	"fmt"
     9  	"io/ioutil"
    10  	"net"
    11  	"net/http"
    12  	"os"
    13  	"path/filepath"
    14  	"strings"
    15  	"time"
    16  
    17  	"github.com/Sirupsen/logrus"
    18  	"github.com/docker/distribution/registry/client/transport"
    19  	"github.com/docker/go-connections/tlsconfig"
    20  )
    21  
    22  var (
    23  	// ErrAlreadyExists is an error returned if an image being pushed
    24  	// already exists on the remote side
    25  	ErrAlreadyExists = errors.New("Image already exists")
    26  )
    27  
    28  func newTLSConfig(hostname string, isSecure bool) (*tls.Config, error) {
    29  	// PreferredServerCipherSuites should have no effect
    30  	tlsConfig := tlsconfig.ServerDefault
    31  
    32  	tlsConfig.InsecureSkipVerify = !isSecure
    33  
    34  	if isSecure && CertsDir != "" {
    35  		hostDir := filepath.Join(CertsDir, cleanPath(hostname))
    36  		logrus.Debugf("hostDir: %s", hostDir)
    37  		if err := ReadCertsDirectory(&tlsConfig, hostDir); err != nil {
    38  			return nil, err
    39  		}
    40  	}
    41  
    42  	return &tlsConfig, nil
    43  }
    44  
    45  func hasFile(files []os.FileInfo, name string) bool {
    46  	for _, f := range files {
    47  		if f.Name() == name {
    48  			return true
    49  		}
    50  	}
    51  	return false
    52  }
    53  
    54  // ReadCertsDirectory reads the directory for TLS certificates
    55  // including roots and certificate pairs and updates the
    56  // provided TLS configuration.
    57  func ReadCertsDirectory(tlsConfig *tls.Config, directory string) error {
    58  	fs, err := ioutil.ReadDir(directory)
    59  	if err != nil && !os.IsNotExist(err) {
    60  		return err
    61  	}
    62  
    63  	for _, f := range fs {
    64  		if strings.HasSuffix(f.Name(), ".crt") {
    65  			if tlsConfig.RootCAs == nil {
    66  				// TODO(dmcgowan): Copy system pool
    67  				tlsConfig.RootCAs = x509.NewCertPool()
    68  			}
    69  			logrus.Debugf("crt: %s", filepath.Join(directory, f.Name()))
    70  			data, err := ioutil.ReadFile(filepath.Join(directory, f.Name()))
    71  			if err != nil {
    72  				return err
    73  			}
    74  			tlsConfig.RootCAs.AppendCertsFromPEM(data)
    75  		}
    76  		if strings.HasSuffix(f.Name(), ".cert") {
    77  			certName := f.Name()
    78  			keyName := certName[:len(certName)-5] + ".key"
    79  			logrus.Debugf("cert: %s", filepath.Join(directory, f.Name()))
    80  			if !hasFile(fs, keyName) {
    81  				return fmt.Errorf("Missing key %s for client certificate %s. Note that CA certificates should use the extension .crt.", keyName, certName)
    82  			}
    83  			cert, err := tls.LoadX509KeyPair(filepath.Join(directory, certName), filepath.Join(directory, keyName))
    84  			if err != nil {
    85  				return err
    86  			}
    87  			tlsConfig.Certificates = append(tlsConfig.Certificates, cert)
    88  		}
    89  		if strings.HasSuffix(f.Name(), ".key") {
    90  			keyName := f.Name()
    91  			certName := keyName[:len(keyName)-4] + ".cert"
    92  			logrus.Debugf("key: %s", filepath.Join(directory, f.Name()))
    93  			if !hasFile(fs, certName) {
    94  				return fmt.Errorf("Missing client certificate %s for key %s", certName, keyName)
    95  			}
    96  		}
    97  	}
    98  
    99  	return nil
   100  }
   101  
   102  // DockerHeaders returns request modifiers with a User-Agent and metaHeaders
   103  func DockerHeaders(userAgent string, metaHeaders http.Header) []transport.RequestModifier {
   104  	modifiers := []transport.RequestModifier{}
   105  	if userAgent != "" {
   106  		modifiers = append(modifiers, transport.NewHeaderRequestModifier(http.Header{
   107  			"User-Agent": []string{userAgent},
   108  		}))
   109  	}
   110  	if metaHeaders != nil {
   111  		modifiers = append(modifiers, transport.NewHeaderRequestModifier(metaHeaders))
   112  	}
   113  	return modifiers
   114  }
   115  
   116  // HTTPClient returns a HTTP client structure which uses the given transport
   117  // and contains the necessary headers for redirected requests
   118  func HTTPClient(transport http.RoundTripper) *http.Client {
   119  	return &http.Client{
   120  		Transport:     transport,
   121  		CheckRedirect: addRequiredHeadersToRedirectedRequests,
   122  	}
   123  }
   124  
   125  func trustedLocation(req *http.Request) bool {
   126  	var (
   127  		trusteds = []string{"docker.com", "docker.io"}
   128  		hostname = strings.SplitN(req.Host, ":", 2)[0]
   129  	)
   130  	if req.URL.Scheme != "https" {
   131  		return false
   132  	}
   133  
   134  	for _, trusted := range trusteds {
   135  		if hostname == trusted || strings.HasSuffix(hostname, "."+trusted) {
   136  			return true
   137  		}
   138  	}
   139  	return false
   140  }
   141  
   142  // addRequiredHeadersToRedirectedRequests adds the necessary redirection headers
   143  // for redirected requests
   144  func addRequiredHeadersToRedirectedRequests(req *http.Request, via []*http.Request) error {
   145  	if via != nil && via[0] != nil {
   146  		if trustedLocation(req) && trustedLocation(via[0]) {
   147  			req.Header = via[0].Header
   148  			return nil
   149  		}
   150  		for k, v := range via[0].Header {
   151  			if k != "Authorization" {
   152  				for _, vv := range v {
   153  					req.Header.Add(k, vv)
   154  				}
   155  			}
   156  		}
   157  	}
   158  	return nil
   159  }
   160  
   161  // NewTransport returns a new HTTP transport. If tlsConfig is nil, it uses the
   162  // default TLS configuration.
   163  func NewTransport(tlsConfig *tls.Config) *http.Transport {
   164  	if tlsConfig == nil {
   165  		var cfg = tlsconfig.ServerDefault
   166  		tlsConfig = &cfg
   167  	}
   168  	return &http.Transport{
   169  		Proxy: http.ProxyFromEnvironment,
   170  		Dial: (&net.Dialer{
   171  			Timeout:   30 * time.Second,
   172  			KeepAlive: 30 * time.Second,
   173  			DualStack: true,
   174  		}).Dial,
   175  		TLSHandshakeTimeout: 10 * time.Second,
   176  		TLSClientConfig:     tlsConfig,
   177  		// TODO(dmcgowan): Call close idle connections when complete and use keep alive
   178  		DisableKeepAlives: true,
   179  	}
   180  }