github.com/sijibomii/docker@v0.0.0-20231230191044-5cf6ca554647/registry/session.go (about) 1 package registry 2 3 import ( 4 "bytes" 5 "crypto/sha256" 6 "errors" 7 "sync" 8 // this is required for some certificates 9 _ "crypto/sha512" 10 "encoding/hex" 11 "encoding/json" 12 "fmt" 13 "io" 14 "io/ioutil" 15 "net/http" 16 "net/http/cookiejar" 17 "net/url" 18 "strconv" 19 "strings" 20 21 "github.com/Sirupsen/logrus" 22 "github.com/docker/distribution/registry/api/errcode" 23 "github.com/docker/docker/pkg/httputils" 24 "github.com/docker/docker/pkg/ioutils" 25 "github.com/docker/docker/pkg/stringid" 26 "github.com/docker/docker/pkg/tarsum" 27 "github.com/docker/docker/reference" 28 "github.com/docker/engine-api/types" 29 registrytypes "github.com/docker/engine-api/types/registry" 30 ) 31 32 var ( 33 // ErrRepoNotFound is returned if the repository didn't exist on the 34 // remote side 35 ErrRepoNotFound = errors.New("Repository not found") 36 ) 37 38 // A Session is used to communicate with a V1 registry 39 type Session struct { 40 indexEndpoint *V1Endpoint 41 client *http.Client 42 // TODO(tiborvass): remove authConfig 43 authConfig *types.AuthConfig 44 id string 45 } 46 47 type authTransport struct { 48 http.RoundTripper 49 *types.AuthConfig 50 51 alwaysSetBasicAuth bool 52 token []string 53 54 mu sync.Mutex // guards modReq 55 modReq map[*http.Request]*http.Request // original -> modified 56 } 57 58 // AuthTransport handles the auth layer when communicating with a v1 registry (private or official) 59 // 60 // For private v1 registries, set alwaysSetBasicAuth to true. 61 // 62 // For the official v1 registry, if there isn't already an Authorization header in the request, 63 // but there is an X-Docker-Token header set to true, then Basic Auth will be used to set the Authorization header. 64 // After sending the request with the provided base http.RoundTripper, if an X-Docker-Token header, representing 65 // a token, is present in the response, then it gets cached and sent in the Authorization header of all subsequent 66 // requests. 67 // 68 // If the server sends a token without the client having requested it, it is ignored. 69 // 70 // This RoundTripper also has a CancelRequest method important for correct timeout handling. 71 func AuthTransport(base http.RoundTripper, authConfig *types.AuthConfig, alwaysSetBasicAuth bool) http.RoundTripper { 72 if base == nil { 73 base = http.DefaultTransport 74 } 75 return &authTransport{ 76 RoundTripper: base, 77 AuthConfig: authConfig, 78 alwaysSetBasicAuth: alwaysSetBasicAuth, 79 modReq: make(map[*http.Request]*http.Request), 80 } 81 } 82 83 // cloneRequest returns a clone of the provided *http.Request. 84 // The clone is a shallow copy of the struct and its Header map. 85 func cloneRequest(r *http.Request) *http.Request { 86 // shallow copy of the struct 87 r2 := new(http.Request) 88 *r2 = *r 89 // deep copy of the Header 90 r2.Header = make(http.Header, len(r.Header)) 91 for k, s := range r.Header { 92 r2.Header[k] = append([]string(nil), s...) 93 } 94 95 return r2 96 } 97 98 // RoundTrip changes a HTTP request's headers to add the necessary 99 // authentication-related headers 100 func (tr *authTransport) RoundTrip(orig *http.Request) (*http.Response, error) { 101 // Authorization should not be set on 302 redirect for untrusted locations. 102 // This logic mirrors the behavior in addRequiredHeadersToRedirectedRequests. 103 // As the authorization logic is currently implemented in RoundTrip, 104 // a 302 redirect is detected by looking at the Referrer header as go http package adds said header. 105 // This is safe as Docker doesn't set Referrer in other scenarios. 106 if orig.Header.Get("Referer") != "" && !trustedLocation(orig) { 107 return tr.RoundTripper.RoundTrip(orig) 108 } 109 110 req := cloneRequest(orig) 111 tr.mu.Lock() 112 tr.modReq[orig] = req 113 tr.mu.Unlock() 114 115 if tr.alwaysSetBasicAuth { 116 if tr.AuthConfig == nil { 117 return nil, errors.New("unexpected error: empty auth config") 118 } 119 req.SetBasicAuth(tr.Username, tr.Password) 120 return tr.RoundTripper.RoundTrip(req) 121 } 122 123 // Don't override 124 if req.Header.Get("Authorization") == "" { 125 if req.Header.Get("X-Docker-Token") == "true" && tr.AuthConfig != nil && len(tr.Username) > 0 { 126 req.SetBasicAuth(tr.Username, tr.Password) 127 } else if len(tr.token) > 0 { 128 req.Header.Set("Authorization", "Token "+strings.Join(tr.token, ",")) 129 } 130 } 131 resp, err := tr.RoundTripper.RoundTrip(req) 132 if err != nil { 133 delete(tr.modReq, orig) 134 return nil, err 135 } 136 if len(resp.Header["X-Docker-Token"]) > 0 { 137 tr.token = resp.Header["X-Docker-Token"] 138 } 139 resp.Body = &ioutils.OnEOFReader{ 140 Rc: resp.Body, 141 Fn: func() { 142 tr.mu.Lock() 143 delete(tr.modReq, orig) 144 tr.mu.Unlock() 145 }, 146 } 147 return resp, nil 148 } 149 150 // CancelRequest cancels an in-flight request by closing its connection. 151 func (tr *authTransport) CancelRequest(req *http.Request) { 152 type canceler interface { 153 CancelRequest(*http.Request) 154 } 155 if cr, ok := tr.RoundTripper.(canceler); ok { 156 tr.mu.Lock() 157 modReq := tr.modReq[req] 158 delete(tr.modReq, req) 159 tr.mu.Unlock() 160 cr.CancelRequest(modReq) 161 } 162 } 163 164 // NewSession creates a new session 165 // TODO(tiborvass): remove authConfig param once registry client v2 is vendored 166 func NewSession(client *http.Client, authConfig *types.AuthConfig, endpoint *V1Endpoint) (r *Session, err error) { 167 r = &Session{ 168 authConfig: authConfig, 169 client: client, 170 indexEndpoint: endpoint, 171 id: stringid.GenerateRandomID(), 172 } 173 174 var alwaysSetBasicAuth bool 175 176 // If we're working with a standalone private registry over HTTPS, send Basic Auth headers 177 // alongside all our requests. 178 if endpoint.String() != IndexServer && endpoint.URL.Scheme == "https" { 179 info, err := endpoint.Ping() 180 if err != nil { 181 return nil, err 182 } 183 if info.Standalone && authConfig != nil { 184 logrus.Debugf("Endpoint %s is eligible for private registry. Enabling decorator.", endpoint.String()) 185 alwaysSetBasicAuth = true 186 } 187 } 188 189 // Annotate the transport unconditionally so that v2 can 190 // properly fallback on v1 when an image is not found. 191 client.Transport = AuthTransport(client.Transport, authConfig, alwaysSetBasicAuth) 192 193 jar, err := cookiejar.New(nil) 194 if err != nil { 195 return nil, errors.New("cookiejar.New is not supposed to return an error") 196 } 197 client.Jar = jar 198 199 return r, nil 200 } 201 202 // ID returns this registry session's ID. 203 func (r *Session) ID() string { 204 return r.id 205 } 206 207 // GetRemoteHistory retrieves the history of a given image from the registry. 208 // It returns a list of the parent's JSON files (including the requested image). 209 func (r *Session) GetRemoteHistory(imgID, registry string) ([]string, error) { 210 res, err := r.client.Get(registry + "images/" + imgID + "/ancestry") 211 if err != nil { 212 return nil, err 213 } 214 defer res.Body.Close() 215 if res.StatusCode != 200 { 216 if res.StatusCode == 401 { 217 return nil, errcode.ErrorCodeUnauthorized.WithArgs() 218 } 219 return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Server error: %d trying to fetch remote history for %s", res.StatusCode, imgID), res) 220 } 221 222 var history []string 223 if err := json.NewDecoder(res.Body).Decode(&history); err != nil { 224 return nil, fmt.Errorf("Error while reading the http response: %v", err) 225 } 226 227 logrus.Debugf("Ancestry: %v", history) 228 return history, nil 229 } 230 231 // LookupRemoteImage checks if an image exists in the registry 232 func (r *Session) LookupRemoteImage(imgID, registry string) error { 233 res, err := r.client.Get(registry + "images/" + imgID + "/json") 234 if err != nil { 235 return err 236 } 237 res.Body.Close() 238 if res.StatusCode != 200 { 239 return httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code %d", res.StatusCode), res) 240 } 241 return nil 242 } 243 244 // GetRemoteImageJSON retrieves an image's JSON metadata from the registry. 245 func (r *Session) GetRemoteImageJSON(imgID, registry string) ([]byte, int64, error) { 246 res, err := r.client.Get(registry + "images/" + imgID + "/json") 247 if err != nil { 248 return nil, -1, fmt.Errorf("Failed to download json: %s", err) 249 } 250 defer res.Body.Close() 251 if res.StatusCode != 200 { 252 return nil, -1, httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code %d", res.StatusCode), res) 253 } 254 // if the size header is not present, then set it to '-1' 255 imageSize := int64(-1) 256 if hdr := res.Header.Get("X-Docker-Size"); hdr != "" { 257 imageSize, err = strconv.ParseInt(hdr, 10, 64) 258 if err != nil { 259 return nil, -1, err 260 } 261 } 262 263 jsonString, err := ioutil.ReadAll(res.Body) 264 if err != nil { 265 return nil, -1, fmt.Errorf("Failed to parse downloaded json: %v (%s)", err, jsonString) 266 } 267 return jsonString, imageSize, nil 268 } 269 270 // GetRemoteImageLayer retrieves an image layer from the registry 271 func (r *Session) GetRemoteImageLayer(imgID, registry string, imgSize int64) (io.ReadCloser, error) { 272 var ( 273 statusCode = 0 274 res *http.Response 275 err error 276 imageURL = fmt.Sprintf("%simages/%s/layer", registry, imgID) 277 ) 278 279 req, err := http.NewRequest("GET", imageURL, nil) 280 if err != nil { 281 return nil, fmt.Errorf("Error while getting from the server: %v", err) 282 } 283 statusCode = 0 284 res, err = r.client.Do(req) 285 if err != nil { 286 logrus.Debugf("Error contacting registry %s: %v", registry, err) 287 // the only case err != nil && res != nil is https://golang.org/src/net/http/client.go#L515 288 if res != nil { 289 if res.Body != nil { 290 res.Body.Close() 291 } 292 statusCode = res.StatusCode 293 } 294 return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)", 295 statusCode, imgID) 296 } 297 298 if res.StatusCode != 200 { 299 res.Body.Close() 300 return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)", 301 res.StatusCode, imgID) 302 } 303 304 if res.Header.Get("Accept-Ranges") == "bytes" && imgSize > 0 { 305 logrus.Debugf("server supports resume") 306 return httputils.ResumableRequestReaderWithInitialResponse(r.client, req, 5, imgSize, res), nil 307 } 308 logrus.Debugf("server doesn't support resume") 309 return res.Body, nil 310 } 311 312 // GetRemoteTag retrieves the tag named in the askedTag argument from the given 313 // repository. It queries each of the registries supplied in the registries 314 // argument, and returns data from the first one that answers the query 315 // successfully. 316 func (r *Session) GetRemoteTag(registries []string, repositoryRef reference.Named, askedTag string) (string, error) { 317 repository := repositoryRef.RemoteName() 318 319 if strings.Count(repository, "/") == 0 { 320 // This will be removed once the registry supports auto-resolution on 321 // the "library" namespace 322 repository = "library/" + repository 323 } 324 for _, host := range registries { 325 endpoint := fmt.Sprintf("%srepositories/%s/tags/%s", host, repository, askedTag) 326 res, err := r.client.Get(endpoint) 327 if err != nil { 328 return "", err 329 } 330 331 logrus.Debugf("Got status code %d from %s", res.StatusCode, endpoint) 332 defer res.Body.Close() 333 334 if res.StatusCode == 404 { 335 return "", ErrRepoNotFound 336 } 337 if res.StatusCode != 200 { 338 continue 339 } 340 341 var tagID string 342 if err := json.NewDecoder(res.Body).Decode(&tagID); err != nil { 343 return "", err 344 } 345 return tagID, nil 346 } 347 return "", fmt.Errorf("Could not reach any registry endpoint") 348 } 349 350 // GetRemoteTags retrieves all tags from the given repository. It queries each 351 // of the registries supplied in the registries argument, and returns data from 352 // the first one that answers the query successfully. It returns a map with 353 // tag names as the keys and image IDs as the values. 354 func (r *Session) GetRemoteTags(registries []string, repositoryRef reference.Named) (map[string]string, error) { 355 repository := repositoryRef.RemoteName() 356 357 if strings.Count(repository, "/") == 0 { 358 // This will be removed once the registry supports auto-resolution on 359 // the "library" namespace 360 repository = "library/" + repository 361 } 362 for _, host := range registries { 363 endpoint := fmt.Sprintf("%srepositories/%s/tags", host, repository) 364 res, err := r.client.Get(endpoint) 365 if err != nil { 366 return nil, err 367 } 368 369 logrus.Debugf("Got status code %d from %s", res.StatusCode, endpoint) 370 defer res.Body.Close() 371 372 if res.StatusCode == 404 { 373 return nil, ErrRepoNotFound 374 } 375 if res.StatusCode != 200 { 376 continue 377 } 378 379 result := make(map[string]string) 380 if err := json.NewDecoder(res.Body).Decode(&result); err != nil { 381 return nil, err 382 } 383 return result, nil 384 } 385 return nil, fmt.Errorf("Could not reach any registry endpoint") 386 } 387 388 func buildEndpointsList(headers []string, indexEp string) ([]string, error) { 389 var endpoints []string 390 parsedURL, err := url.Parse(indexEp) 391 if err != nil { 392 return nil, err 393 } 394 var urlScheme = parsedURL.Scheme 395 // The registry's URL scheme has to match the Index' 396 for _, ep := range headers { 397 epList := strings.Split(ep, ",") 398 for _, epListElement := range epList { 399 endpoints = append( 400 endpoints, 401 fmt.Sprintf("%s://%s/v1/", urlScheme, strings.TrimSpace(epListElement))) 402 } 403 } 404 return endpoints, nil 405 } 406 407 // GetRepositoryData returns lists of images and endpoints for the repository 408 func (r *Session) GetRepositoryData(name reference.Named) (*RepositoryData, error) { 409 repositoryTarget := fmt.Sprintf("%srepositories/%s/images", r.indexEndpoint.String(), name.RemoteName()) 410 411 logrus.Debugf("[registry] Calling GET %s", repositoryTarget) 412 413 req, err := http.NewRequest("GET", repositoryTarget, nil) 414 if err != nil { 415 return nil, err 416 } 417 // this will set basic auth in r.client.Transport and send cached X-Docker-Token headers for all subsequent requests 418 req.Header.Set("X-Docker-Token", "true") 419 res, err := r.client.Do(req) 420 if err != nil { 421 // check if the error is because of i/o timeout 422 // and return a non-obtuse error message for users 423 // "Get https://index.docker.io/v1/repositories/library/busybox/images: i/o timeout" 424 // was a top search on the docker user forum 425 if isTimeout(err) { 426 return nil, fmt.Errorf("Network timed out while trying to connect to %s. You may want to check your internet connection or if you are behind a proxy.", repositoryTarget) 427 } 428 return nil, fmt.Errorf("Error while pulling image: %v", err) 429 } 430 defer res.Body.Close() 431 if res.StatusCode == 401 { 432 return nil, errcode.ErrorCodeUnauthorized.WithArgs() 433 } 434 // TODO: Right now we're ignoring checksums in the response body. 435 // In the future, we need to use them to check image validity. 436 if res.StatusCode == 404 { 437 return nil, httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code: %d", res.StatusCode), res) 438 } else if res.StatusCode != 200 { 439 errBody, err := ioutil.ReadAll(res.Body) 440 if err != nil { 441 logrus.Debugf("Error reading response body: %s", err) 442 } 443 return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to pull repository %s: %q", res.StatusCode, name.RemoteName(), errBody), res) 444 } 445 446 var endpoints []string 447 if res.Header.Get("X-Docker-Endpoints") != "" { 448 endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.String()) 449 if err != nil { 450 return nil, err 451 } 452 } else { 453 // Assume the endpoint is on the same host 454 endpoints = append(endpoints, fmt.Sprintf("%s://%s/v1/", r.indexEndpoint.URL.Scheme, req.URL.Host)) 455 } 456 457 remoteChecksums := []*ImgData{} 458 if err := json.NewDecoder(res.Body).Decode(&remoteChecksums); err != nil { 459 return nil, err 460 } 461 462 // Forge a better object from the retrieved data 463 imgsData := make(map[string]*ImgData, len(remoteChecksums)) 464 for _, elem := range remoteChecksums { 465 imgsData[elem.ID] = elem 466 } 467 468 return &RepositoryData{ 469 ImgList: imgsData, 470 Endpoints: endpoints, 471 }, nil 472 } 473 474 // PushImageChecksumRegistry uploads checksums for an image 475 func (r *Session) PushImageChecksumRegistry(imgData *ImgData, registry string) error { 476 u := registry + "images/" + imgData.ID + "/checksum" 477 478 logrus.Debugf("[registry] Calling PUT %s", u) 479 480 req, err := http.NewRequest("PUT", u, nil) 481 if err != nil { 482 return err 483 } 484 req.Header.Set("X-Docker-Checksum", imgData.Checksum) 485 req.Header.Set("X-Docker-Checksum-Payload", imgData.ChecksumPayload) 486 487 res, err := r.client.Do(req) 488 if err != nil { 489 return fmt.Errorf("Failed to upload metadata: %v", err) 490 } 491 defer res.Body.Close() 492 if len(res.Cookies()) > 0 { 493 r.client.Jar.SetCookies(req.URL, res.Cookies()) 494 } 495 if res.StatusCode != 200 { 496 errBody, err := ioutil.ReadAll(res.Body) 497 if err != nil { 498 return fmt.Errorf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err) 499 } 500 var jsonBody map[string]string 501 if err := json.Unmarshal(errBody, &jsonBody); err != nil { 502 errBody = []byte(err.Error()) 503 } else if jsonBody["error"] == "Image already exists" { 504 return ErrAlreadyExists 505 } 506 return fmt.Errorf("HTTP code %d while uploading metadata: %q", res.StatusCode, errBody) 507 } 508 return nil 509 } 510 511 // PushImageJSONRegistry pushes JSON metadata for a local image to the registry 512 func (r *Session) PushImageJSONRegistry(imgData *ImgData, jsonRaw []byte, registry string) error { 513 514 u := registry + "images/" + imgData.ID + "/json" 515 516 logrus.Debugf("[registry] Calling PUT %s", u) 517 518 req, err := http.NewRequest("PUT", u, bytes.NewReader(jsonRaw)) 519 if err != nil { 520 return err 521 } 522 req.Header.Add("Content-type", "application/json") 523 524 res, err := r.client.Do(req) 525 if err != nil { 526 return fmt.Errorf("Failed to upload metadata: %s", err) 527 } 528 defer res.Body.Close() 529 if res.StatusCode == 401 && strings.HasPrefix(registry, "http://") { 530 return httputils.NewHTTPRequestError("HTTP code 401, Docker will not send auth headers over HTTP.", res) 531 } 532 if res.StatusCode != 200 { 533 errBody, err := ioutil.ReadAll(res.Body) 534 if err != nil { 535 return httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err), res) 536 } 537 var jsonBody map[string]string 538 if err := json.Unmarshal(errBody, &jsonBody); err != nil { 539 errBody = []byte(err.Error()) 540 } else if jsonBody["error"] == "Image already exists" { 541 return ErrAlreadyExists 542 } 543 return httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code %d while uploading metadata: %q", res.StatusCode, errBody), res) 544 } 545 return nil 546 } 547 548 // PushImageLayerRegistry sends the checksum of an image layer to the registry 549 func (r *Session) PushImageLayerRegistry(imgID string, layer io.Reader, registry string, jsonRaw []byte) (checksum string, checksumPayload string, err error) { 550 u := registry + "images/" + imgID + "/layer" 551 552 logrus.Debugf("[registry] Calling PUT %s", u) 553 554 tarsumLayer, err := tarsum.NewTarSum(layer, false, tarsum.Version0) 555 if err != nil { 556 return "", "", err 557 } 558 h := sha256.New() 559 h.Write(jsonRaw) 560 h.Write([]byte{'\n'}) 561 checksumLayer := io.TeeReader(tarsumLayer, h) 562 563 req, err := http.NewRequest("PUT", u, checksumLayer) 564 if err != nil { 565 return "", "", err 566 } 567 req.Header.Add("Content-Type", "application/octet-stream") 568 req.ContentLength = -1 569 req.TransferEncoding = []string{"chunked"} 570 res, err := r.client.Do(req) 571 if err != nil { 572 return "", "", fmt.Errorf("Failed to upload layer: %v", err) 573 } 574 if rc, ok := layer.(io.Closer); ok { 575 if err := rc.Close(); err != nil { 576 return "", "", err 577 } 578 } 579 defer res.Body.Close() 580 581 if res.StatusCode != 200 { 582 errBody, err := ioutil.ReadAll(res.Body) 583 if err != nil { 584 return "", "", httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err), res) 585 } 586 return "", "", httputils.NewHTTPRequestError(fmt.Sprintf("Received HTTP code %d while uploading layer: %q", res.StatusCode, errBody), res) 587 } 588 589 checksumPayload = "sha256:" + hex.EncodeToString(h.Sum(nil)) 590 return tarsumLayer.Sum(jsonRaw), checksumPayload, nil 591 } 592 593 // PushRegistryTag pushes a tag on the registry. 594 // Remote has the format '<user>/<repo> 595 func (r *Session) PushRegistryTag(remote reference.Named, revision, tag, registry string) error { 596 // "jsonify" the string 597 revision = "\"" + revision + "\"" 598 path := fmt.Sprintf("repositories/%s/tags/%s", remote.RemoteName(), tag) 599 600 req, err := http.NewRequest("PUT", registry+path, strings.NewReader(revision)) 601 if err != nil { 602 return err 603 } 604 req.Header.Add("Content-type", "application/json") 605 req.ContentLength = int64(len(revision)) 606 res, err := r.client.Do(req) 607 if err != nil { 608 return err 609 } 610 res.Body.Close() 611 if res.StatusCode != 200 && res.StatusCode != 201 { 612 return httputils.NewHTTPRequestError(fmt.Sprintf("Internal server error: %d trying to push tag %s on %s", res.StatusCode, tag, remote.RemoteName()), res) 613 } 614 return nil 615 } 616 617 // PushImageJSONIndex uploads an image list to the repository 618 func (r *Session) PushImageJSONIndex(remote reference.Named, imgList []*ImgData, validate bool, regs []string) (*RepositoryData, error) { 619 cleanImgList := []*ImgData{} 620 if validate { 621 for _, elem := range imgList { 622 if elem.Checksum != "" { 623 cleanImgList = append(cleanImgList, elem) 624 } 625 } 626 } else { 627 cleanImgList = imgList 628 } 629 630 imgListJSON, err := json.Marshal(cleanImgList) 631 if err != nil { 632 return nil, err 633 } 634 var suffix string 635 if validate { 636 suffix = "images" 637 } 638 u := fmt.Sprintf("%srepositories/%s/%s", r.indexEndpoint.String(), remote.RemoteName(), suffix) 639 logrus.Debugf("[registry] PUT %s", u) 640 logrus.Debugf("Image list pushed to index:\n%s", imgListJSON) 641 headers := map[string][]string{ 642 "Content-type": {"application/json"}, 643 // this will set basic auth in r.client.Transport and send cached X-Docker-Token headers for all subsequent requests 644 "X-Docker-Token": {"true"}, 645 } 646 if validate { 647 headers["X-Docker-Endpoints"] = regs 648 } 649 650 // Redirect if necessary 651 var res *http.Response 652 for { 653 if res, err = r.putImageRequest(u, headers, imgListJSON); err != nil { 654 return nil, err 655 } 656 if !shouldRedirect(res) { 657 break 658 } 659 res.Body.Close() 660 u = res.Header.Get("Location") 661 logrus.Debugf("Redirected to %s", u) 662 } 663 defer res.Body.Close() 664 665 if res.StatusCode == 401 { 666 return nil, errcode.ErrorCodeUnauthorized.WithArgs() 667 } 668 669 var tokens, endpoints []string 670 if !validate { 671 if res.StatusCode != 200 && res.StatusCode != 201 { 672 errBody, err := ioutil.ReadAll(res.Body) 673 if err != nil { 674 logrus.Debugf("Error reading response body: %s", err) 675 } 676 return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to push repository %s: %q", res.StatusCode, remote.RemoteName(), errBody), res) 677 } 678 tokens = res.Header["X-Docker-Token"] 679 logrus.Debugf("Auth token: %v", tokens) 680 681 if res.Header.Get("X-Docker-Endpoints") == "" { 682 return nil, fmt.Errorf("Index response didn't contain any endpoints") 683 } 684 endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.String()) 685 if err != nil { 686 return nil, err 687 } 688 } else { 689 if res.StatusCode != 204 { 690 errBody, err := ioutil.ReadAll(res.Body) 691 if err != nil { 692 logrus.Debugf("Error reading response body: %s", err) 693 } 694 return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to push checksums %s: %q", res.StatusCode, remote.RemoteName(), errBody), res) 695 } 696 } 697 698 return &RepositoryData{ 699 Endpoints: endpoints, 700 }, nil 701 } 702 703 func (r *Session) putImageRequest(u string, headers map[string][]string, body []byte) (*http.Response, error) { 704 req, err := http.NewRequest("PUT", u, bytes.NewReader(body)) 705 if err != nil { 706 return nil, err 707 } 708 req.ContentLength = int64(len(body)) 709 for k, v := range headers { 710 req.Header[k] = v 711 } 712 response, err := r.client.Do(req) 713 if err != nil { 714 return nil, err 715 } 716 return response, nil 717 } 718 719 func shouldRedirect(response *http.Response) bool { 720 return response.StatusCode >= 300 && response.StatusCode < 400 721 } 722 723 // SearchRepositories performs a search against the remote repository 724 func (r *Session) SearchRepositories(term string) (*registrytypes.SearchResults, error) { 725 logrus.Debugf("Index server: %s", r.indexEndpoint) 726 u := r.indexEndpoint.String() + "search?q=" + url.QueryEscape(term) 727 728 req, err := http.NewRequest("GET", u, nil) 729 if err != nil { 730 return nil, fmt.Errorf("Error while getting from the server: %v", err) 731 } 732 // Have the AuthTransport send authentication, when logged in. 733 req.Header.Set("X-Docker-Token", "true") 734 res, err := r.client.Do(req) 735 if err != nil { 736 return nil, err 737 } 738 defer res.Body.Close() 739 if res.StatusCode != 200 { 740 return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Unexpected status code %d", res.StatusCode), res) 741 } 742 result := new(registrytypes.SearchResults) 743 return result, json.NewDecoder(res.Body).Decode(result) 744 } 745 746 // GetAuthConfig returns the authentication settings for a session 747 // TODO(tiborvass): remove this once registry client v2 is vendored 748 func (r *Session) GetAuthConfig(withPasswd bool) *types.AuthConfig { 749 password := "" 750 if withPasswd { 751 password = r.authConfig.Password 752 } 753 return &types.AuthConfig{ 754 Username: r.authConfig.Username, 755 Password: password, 756 } 757 } 758 759 func isTimeout(err error) bool { 760 type timeout interface { 761 Timeout() bool 762 } 763 e := err 764 switch urlErr := err.(type) { 765 case *url.Error: 766 e = urlErr.Err 767 } 768 t, ok := e.(timeout) 769 return ok && t.Timeout() 770 }