]> Cypherpunks.ru repositories - gostls13.git/blob - src/net/http/client.go
1e300acf89be1c57c5aacda0d0b79943e11c3d2b
[gostls13.git] / src / net / http / client.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // HTTP client. See RFC 7230 through 7235.
6 //
7 // This is the high-level Client interface.
8 // The low-level implementation is in transport.go.
9
10 package http
11
12 import (
13         "context"
14         "crypto/tls"
15         "encoding/base64"
16         "errors"
17         "fmt"
18         "io"
19         "log"
20         "net/http/internal/ascii"
21         "net/url"
22         "reflect"
23         "sort"
24         "strings"
25         "sync"
26         "sync/atomic"
27         "time"
28 )
29
30 // A Client is an HTTP client. Its zero value (DefaultClient) is a
31 // usable client that uses DefaultTransport.
32 //
33 // The Client's Transport typically has internal state (cached TCP
34 // connections), so Clients should be reused instead of created as
35 // needed. Clients are safe for concurrent use by multiple goroutines.
36 //
37 // A Client is higher-level than a RoundTripper (such as Transport)
38 // and additionally handles HTTP details such as cookies and
39 // redirects.
40 //
41 // When following redirects, the Client will forward all headers set on the
42 // initial Request except:
43 //
44 // • when forwarding sensitive headers like "Authorization",
45 // "WWW-Authenticate", and "Cookie" to untrusted targets.
46 // These headers will be ignored when following a redirect to a domain
47 // that is not a subdomain match or exact match of the initial domain.
48 // For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com"
49 // will forward the sensitive headers, but a redirect to "bar.com" will not.
50 //
51 // • when forwarding the "Cookie" header with a non-nil cookie Jar.
52 // Since each redirect may mutate the state of the cookie jar,
53 // a redirect may possibly alter a cookie set in the initial request.
54 // When forwarding the "Cookie" header, any mutated cookies will be omitted,
55 // with the expectation that the Jar will insert those mutated cookies
56 // with the updated values (assuming the origin matches).
57 // If Jar is nil, the initial cookies are forwarded without change.
58 type Client struct {
59         // Transport specifies the mechanism by which individual
60         // HTTP requests are made.
61         // If nil, DefaultTransport is used.
62         Transport RoundTripper
63
64         // CheckRedirect specifies the policy for handling redirects.
65         // If CheckRedirect is not nil, the client calls it before
66         // following an HTTP redirect. The arguments req and via are
67         // the upcoming request and the requests made already, oldest
68         // first. If CheckRedirect returns an error, the Client's Get
69         // method returns both the previous Response (with its Body
70         // closed) and CheckRedirect's error (wrapped in a url.Error)
71         // instead of issuing the Request req.
72         // As a special case, if CheckRedirect returns ErrUseLastResponse,
73         // then the most recent response is returned with its body
74         // unclosed, along with a nil error.
75         //
76         // If CheckRedirect is nil, the Client uses its default policy,
77         // which is to stop after 10 consecutive requests.
78         CheckRedirect func(req *Request, via []*Request) error
79
80         // Jar specifies the cookie jar.
81         //
82         // The Jar is used to insert relevant cookies into every
83         // outbound Request and is updated with the cookie values
84         // of every inbound Response. The Jar is consulted for every
85         // redirect that the Client follows.
86         //
87         // If Jar is nil, cookies are only sent if they are explicitly
88         // set on the Request.
89         Jar CookieJar
90
91         // Timeout specifies a time limit for requests made by this
92         // Client. The timeout includes connection time, any
93         // redirects, and reading the response body. The timer remains
94         // running after Get, Head, Post, or Do return and will
95         // interrupt reading of the Response.Body.
96         //
97         // A Timeout of zero means no timeout.
98         //
99         // The Client cancels requests to the underlying Transport
100         // as if the Request's Context ended.
101         //
102         // For compatibility, the Client will also use the deprecated
103         // CancelRequest method on Transport if found. New
104         // RoundTripper implementations should use the Request's Context
105         // for cancellation instead of implementing CancelRequest.
106         Timeout time.Duration
107 }
108
109 // DefaultClient is the default Client and is used by Get, Head, and Post.
110 var DefaultClient = &Client{}
111
112 // RoundTripper is an interface representing the ability to execute a
113 // single HTTP transaction, obtaining the Response for a given Request.
114 //
115 // A RoundTripper must be safe for concurrent use by multiple
116 // goroutines.
117 type RoundTripper interface {
118         // RoundTrip executes a single HTTP transaction, returning
119         // a Response for the provided Request.
120         //
121         // RoundTrip should not attempt to interpret the response. In
122         // particular, RoundTrip must return err == nil if it obtained
123         // a response, regardless of the response's HTTP status code.
124         // A non-nil err should be reserved for failure to obtain a
125         // response. Similarly, RoundTrip should not attempt to
126         // handle higher-level protocol details such as redirects,
127         // authentication, or cookies.
128         //
129         // RoundTrip should not modify the request, except for
130         // consuming and closing the Request's Body. RoundTrip may
131         // read fields of the request in a separate goroutine. Callers
132         // should not mutate or reuse the request until the Response's
133         // Body has been closed.
134         //
135         // RoundTrip must always close the body, including on errors,
136         // but depending on the implementation may do so in a separate
137         // goroutine even after RoundTrip returns. This means that
138         // callers wanting to reuse the body for subsequent requests
139         // must arrange to wait for the Close call before doing so.
140         //
141         // The Request's URL and Header fields must be initialized.
142         RoundTrip(*Request) (*Response, error)
143 }
144
145 // refererForURL returns a referer without any authentication info or
146 // an empty string if lastReq scheme is https and newReq scheme is http.
147 // If the referer was explicitly set, then it will continue to be used.
148 func refererForURL(lastReq, newReq *url.URL, explicitRef string) string {
149         // https://tools.ietf.org/html/rfc7231#section-5.5.2
150         //   "Clients SHOULD NOT include a Referer header field in a
151         //    (non-secure) HTTP request if the referring page was
152         //    transferred with a secure protocol."
153         if lastReq.Scheme == "https" && newReq.Scheme == "http" {
154                 return ""
155         }
156         if explicitRef != "" {
157                 return explicitRef
158         }
159
160         referer := lastReq.String()
161         if lastReq.User != nil {
162                 // This is not very efficient, but is the best we can
163                 // do without:
164                 // - introducing a new method on URL
165                 // - creating a race condition
166                 // - copying the URL struct manually, which would cause
167                 //   maintenance problems down the line
168                 auth := lastReq.User.String() + "@"
169                 referer = strings.Replace(referer, auth, "", 1)
170         }
171         return referer
172 }
173
174 // didTimeout is non-nil only if err != nil.
175 func (c *Client) send(req *Request, deadline time.Time) (resp *Response, didTimeout func() bool, err error) {
176         if c.Jar != nil {
177                 for _, cookie := range c.Jar.Cookies(req.URL) {
178                         req.AddCookie(cookie)
179                 }
180         }
181         resp, didTimeout, err = send(req, c.transport(), deadline)
182         if err != nil {
183                 return nil, didTimeout, err
184         }
185         if c.Jar != nil {
186                 if rc := resp.Cookies(); len(rc) > 0 {
187                         c.Jar.SetCookies(req.URL, rc)
188                 }
189         }
190         return resp, nil, nil
191 }
192
193 func (c *Client) deadline() time.Time {
194         if c.Timeout > 0 {
195                 return time.Now().Add(c.Timeout)
196         }
197         return time.Time{}
198 }
199
200 func (c *Client) transport() RoundTripper {
201         if c.Transport != nil {
202                 return c.Transport
203         }
204         return DefaultTransport
205 }
206
207 // send issues an HTTP request.
208 // Caller should close resp.Body when done reading from it.
209 func send(ireq *Request, rt RoundTripper, deadline time.Time) (resp *Response, didTimeout func() bool, err error) {
210         req := ireq // req is either the original request, or a modified fork
211
212         if rt == nil {
213                 req.closeBody()
214                 return nil, alwaysFalse, errors.New("http: no Client.Transport or DefaultTransport")
215         }
216
217         if req.URL == nil {
218                 req.closeBody()
219                 return nil, alwaysFalse, errors.New("http: nil Request.URL")
220         }
221
222         if req.RequestURI != "" {
223                 req.closeBody()
224                 return nil, alwaysFalse, errors.New("http: Request.RequestURI can't be set in client requests")
225         }
226
227         // forkReq forks req into a shallow clone of ireq the first
228         // time it's called.
229         forkReq := func() {
230                 if ireq == req {
231                         req = new(Request)
232                         *req = *ireq // shallow clone
233                 }
234         }
235
236         // Most the callers of send (Get, Post, et al) don't need
237         // Headers, leaving it uninitialized. We guarantee to the
238         // Transport that this has been initialized, though.
239         if req.Header == nil {
240                 forkReq()
241                 req.Header = make(Header)
242         }
243
244         if u := req.URL.User; u != nil && req.Header.Get("Authorization") == "" {
245                 username := u.Username()
246                 password, _ := u.Password()
247                 forkReq()
248                 req.Header = cloneOrMakeHeader(ireq.Header)
249                 req.Header.Set("Authorization", "Basic "+basicAuth(username, password))
250         }
251
252         if !deadline.IsZero() {
253                 forkReq()
254         }
255         stopTimer, didTimeout := setRequestCancel(req, rt, deadline)
256
257         resp, err = rt.RoundTrip(req)
258         if err != nil {
259                 stopTimer()
260                 if resp != nil {
261                         log.Printf("RoundTripper returned a response & error; ignoring response")
262                 }
263                 if tlsErr, ok := err.(tls.RecordHeaderError); ok {
264                         // If we get a bad TLS record header, check to see if the
265                         // response looks like HTTP and give a more helpful error.
266                         // See golang.org/issue/11111.
267                         if string(tlsErr.RecordHeader[:]) == "HTTP/" {
268                                 err = errors.New("http: server gave HTTP response to HTTPS client")
269                         }
270                 }
271                 return nil, didTimeout, err
272         }
273         if resp == nil {
274                 return nil, didTimeout, fmt.Errorf("http: RoundTripper implementation (%T) returned a nil *Response with a nil error", rt)
275         }
276         if resp.Body == nil {
277                 // The documentation on the Body field says “The http Client and Transport
278                 // guarantee that Body is always non-nil, even on responses without a body
279                 // or responses with a zero-length body.” Unfortunately, we didn't document
280                 // that same constraint for arbitrary RoundTripper implementations, and
281                 // RoundTripper implementations in the wild (mostly in tests) assume that
282                 // they can use a nil Body to mean an empty one (similar to Request.Body).
283                 // (See https://golang.org/issue/38095.)
284                 //
285                 // If the ContentLength allows the Body to be empty, fill in an empty one
286                 // here to ensure that it is non-nil.
287                 if resp.ContentLength > 0 && req.Method != "HEAD" {
288                         return nil, didTimeout, fmt.Errorf("http: RoundTripper implementation (%T) returned a *Response with content length %d but a nil Body", rt, resp.ContentLength)
289                 }
290                 resp.Body = io.NopCloser(strings.NewReader(""))
291         }
292         if !deadline.IsZero() {
293                 resp.Body = &cancelTimerBody{
294                         stop:          stopTimer,
295                         rc:            resp.Body,
296                         reqDidTimeout: didTimeout,
297                 }
298         }
299         return resp, nil, nil
300 }
301
302 // timeBeforeContextDeadline reports whether the non-zero Time t is
303 // before ctx's deadline, if any. If ctx does not have a deadline, it
304 // always reports true (the deadline is considered infinite).
305 func timeBeforeContextDeadline(t time.Time, ctx context.Context) bool {
306         d, ok := ctx.Deadline()
307         if !ok {
308                 return true
309         }
310         return t.Before(d)
311 }
312
313 // knownRoundTripperImpl reports whether rt is a RoundTripper that's
314 // maintained by the Go team and known to implement the latest
315 // optional semantics (notably contexts). The Request is used
316 // to check whether this particular request is using an alternate protocol,
317 // in which case we need to check the RoundTripper for that protocol.
318 func knownRoundTripperImpl(rt RoundTripper, req *Request) bool {
319         switch t := rt.(type) {
320         case *Transport:
321                 if altRT := t.alternateRoundTripper(req); altRT != nil {
322                         return knownRoundTripperImpl(altRT, req)
323                 }
324                 return true
325         case *http2Transport, http2noDialH2RoundTripper:
326                 return true
327         }
328         // There's a very minor chance of a false positive with this.
329         // Instead of detecting our golang.org/x/net/http2.Transport,
330         // it might detect a Transport type in a different http2
331         // package. But I know of none, and the only problem would be
332         // some temporarily leaked goroutines if the transport didn't
333         // support contexts. So this is a good enough heuristic:
334         if reflect.TypeOf(rt).String() == "*http2.Transport" {
335                 return true
336         }
337         return false
338 }
339
340 // setRequestCancel sets req.Cancel and adds a deadline context to req
341 // if deadline is non-zero. The RoundTripper's type is used to
342 // determine whether the legacy CancelRequest behavior should be used.
343 //
344 // As background, there are three ways to cancel a request:
345 // First was Transport.CancelRequest. (deprecated)
346 // Second was Request.Cancel.
347 // Third was Request.Context.
348 // This function populates the second and third, and uses the first if it really needs to.
349 func setRequestCancel(req *Request, rt RoundTripper, deadline time.Time) (stopTimer func(), didTimeout func() bool) {
350         if deadline.IsZero() {
351                 return nop, alwaysFalse
352         }
353         knownTransport := knownRoundTripperImpl(rt, req)
354         oldCtx := req.Context()
355
356         if req.Cancel == nil && knownTransport {
357                 // If they already had a Request.Context that's
358                 // expiring sooner, do nothing:
359                 if !timeBeforeContextDeadline(deadline, oldCtx) {
360                         return nop, alwaysFalse
361                 }
362
363                 var cancelCtx func()
364                 req.ctx, cancelCtx = context.WithDeadline(oldCtx, deadline)
365                 return cancelCtx, func() bool { return time.Now().After(deadline) }
366         }
367         initialReqCancel := req.Cancel // the user's original Request.Cancel, if any
368
369         var cancelCtx func()
370         if timeBeforeContextDeadline(deadline, oldCtx) {
371                 req.ctx, cancelCtx = context.WithDeadline(oldCtx, deadline)
372         }
373
374         cancel := make(chan struct{})
375         req.Cancel = cancel
376
377         doCancel := func() {
378                 // The second way in the func comment above:
379                 close(cancel)
380                 // The first way, used only for RoundTripper
381                 // implementations written before Go 1.5 or Go 1.6.
382                 type canceler interface{ CancelRequest(*Request) }
383                 if v, ok := rt.(canceler); ok {
384                         v.CancelRequest(req)
385                 }
386         }
387
388         stopTimerCh := make(chan struct{})
389         var once sync.Once
390         stopTimer = func() {
391                 once.Do(func() {
392                         close(stopTimerCh)
393                         if cancelCtx != nil {
394                                 cancelCtx()
395                         }
396                 })
397         }
398
399         timer := time.NewTimer(time.Until(deadline))
400         var timedOut atomic.Bool
401
402         go func() {
403                 select {
404                 case <-initialReqCancel:
405                         doCancel()
406                         timer.Stop()
407                 case <-timer.C:
408                         timedOut.Store(true)
409                         doCancel()
410                 case <-stopTimerCh:
411                         timer.Stop()
412                 }
413         }()
414
415         return stopTimer, timedOut.Load
416 }
417
418 // See 2 (end of page 4) https://www.ietf.org/rfc/rfc2617.txt
419 // "To receive authorization, the client sends the userid and password,
420 // separated by a single colon (":") character, within a base64
421 // encoded string in the credentials."
422 // It is not meant to be urlencoded.
423 func basicAuth(username, password string) string {
424         auth := username + ":" + password
425         return base64.StdEncoding.EncodeToString([]byte(auth))
426 }
427
428 // Get issues a GET to the specified URL. If the response is one of
429 // the following redirect codes, Get follows the redirect, up to a
430 // maximum of 10 redirects:
431 //
432 //      301 (Moved Permanently)
433 //      302 (Found)
434 //      303 (See Other)
435 //      307 (Temporary Redirect)
436 //      308 (Permanent Redirect)
437 //
438 // An error is returned if there were too many redirects or if there
439 // was an HTTP protocol error. A non-2xx response doesn't cause an
440 // error. Any returned error will be of type *url.Error. The url.Error
441 // value's Timeout method will report true if the request timed out.
442 //
443 // When err is nil, resp always contains a non-nil resp.Body.
444 // Caller should close resp.Body when done reading from it.
445 //
446 // Get is a wrapper around DefaultClient.Get.
447 //
448 // To make a request with custom headers, use NewRequest and
449 // DefaultClient.Do.
450 //
451 // To make a request with a specified context.Context, use NewRequestWithContext
452 // and DefaultClient.Do.
453 func Get(url string) (resp *Response, err error) {
454         return DefaultClient.Get(url)
455 }
456
457 // Get issues a GET to the specified URL. If the response is one of the
458 // following redirect codes, Get follows the redirect after calling the
459 // Client's CheckRedirect function:
460 //
461 //      301 (Moved Permanently)
462 //      302 (Found)
463 //      303 (See Other)
464 //      307 (Temporary Redirect)
465 //      308 (Permanent Redirect)
466 //
467 // An error is returned if the Client's CheckRedirect function fails
468 // or if there was an HTTP protocol error. A non-2xx response doesn't
469 // cause an error. Any returned error will be of type *url.Error. The
470 // url.Error value's Timeout method will report true if the request
471 // timed out.
472 //
473 // When err is nil, resp always contains a non-nil resp.Body.
474 // Caller should close resp.Body when done reading from it.
475 //
476 // To make a request with custom headers, use NewRequest and Client.Do.
477 //
478 // To make a request with a specified context.Context, use NewRequestWithContext
479 // and Client.Do.
480 func (c *Client) Get(url string) (resp *Response, err error) {
481         req, err := NewRequest("GET", url, nil)
482         if err != nil {
483                 return nil, err
484         }
485         return c.Do(req)
486 }
487
488 func alwaysFalse() bool { return false }
489
490 // ErrUseLastResponse can be returned by Client.CheckRedirect hooks to
491 // control how redirects are processed. If returned, the next request
492 // is not sent and the most recent response is returned with its body
493 // unclosed.
494 var ErrUseLastResponse = errors.New("net/http: use last response")
495
496 // checkRedirect calls either the user's configured CheckRedirect
497 // function, or the default.
498 func (c *Client) checkRedirect(req *Request, via []*Request) error {
499         fn := c.CheckRedirect
500         if fn == nil {
501                 fn = defaultCheckRedirect
502         }
503         return fn(req, via)
504 }
505
506 // redirectBehavior describes what should happen when the
507 // client encounters a 3xx status code from the server.
508 func redirectBehavior(reqMethod string, resp *Response, ireq *Request) (redirectMethod string, shouldRedirect, includeBody bool) {
509         switch resp.StatusCode {
510         case 301, 302, 303:
511                 redirectMethod = reqMethod
512                 shouldRedirect = true
513                 includeBody = false
514
515                 // RFC 2616 allowed automatic redirection only with GET and
516                 // HEAD requests. RFC 7231 lifts this restriction, but we still
517                 // restrict other methods to GET to maintain compatibility.
518                 // See Issue 18570.
519                 if reqMethod != "GET" && reqMethod != "HEAD" {
520                         redirectMethod = "GET"
521                 }
522         case 307, 308:
523                 redirectMethod = reqMethod
524                 shouldRedirect = true
525                 includeBody = true
526
527                 if ireq.GetBody == nil && ireq.outgoingLength() != 0 {
528                         // We had a request body, and 307/308 require
529                         // re-sending it, but GetBody is not defined. So just
530                         // return this response to the user instead of an
531                         // error, like we did in Go 1.7 and earlier.
532                         shouldRedirect = false
533                 }
534         }
535         return redirectMethod, shouldRedirect, includeBody
536 }
537
538 // urlErrorOp returns the (*url.Error).Op value to use for the
539 // provided (*Request).Method value.
540 func urlErrorOp(method string) string {
541         if method == "" {
542                 return "Get"
543         }
544         if lowerMethod, ok := ascii.ToLower(method); ok {
545                 return method[:1] + lowerMethod[1:]
546         }
547         return method
548 }
549
550 // Do sends an HTTP request and returns an HTTP response, following
551 // policy (such as redirects, cookies, auth) as configured on the
552 // client.
553 //
554 // An error is returned if caused by client policy (such as
555 // CheckRedirect), or failure to speak HTTP (such as a network
556 // connectivity problem). A non-2xx status code doesn't cause an
557 // error.
558 //
559 // If the returned error is nil, the Response will contain a non-nil
560 // Body which the user is expected to close. If the Body is not both
561 // read to EOF and closed, the Client's underlying RoundTripper
562 // (typically Transport) may not be able to re-use a persistent TCP
563 // connection to the server for a subsequent "keep-alive" request.
564 //
565 // The request Body, if non-nil, will be closed by the underlying
566 // Transport, even on errors.
567 //
568 // On error, any Response can be ignored. A non-nil Response with a
569 // non-nil error only occurs when CheckRedirect fails, and even then
570 // the returned Response.Body is already closed.
571 //
572 // Generally Get, Post, or PostForm will be used instead of Do.
573 //
574 // If the server replies with a redirect, the Client first uses the
575 // CheckRedirect function to determine whether the redirect should be
576 // followed. If permitted, a 301, 302, or 303 redirect causes
577 // subsequent requests to use HTTP method GET
578 // (or HEAD if the original request was HEAD), with no body.
579 // A 307 or 308 redirect preserves the original HTTP method and body,
580 // provided that the Request.GetBody function is defined.
581 // The NewRequest function automatically sets GetBody for common
582 // standard library body types.
583 //
584 // Any returned error will be of type *url.Error. The url.Error
585 // value's Timeout method will report true if the request timed out.
586 func (c *Client) Do(req *Request) (*Response, error) {
587         return c.do(req)
588 }
589
590 var testHookClientDoResult func(retres *Response, reterr error)
591
592 func (c *Client) do(req *Request) (retres *Response, reterr error) {
593         if testHookClientDoResult != nil {
594                 defer func() { testHookClientDoResult(retres, reterr) }()
595         }
596         if req.URL == nil {
597                 req.closeBody()
598                 return nil, &url.Error{
599                         Op:  urlErrorOp(req.Method),
600                         Err: errors.New("http: nil Request.URL"),
601                 }
602         }
603
604         var (
605                 deadline      = c.deadline()
606                 reqs          []*Request
607                 resp          *Response
608                 copyHeaders   = c.makeHeadersCopier(req)
609                 reqBodyClosed = false // have we closed the current req.Body?
610
611                 // Redirect behavior:
612                 redirectMethod string
613                 includeBody    bool
614         )
615         uerr := func(err error) error {
616                 // the body may have been closed already by c.send()
617                 if !reqBodyClosed {
618                         req.closeBody()
619                 }
620                 var urlStr string
621                 if resp != nil && resp.Request != nil {
622                         urlStr = stripPassword(resp.Request.URL)
623                 } else {
624                         urlStr = stripPassword(req.URL)
625                 }
626                 return &url.Error{
627                         Op:  urlErrorOp(reqs[0].Method),
628                         URL: urlStr,
629                         Err: err,
630                 }
631         }
632         for {
633                 // For all but the first request, create the next
634                 // request hop and replace req.
635                 if len(reqs) > 0 {
636                         loc := resp.Header.Get("Location")
637                         if loc == "" {
638                                 // While most 3xx responses include a Location, it is not
639                                 // required and 3xx responses without a Location have been
640                                 // observed in the wild. See issues #17773 and #49281.
641                                 return resp, nil
642                         }
643                         u, err := req.URL.Parse(loc)
644                         if err != nil {
645                                 resp.closeBody()
646                                 return nil, uerr(fmt.Errorf("failed to parse Location header %q: %v", loc, err))
647                         }
648                         host := ""
649                         if req.Host != "" && req.Host != req.URL.Host {
650                                 // If the caller specified a custom Host header and the
651                                 // redirect location is relative, preserve the Host header
652                                 // through the redirect. See issue #22233.
653                                 if u, _ := url.Parse(loc); u != nil && !u.IsAbs() {
654                                         host = req.Host
655                                 }
656                         }
657                         ireq := reqs[0]
658                         req = &Request{
659                                 Method:   redirectMethod,
660                                 Response: resp,
661                                 URL:      u,
662                                 Header:   make(Header),
663                                 Host:     host,
664                                 Cancel:   ireq.Cancel,
665                                 ctx:      ireq.ctx,
666                         }
667                         if includeBody && ireq.GetBody != nil {
668                                 req.Body, err = ireq.GetBody()
669                                 if err != nil {
670                                         resp.closeBody()
671                                         return nil, uerr(err)
672                                 }
673                                 req.ContentLength = ireq.ContentLength
674                         }
675
676                         // Copy original headers before setting the Referer,
677                         // in case the user set Referer on their first request.
678                         // If they really want to override, they can do it in
679                         // their CheckRedirect func.
680                         copyHeaders(req)
681
682                         // Add the Referer header from the most recent
683                         // request URL to the new one, if it's not https->http:
684                         if ref := refererForURL(reqs[len(reqs)-1].URL, req.URL, req.Header.Get("Referer")); ref != "" {
685                                 req.Header.Set("Referer", ref)
686                         }
687                         err = c.checkRedirect(req, reqs)
688
689                         // Sentinel error to let users select the
690                         // previous response, without closing its
691                         // body. See Issue 10069.
692                         if err == ErrUseLastResponse {
693                                 return resp, nil
694                         }
695
696                         // Close the previous response's body. But
697                         // read at least some of the body so if it's
698                         // small the underlying TCP connection will be
699                         // re-used. No need to check for errors: if it
700                         // fails, the Transport won't reuse it anyway.
701                         const maxBodySlurpSize = 2 << 10
702                         if resp.ContentLength == -1 || resp.ContentLength <= maxBodySlurpSize {
703                                 io.CopyN(io.Discard, resp.Body, maxBodySlurpSize)
704                         }
705                         resp.Body.Close()
706
707                         if err != nil {
708                                 // Special case for Go 1 compatibility: return both the response
709                                 // and an error if the CheckRedirect function failed.
710                                 // See https://golang.org/issue/3795
711                                 // The resp.Body has already been closed.
712                                 ue := uerr(err)
713                                 ue.(*url.Error).URL = loc
714                                 return resp, ue
715                         }
716                 }
717
718                 reqs = append(reqs, req)
719                 var err error
720                 var didTimeout func() bool
721                 if resp, didTimeout, err = c.send(req, deadline); err != nil {
722                         // c.send() always closes req.Body
723                         reqBodyClosed = true
724                         if !deadline.IsZero() && didTimeout() {
725                                 err = &httpError{
726                                         err:     err.Error() + " (Client.Timeout exceeded while awaiting headers)",
727                                         timeout: true,
728                                 }
729                         }
730                         return nil, uerr(err)
731                 }
732
733                 var shouldRedirect bool
734                 redirectMethod, shouldRedirect, includeBody = redirectBehavior(req.Method, resp, reqs[0])
735                 if !shouldRedirect {
736                         return resp, nil
737                 }
738
739                 req.closeBody()
740         }
741 }
742
743 // makeHeadersCopier makes a function that copies headers from the
744 // initial Request, ireq. For every redirect, this function must be called
745 // so that it can copy headers into the upcoming Request.
746 func (c *Client) makeHeadersCopier(ireq *Request) func(*Request) {
747         // The headers to copy are from the very initial request.
748         // We use a closured callback to keep a reference to these original headers.
749         var (
750                 ireqhdr  = cloneOrMakeHeader(ireq.Header)
751                 icookies map[string][]*Cookie
752         )
753         if c.Jar != nil && ireq.Header.Get("Cookie") != "" {
754                 icookies = make(map[string][]*Cookie)
755                 for _, c := range ireq.Cookies() {
756                         icookies[c.Name] = append(icookies[c.Name], c)
757                 }
758         }
759
760         preq := ireq // The previous request
761         return func(req *Request) {
762                 // If Jar is present and there was some initial cookies provided
763                 // via the request header, then we may need to alter the initial
764                 // cookies as we follow redirects since each redirect may end up
765                 // modifying a pre-existing cookie.
766                 //
767                 // Since cookies already set in the request header do not contain
768                 // information about the original domain and path, the logic below
769                 // assumes any new set cookies override the original cookie
770                 // regardless of domain or path.
771                 //
772                 // See https://golang.org/issue/17494
773                 if c.Jar != nil && icookies != nil {
774                         var changed bool
775                         resp := req.Response // The response that caused the upcoming redirect
776                         for _, c := range resp.Cookies() {
777                                 if _, ok := icookies[c.Name]; ok {
778                                         delete(icookies, c.Name)
779                                         changed = true
780                                 }
781                         }
782                         if changed {
783                                 ireqhdr.Del("Cookie")
784                                 var ss []string
785                                 for _, cs := range icookies {
786                                         for _, c := range cs {
787                                                 ss = append(ss, c.Name+"="+c.Value)
788                                         }
789                                 }
790                                 sort.Strings(ss) // Ensure deterministic headers
791                                 ireqhdr.Set("Cookie", strings.Join(ss, "; "))
792                         }
793                 }
794
795                 // Copy the initial request's Header values
796                 // (at least the safe ones).
797                 for k, vv := range ireqhdr {
798                         if shouldCopyHeaderOnRedirect(k, preq.URL, req.URL) {
799                                 req.Header[k] = vv
800                         }
801                 }
802
803                 preq = req // Update previous Request with the current request
804         }
805 }
806
807 func defaultCheckRedirect(req *Request, via []*Request) error {
808         if len(via) >= 10 {
809                 return errors.New("stopped after 10 redirects")
810         }
811         return nil
812 }
813
814 // Post issues a POST to the specified URL.
815 //
816 // Caller should close resp.Body when done reading from it.
817 //
818 // If the provided body is an io.Closer, it is closed after the
819 // request.
820 //
821 // Post is a wrapper around DefaultClient.Post.
822 //
823 // To set custom headers, use NewRequest and DefaultClient.Do.
824 //
825 // See the Client.Do method documentation for details on how redirects
826 // are handled.
827 //
828 // To make a request with a specified context.Context, use NewRequestWithContext
829 // and DefaultClient.Do.
830 func Post(url, contentType string, body io.Reader) (resp *Response, err error) {
831         return DefaultClient.Post(url, contentType, body)
832 }
833
834 // Post issues a POST to the specified URL.
835 //
836 // Caller should close resp.Body when done reading from it.
837 //
838 // If the provided body is an io.Closer, it is closed after the
839 // request.
840 //
841 // To set custom headers, use NewRequest and Client.Do.
842 //
843 // To make a request with a specified context.Context, use NewRequestWithContext
844 // and Client.Do.
845 //
846 // See the Client.Do method documentation for details on how redirects
847 // are handled.
848 func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error) {
849         req, err := NewRequest("POST", url, body)
850         if err != nil {
851                 return nil, err
852         }
853         req.Header.Set("Content-Type", contentType)
854         return c.Do(req)
855 }
856
857 // PostForm issues a POST to the specified URL, with data's keys and
858 // values URL-encoded as the request body.
859 //
860 // The Content-Type header is set to application/x-www-form-urlencoded.
861 // To set other headers, use NewRequest and DefaultClient.Do.
862 //
863 // When err is nil, resp always contains a non-nil resp.Body.
864 // Caller should close resp.Body when done reading from it.
865 //
866 // PostForm is a wrapper around DefaultClient.PostForm.
867 //
868 // See the Client.Do method documentation for details on how redirects
869 // are handled.
870 //
871 // To make a request with a specified context.Context, use NewRequestWithContext
872 // and DefaultClient.Do.
873 func PostForm(url string, data url.Values) (resp *Response, err error) {
874         return DefaultClient.PostForm(url, data)
875 }
876
877 // PostForm issues a POST to the specified URL,
878 // with data's keys and values URL-encoded as the request body.
879 //
880 // The Content-Type header is set to application/x-www-form-urlencoded.
881 // To set other headers, use NewRequest and Client.Do.
882 //
883 // When err is nil, resp always contains a non-nil resp.Body.
884 // Caller should close resp.Body when done reading from it.
885 //
886 // See the Client.Do method documentation for details on how redirects
887 // are handled.
888 //
889 // To make a request with a specified context.Context, use NewRequestWithContext
890 // and Client.Do.
891 func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error) {
892         return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
893 }
894
895 // Head issues a HEAD to the specified URL. If the response is one of
896 // the following redirect codes, Head follows the redirect, up to a
897 // maximum of 10 redirects:
898 //
899 //      301 (Moved Permanently)
900 //      302 (Found)
901 //      303 (See Other)
902 //      307 (Temporary Redirect)
903 //      308 (Permanent Redirect)
904 //
905 // Head is a wrapper around DefaultClient.Head.
906 //
907 // To make a request with a specified context.Context, use NewRequestWithContext
908 // and DefaultClient.Do.
909 func Head(url string) (resp *Response, err error) {
910         return DefaultClient.Head(url)
911 }
912
913 // Head issues a HEAD to the specified URL. If the response is one of the
914 // following redirect codes, Head follows the redirect after calling the
915 // Client's CheckRedirect function:
916 //
917 //      301 (Moved Permanently)
918 //      302 (Found)
919 //      303 (See Other)
920 //      307 (Temporary Redirect)
921 //      308 (Permanent Redirect)
922 //
923 // To make a request with a specified context.Context, use NewRequestWithContext
924 // and Client.Do.
925 func (c *Client) Head(url string) (resp *Response, err error) {
926         req, err := NewRequest("HEAD", url, nil)
927         if err != nil {
928                 return nil, err
929         }
930         return c.Do(req)
931 }
932
933 // CloseIdleConnections closes any connections on its Transport which
934 // were previously connected from previous requests but are now
935 // sitting idle in a "keep-alive" state. It does not interrupt any
936 // connections currently in use.
937 //
938 // If the Client's Transport does not have a CloseIdleConnections method
939 // then this method does nothing.
940 func (c *Client) CloseIdleConnections() {
941         type closeIdler interface {
942                 CloseIdleConnections()
943         }
944         if tr, ok := c.transport().(closeIdler); ok {
945                 tr.CloseIdleConnections()
946         }
947 }
948
949 // cancelTimerBody is an io.ReadCloser that wraps rc with two features:
950 //  1. On Read error or close, the stop func is called.
951 //  2. On Read failure, if reqDidTimeout is true, the error is wrapped and
952 //     marked as net.Error that hit its timeout.
953 type cancelTimerBody struct {
954         stop          func() // stops the time.Timer waiting to cancel the request
955         rc            io.ReadCloser
956         reqDidTimeout func() bool
957 }
958
959 func (b *cancelTimerBody) Read(p []byte) (n int, err error) {
960         n, err = b.rc.Read(p)
961         if err == nil {
962                 return n, nil
963         }
964         if err == io.EOF {
965                 return n, err
966         }
967         if b.reqDidTimeout() {
968                 err = &httpError{
969                         err:     err.Error() + " (Client.Timeout or context cancellation while reading body)",
970                         timeout: true,
971                 }
972         }
973         return n, err
974 }
975
976 func (b *cancelTimerBody) Close() error {
977         err := b.rc.Close()
978         b.stop()
979         return err
980 }
981
982 func shouldCopyHeaderOnRedirect(headerKey string, initial, dest *url.URL) bool {
983         switch CanonicalHeaderKey(headerKey) {
984         case "Authorization", "Www-Authenticate", "Cookie", "Cookie2":
985                 // Permit sending auth/cookie headers from "foo.com"
986                 // to "sub.foo.com".
987
988                 // Note that we don't send all cookies to subdomains
989                 // automatically. This function is only used for
990                 // Cookies set explicitly on the initial outgoing
991                 // client request. Cookies automatically added via the
992                 // CookieJar mechanism continue to follow each
993                 // cookie's scope as set by Set-Cookie. But for
994                 // outgoing requests with the Cookie header set
995                 // directly, we don't know their scope, so we assume
996                 // it's for *.domain.com.
997
998                 ihost := idnaASCIIFromURL(initial)
999                 dhost := idnaASCIIFromURL(dest)
1000                 return isDomainOrSubdomain(dhost, ihost)
1001         }
1002         // All other headers are copied:
1003         return true
1004 }
1005
1006 // isDomainOrSubdomain reports whether sub is a subdomain (or exact
1007 // match) of the parent domain.
1008 //
1009 // Both domains must already be in canonical form.
1010 func isDomainOrSubdomain(sub, parent string) bool {
1011         if sub == parent {
1012                 return true
1013         }
1014         // If sub is "foo.example.com" and parent is "example.com",
1015         // that means sub must end in "."+parent.
1016         // Do it without allocating.
1017         if !strings.HasSuffix(sub, parent) {
1018                 return false
1019         }
1020         return sub[len(sub)-len(parent)-1] == '.'
1021 }
1022
1023 func stripPassword(u *url.URL) string {
1024         _, passSet := u.User.Password()
1025         if passSet {
1026                 return strings.Replace(u.String(), u.User.String()+"@", u.User.Username()+":***@", 1)
1027         }
1028         return u.String()
1029 }