Source file src/net/http/client.go

Documentation: net/http

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

View as plain text