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

View as plain text