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