github.com/lmars/docker@v1.6.0-rc2/registry/endpoint.go (about) 1 package registry 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io/ioutil" 7 "net" 8 "net/http" 9 "net/url" 10 "strings" 11 12 log "github.com/Sirupsen/logrus" 13 "github.com/docker/docker/registry/v2" 14 "github.com/docker/docker/utils" 15 ) 16 17 // for mocking in unit tests 18 var lookupIP = net.LookupIP 19 20 // scans string for api version in the URL path. returns the trimmed address, if version found, string and API version. 21 func scanForAPIVersion(address string) (string, APIVersion) { 22 var ( 23 chunks []string 24 apiVersionStr string 25 ) 26 27 if strings.HasSuffix(address, "/") { 28 address = address[:len(address)-1] 29 } 30 31 chunks = strings.Split(address, "/") 32 apiVersionStr = chunks[len(chunks)-1] 33 34 for k, v := range apiVersions { 35 if apiVersionStr == v { 36 address = strings.Join(chunks[:len(chunks)-1], "/") 37 return address, k 38 } 39 } 40 41 return address, APIVersionUnknown 42 } 43 44 // NewEndpoint parses the given address to return a registry endpoint. 45 func NewEndpoint(index *IndexInfo) (*Endpoint, error) { 46 // *TODO: Allow per-registry configuration of endpoints. 47 endpoint, err := newEndpoint(index.GetAuthConfigKey(), index.Secure) 48 if err != nil { 49 return nil, err 50 } 51 if err := validateEndpoint(endpoint); err != nil { 52 return nil, err 53 } 54 55 return endpoint, nil 56 } 57 58 func validateEndpoint(endpoint *Endpoint) error { 59 log.Debugf("pinging registry endpoint %s", endpoint) 60 61 // Try HTTPS ping to registry 62 endpoint.URL.Scheme = "https" 63 if _, err := endpoint.Ping(); err != nil { 64 if endpoint.IsSecure { 65 // If registry is secure and HTTPS failed, show user the error and tell them about `--insecure-registry` 66 // in case that's what they need. DO NOT accept unknown CA certificates, and DO NOT fallback to HTTP. 67 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) 68 } 69 70 // If registry is insecure and HTTPS failed, fallback to HTTP. 71 log.Debugf("Error from registry %q marked as insecure: %v. Insecurely falling back to HTTP", endpoint, err) 72 endpoint.URL.Scheme = "http" 73 74 var err2 error 75 if _, err2 = endpoint.Ping(); err2 == nil { 76 return nil 77 } 78 79 return fmt.Errorf("invalid registry endpoint %q. HTTPS attempt: %v. HTTP attempt: %v", endpoint, err, err2) 80 } 81 82 return nil 83 } 84 85 func newEndpoint(address string, secure bool) (*Endpoint, error) { 86 var ( 87 endpoint = new(Endpoint) 88 trimmedAddress string 89 err error 90 ) 91 92 if !strings.HasPrefix(address, "http") { 93 address = "https://" + address 94 } 95 96 trimmedAddress, endpoint.Version = scanForAPIVersion(address) 97 98 if endpoint.URL, err = url.Parse(trimmedAddress); err != nil { 99 return nil, err 100 } 101 endpoint.IsSecure = secure 102 return endpoint, nil 103 } 104 105 func (repoInfo *RepositoryInfo) GetEndpoint() (*Endpoint, error) { 106 return NewEndpoint(repoInfo.Index) 107 } 108 109 // Endpoint stores basic information about a registry endpoint. 110 type Endpoint struct { 111 URL *url.URL 112 Version APIVersion 113 IsSecure bool 114 AuthChallenges []*AuthorizationChallenge 115 URLBuilder *v2.URLBuilder 116 } 117 118 // Get the formated URL for the root of this registry Endpoint 119 func (e *Endpoint) String() string { 120 return fmt.Sprintf("%s/v%d/", e.URL, e.Version) 121 } 122 123 // VersionString returns a formatted string of this 124 // endpoint address using the given API Version. 125 func (e *Endpoint) VersionString(version APIVersion) string { 126 return fmt.Sprintf("%s/v%d/", e.URL, version) 127 } 128 129 // Path returns a formatted string for the URL 130 // of this endpoint with the given path appended. 131 func (e *Endpoint) Path(path string) string { 132 return fmt.Sprintf("%s/v%d/%s", e.URL, e.Version, path) 133 } 134 135 func (e *Endpoint) Ping() (RegistryInfo, error) { 136 // The ping logic to use is determined by the registry endpoint version. 137 factory := HTTPRequestFactory(nil) 138 switch e.Version { 139 case APIVersion1: 140 return e.pingV1(factory) 141 case APIVersion2: 142 return e.pingV2(factory) 143 } 144 145 // APIVersionUnknown 146 // We should try v2 first... 147 e.Version = APIVersion2 148 regInfo, errV2 := e.pingV2(factory) 149 if errV2 == nil { 150 return regInfo, nil 151 } 152 153 // ... then fallback to v1. 154 e.Version = APIVersion1 155 regInfo, errV1 := e.pingV1(factory) 156 if errV1 == nil { 157 return regInfo, nil 158 } 159 160 e.Version = APIVersionUnknown 161 return RegistryInfo{}, fmt.Errorf("unable to ping registry endpoint %s\nv2 ping attempt failed with error: %s\n v1 ping attempt failed with error: %s", e, errV2, errV1) 162 } 163 164 func (e *Endpoint) pingV1(factory *utils.HTTPRequestFactory) (RegistryInfo, error) { 165 log.Debugf("attempting v1 ping for registry endpoint %s", e) 166 167 if e.String() == IndexServerAddress() { 168 // Skip the check, we know this one is valid 169 // (and we never want to fallback to http in case of error) 170 return RegistryInfo{Standalone: false}, nil 171 } 172 173 req, err := factory.NewRequest("GET", e.Path("_ping"), nil) 174 if err != nil { 175 return RegistryInfo{Standalone: false}, err 176 } 177 178 resp, _, err := doRequest(req, nil, ConnectTimeout, e.IsSecure) 179 if err != nil { 180 return RegistryInfo{Standalone: false}, err 181 } 182 183 defer resp.Body.Close() 184 185 jsonString, err := ioutil.ReadAll(resp.Body) 186 if err != nil { 187 return RegistryInfo{Standalone: false}, fmt.Errorf("error while reading the http response: %s", err) 188 } 189 190 // If the header is absent, we assume true for compatibility with earlier 191 // versions of the registry. default to true 192 info := RegistryInfo{ 193 Standalone: true, 194 } 195 if err := json.Unmarshal(jsonString, &info); err != nil { 196 log.Debugf("Error unmarshalling the _ping RegistryInfo: %s", err) 197 // don't stop here. Just assume sane defaults 198 } 199 if hdr := resp.Header.Get("X-Docker-Registry-Version"); hdr != "" { 200 log.Debugf("Registry version header: '%s'", hdr) 201 info.Version = hdr 202 } 203 log.Debugf("RegistryInfo.Version: %q", info.Version) 204 205 standalone := resp.Header.Get("X-Docker-Registry-Standalone") 206 log.Debugf("Registry standalone header: '%s'", standalone) 207 // Accepted values are "true" (case-insensitive) and "1". 208 if strings.EqualFold(standalone, "true") || standalone == "1" { 209 info.Standalone = true 210 } else if len(standalone) > 0 { 211 // there is a header set, and it is not "true" or "1", so assume fails 212 info.Standalone = false 213 } 214 log.Debugf("RegistryInfo.Standalone: %t", info.Standalone) 215 return info, nil 216 } 217 218 func (e *Endpoint) pingV2(factory *utils.HTTPRequestFactory) (RegistryInfo, error) { 219 log.Debugf("attempting v2 ping for registry endpoint %s", e) 220 221 req, err := factory.NewRequest("GET", e.Path(""), nil) 222 if err != nil { 223 return RegistryInfo{}, err 224 } 225 226 resp, _, err := doRequest(req, nil, ConnectTimeout, e.IsSecure) 227 if err != nil { 228 return RegistryInfo{}, err 229 } 230 defer resp.Body.Close() 231 232 // The endpoint may have multiple supported versions. 233 // Ensure it supports the v2 Registry API. 234 var supportsV2 bool 235 236 HeaderLoop: 237 for _, supportedVersions := range resp.Header[http.CanonicalHeaderKey("Docker-Distribution-API-Version")] { 238 for _, versionName := range strings.Fields(supportedVersions) { 239 if versionName == "registry/2.0" { 240 supportsV2 = true 241 break HeaderLoop 242 } 243 } 244 } 245 246 if !supportsV2 { 247 return RegistryInfo{}, fmt.Errorf("%s does not appear to be a v2 registry endpoint", e) 248 } 249 250 if resp.StatusCode == http.StatusOK { 251 // It would seem that no authentication/authorization is required. 252 // So we don't need to parse/add any authorization schemes. 253 return RegistryInfo{Standalone: true}, nil 254 } 255 256 if resp.StatusCode == http.StatusUnauthorized { 257 // Parse the WWW-Authenticate Header and store the challenges 258 // on this endpoint object. 259 e.AuthChallenges = parseAuthHeader(resp.Header) 260 return RegistryInfo{}, nil 261 } 262 263 return RegistryInfo{}, fmt.Errorf("v2 registry endpoint returned status %d: %q", resp.StatusCode, http.StatusText(resp.StatusCode)) 264 }