Source file src/net/http/transport.go

Documentation: net/http

     1  // Copyright 2011 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 implementation. See RFC 7230 through 7235.
     6  //
     7  // This is the low-level Transport implementation of RoundTripper.
     8  // The high-level interface is in client.go.
     9  
    10  package http
    11  
    12  import (
    13  	"bufio"
    14  	"compress/gzip"
    15  	"container/list"
    16  	"context"
    17  	"crypto/tls"
    18  	"errors"
    19  	"fmt"
    20  	"io"
    21  	"log"
    22  	"net"
    23  	"net/http/httptrace"
    24  	"net/textproto"
    25  	"net/url"
    26  	"os"
    27  	"reflect"
    28  	"strings"
    29  	"sync"
    30  	"sync/atomic"
    31  	"time"
    32  
    33  	"golang.org/x/net/http/httpguts"
    34  	"golang.org/x/net/http/httpproxy"
    35  )
    36  
    37  // DefaultTransport is the default implementation of Transport and is
    38  // used by DefaultClient. It establishes network connections as needed
    39  // and caches them for reuse by subsequent calls. It uses HTTP proxies
    40  // as directed by the $HTTP_PROXY and $NO_PROXY (or $http_proxy and
    41  // $no_proxy) environment variables.
    42  var DefaultTransport RoundTripper = &Transport{
    43  	Proxy: ProxyFromEnvironment,
    44  	DialContext: (&net.Dialer{
    45  		Timeout:   30 * time.Second,
    46  		KeepAlive: 30 * time.Second,
    47  		DualStack: true,
    48  	}).DialContext,
    49  	ForceAttemptHTTP2:     true,
    50  	MaxIdleConns:          100,
    51  	IdleConnTimeout:       90 * time.Second,
    52  	TLSHandshakeTimeout:   10 * time.Second,
    53  	ExpectContinueTimeout: 1 * time.Second,
    54  }
    55  
    56  // DefaultMaxIdleConnsPerHost is the default value of Transport's
    57  // MaxIdleConnsPerHost.
    58  const DefaultMaxIdleConnsPerHost = 2
    59  
    60  // Transport is an implementation of RoundTripper that supports HTTP,
    61  // HTTPS, and HTTP proxies (for either HTTP or HTTPS with CONNECT).
    62  //
    63  // By default, Transport caches connections for future re-use.
    64  // This may leave many open connections when accessing many hosts.
    65  // This behavior can be managed using Transport's CloseIdleConnections method
    66  // and the MaxIdleConnsPerHost and DisableKeepAlives fields.
    67  //
    68  // Transports should be reused instead of created as needed.
    69  // Transports are safe for concurrent use by multiple goroutines.
    70  //
    71  // A Transport is a low-level primitive for making HTTP and HTTPS requests.
    72  // For high-level functionality, such as cookies and redirects, see Client.
    73  //
    74  // Transport uses HTTP/1.1 for HTTP URLs and either HTTP/1.1 or HTTP/2
    75  // for HTTPS URLs, depending on whether the server supports HTTP/2,
    76  // and how the Transport is configured. The DefaultTransport supports HTTP/2.
    77  // To explicitly enable HTTP/2 on a transport, use golang.org/x/net/http2
    78  // and call ConfigureTransport. See the package docs for more about HTTP/2.
    79  //
    80  // Responses with status codes in the 1xx range are either handled
    81  // automatically (100 expect-continue) or ignored. The one
    82  // exception is HTTP status code 101 (Switching Protocols), which is
    83  // considered a terminal status and returned by RoundTrip. To see the
    84  // ignored 1xx responses, use the httptrace trace package's
    85  // ClientTrace.Got1xxResponse.
    86  //
    87  // Transport only retries a request upon encountering a network error
    88  // if the request is idempotent and either has no body or has its
    89  // Request.GetBody defined. HTTP requests are considered idempotent if
    90  // they have HTTP methods GET, HEAD, OPTIONS, or TRACE; or if their
    91  // Header map contains an "Idempotency-Key" or "X-Idempotency-Key"
    92  // entry. If the idempotency key value is a zero-length slice, the
    93  // request is treated as idempotent but the header is not sent on the
    94  // wire.
    95  type Transport struct {
    96  	idleMu       sync.Mutex
    97  	closeIdle    bool                                // user has requested to close all idle conns
    98  	idleConn     map[connectMethodKey][]*persistConn // most recently used at end
    99  	idleConnWait map[connectMethodKey]wantConnQueue  // waiting getConns
   100  	idleLRU      connLRU
   101  
   102  	reqMu       sync.Mutex
   103  	reqCanceler map[*Request]func(error)
   104  
   105  	altMu    sync.Mutex   // guards changing altProto only
   106  	altProto atomic.Value // of nil or map[string]RoundTripper, key is URI scheme
   107  
   108  	connsPerHostMu   sync.Mutex
   109  	connsPerHost     map[connectMethodKey]int
   110  	connsPerHostWait map[connectMethodKey]wantConnQueue // waiting getConns
   111  
   112  	// Proxy specifies a function to return a proxy for a given
   113  	// Request. If the function returns a non-nil error, the
   114  	// request is aborted with the provided error.
   115  	//
   116  	// The proxy type is determined by the URL scheme. "http",
   117  	// "https", and "socks5" are supported. If the scheme is empty,
   118  	// "http" is assumed.
   119  	//
   120  	// If Proxy is nil or returns a nil *URL, no proxy is used.
   121  	Proxy func(*Request) (*url.URL, error)
   122  
   123  	// DialContext specifies the dial function for creating unencrypted TCP connections.
   124  	// If DialContext is nil (and the deprecated Dial below is also nil),
   125  	// then the transport dials using package net.
   126  	//
   127  	// DialContext runs concurrently with calls to RoundTrip.
   128  	// A RoundTrip call that initiates a dial may end up using
   129  	// a connection dialed previously when the earlier connection
   130  	// becomes idle before the later DialContext completes.
   131  	DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
   132  
   133  	// Dial specifies the dial function for creating unencrypted TCP connections.
   134  	//
   135  	// Dial runs concurrently with calls to RoundTrip.
   136  	// A RoundTrip call that initiates a dial may end up using
   137  	// a connection dialed previously when the earlier connection
   138  	// becomes idle before the later Dial completes.
   139  	//
   140  	// Deprecated: Use DialContext instead, which allows the transport
   141  	// to cancel dials as soon as they are no longer needed.
   142  	// If both are set, DialContext takes priority.
   143  	Dial func(network, addr string) (net.Conn, error)
   144  
   145  	// DialTLSContext specifies an optional dial function for creating
   146  	// TLS connections for non-proxied HTTPS requests.
   147  	//
   148  	// If DialTLSContext is nil (and the deprecated DialTLS below is also nil),
   149  	// DialContext and TLSClientConfig are used.
   150  	//
   151  	// If DialTLSContext is set, the Dial and DialContext hooks are not used for HTTPS
   152  	// requests and the TLSClientConfig and TLSHandshakeTimeout
   153  	// are ignored. The returned net.Conn is assumed to already be
   154  	// past the TLS handshake.
   155  	DialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error)
   156  
   157  	// DialTLS specifies an optional dial function for creating
   158  	// TLS connections for non-proxied HTTPS requests.
   159  	//
   160  	// Deprecated: Use DialTLSContext instead, which allows the transport
   161  	// to cancel dials as soon as they are no longer needed.
   162  	// If both are set, DialTLSContext takes priority.
   163  	DialTLS func(network, addr string) (net.Conn, error)
   164  
   165  	// TLSClientConfig specifies the TLS configuration to use with
   166  	// tls.Client.
   167  	// If nil, the default configuration is used.
   168  	// If non-nil, HTTP/2 support may not be enabled by default.
   169  	TLSClientConfig *tls.Config
   170  
   171  	// TLSHandshakeTimeout specifies the maximum amount of time waiting to
   172  	// wait for a TLS handshake. Zero means no timeout.
   173  	TLSHandshakeTimeout time.Duration
   174  
   175  	// DisableKeepAlives, if true, disables HTTP keep-alives and
   176  	// will only use the connection to the server for a single
   177  	// HTTP request.
   178  	//
   179  	// This is unrelated to the similarly named TCP keep-alives.
   180  	DisableKeepAlives bool
   181  
   182  	// DisableCompression, if true, prevents the Transport from
   183  	// requesting compression with an "Accept-Encoding: gzip"
   184  	// request header when the Request contains no existing
   185  	// Accept-Encoding value. If the Transport requests gzip on
   186  	// its own and gets a gzipped response, it's transparently
   187  	// decoded in the Response.Body. However, if the user
   188  	// explicitly requested gzip it is not automatically
   189  	// uncompressed.
   190  	DisableCompression bool
   191  
   192  	// MaxIdleConns controls the maximum number of idle (keep-alive)
   193  	// connections across all hosts. Zero means no limit.
   194  	MaxIdleConns int
   195  
   196  	// MaxIdleConnsPerHost, if non-zero, controls the maximum idle
   197  	// (keep-alive) connections to keep per-host. If zero,
   198  	// DefaultMaxIdleConnsPerHost is used.
   199  	MaxIdleConnsPerHost int
   200  
   201  	// MaxConnsPerHost optionally limits the total number of
   202  	// connections per host, including connections in the dialing,
   203  	// active, and idle states. On limit violation, dials will block.
   204  	//
   205  	// Zero means no limit.
   206  	MaxConnsPerHost int
   207  
   208  	// IdleConnTimeout is the maximum amount of time an idle
   209  	// (keep-alive) connection will remain idle before closing
   210  	// itself.
   211  	// Zero means no limit.
   212  	IdleConnTimeout time.Duration
   213  
   214  	// ResponseHeaderTimeout, if non-zero, specifies the amount of
   215  	// time to wait for a server's response headers after fully
   216  	// writing the request (including its body, if any). This
   217  	// time does not include the time to read the response body.
   218  	ResponseHeaderTimeout time.Duration
   219  
   220  	// ExpectContinueTimeout, if non-zero, specifies the amount of
   221  	// time to wait for a server's first response headers after fully
   222  	// writing the request headers if the request has an
   223  	// "Expect: 100-continue" header. Zero means no timeout and
   224  	// causes the body to be sent immediately, without
   225  	// waiting for the server to approve.
   226  	// This time does not include the time to send the request header.
   227  	ExpectContinueTimeout time.Duration
   228  
   229  	// TLSNextProto specifies how the Transport switches to an
   230  	// alternate protocol (such as HTTP/2) after a TLS ALPN
   231  	// protocol negotiation. If Transport dials an TLS connection
   232  	// with a non-empty protocol name and TLSNextProto contains a
   233  	// map entry for that key (such as "h2"), then the func is
   234  	// called with the request's authority (such as "example.com"
   235  	// or "example.com:1234") and the TLS connection. The function
   236  	// must return a RoundTripper that then handles the request.
   237  	// If TLSNextProto is not nil, HTTP/2 support is not enabled
   238  	// automatically.
   239  	TLSNextProto map[string]func(authority string, c *tls.Conn) RoundTripper
   240  
   241  	// ProxyConnectHeader optionally specifies headers to send to
   242  	// proxies during CONNECT requests.
   243  	ProxyConnectHeader Header
   244  
   245  	// MaxResponseHeaderBytes specifies a limit on how many
   246  	// response bytes are allowed in the server's response
   247  	// header.
   248  	//
   249  	// Zero means to use a default limit.
   250  	MaxResponseHeaderBytes int64
   251  
   252  	// WriteBufferSize specifies the size of the write buffer used
   253  	// when writing to the transport.
   254  	// If zero, a default (currently 4KB) is used.
   255  	WriteBufferSize int
   256  
   257  	// ReadBufferSize specifies the size of the read buffer used
   258  	// when reading from the transport.
   259  	// If zero, a default (currently 4KB) is used.
   260  	ReadBufferSize int
   261  
   262  	// nextProtoOnce guards initialization of TLSNextProto and
   263  	// h2transport (via onceSetNextProtoDefaults)
   264  	nextProtoOnce      sync.Once
   265  	h2transport        h2Transport // non-nil if http2 wired up
   266  	tlsNextProtoWasNil bool        // whether TLSNextProto was nil when the Once fired
   267  
   268  	// ForceAttemptHTTP2 controls whether HTTP/2 is enabled when a non-zero
   269  	// Dial, DialTLS, or DialContext func or TLSClientConfig is provided.
   270  	// By default, use of any those fields conservatively disables HTTP/2.
   271  	// To use a custom dialer or TLS config and still attempt HTTP/2
   272  	// upgrades, set this to true.
   273  	ForceAttemptHTTP2 bool
   274  }
   275  
   276  func (t *Transport) writeBufferSize() int {
   277  	if t.WriteBufferSize > 0 {
   278  		return t.WriteBufferSize
   279  	}
   280  	return 4 << 10
   281  }
   282  
   283  func (t *Transport) readBufferSize() int {
   284  	if t.ReadBufferSize > 0 {
   285  		return t.ReadBufferSize
   286  	}
   287  	return 4 << 10
   288  }
   289  
   290  // Clone returns a deep copy of t's exported fields.
   291  func (t *Transport) Clone() *Transport {
   292  	t.nextProtoOnce.Do(t.onceSetNextProtoDefaults)
   293  	t2 := &Transport{
   294  		Proxy:                  t.Proxy,
   295  		DialContext:            t.DialContext,
   296  		Dial:                   t.Dial,
   297  		DialTLS:                t.DialTLS,
   298  		DialTLSContext:         t.DialTLSContext,
   299  		TLSHandshakeTimeout:    t.TLSHandshakeTimeout,
   300  		DisableKeepAlives:      t.DisableKeepAlives,
   301  		DisableCompression:     t.DisableCompression,
   302  		MaxIdleConns:           t.MaxIdleConns,
   303  		MaxIdleConnsPerHost:    t.MaxIdleConnsPerHost,
   304  		MaxConnsPerHost:        t.MaxConnsPerHost,
   305  		IdleConnTimeout:        t.IdleConnTimeout,
   306  		ResponseHeaderTimeout:  t.ResponseHeaderTimeout,
   307  		ExpectContinueTimeout:  t.ExpectContinueTimeout,
   308  		ProxyConnectHeader:     t.ProxyConnectHeader.Clone(),
   309  		MaxResponseHeaderBytes: t.MaxResponseHeaderBytes,
   310  		ForceAttemptHTTP2:      t.ForceAttemptHTTP2,
   311  		WriteBufferSize:        t.WriteBufferSize,
   312  		ReadBufferSize:         t.ReadBufferSize,
   313  	}
   314  	if t.TLSClientConfig != nil {
   315  		t2.TLSClientConfig = t.TLSClientConfig.Clone()
   316  	}
   317  	if !t.tlsNextProtoWasNil {
   318  		npm := map[string]func(authority string, c *tls.Conn) RoundTripper{}
   319  		for k, v := range t.TLSNextProto {
   320  			npm[k] = v
   321  		}
   322  		t2.TLSNextProto = npm
   323  	}
   324  	return t2
   325  }
   326  
   327  // h2Transport is the interface we expect to be able to call from
   328  // net/http against an *http2.Transport that's either bundled into
   329  // h2_bundle.go or supplied by the user via x/net/http2.
   330  //
   331  // We name it with the "h2" prefix to stay out of the "http2" prefix
   332  // namespace used by x/tools/cmd/bundle for h2_bundle.go.
   333  type h2Transport interface {
   334  	CloseIdleConnections()
   335  }
   336  
   337  func (t *Transport) hasCustomTLSDialer() bool {
   338  	return t.DialTLS != nil || t.DialTLSContext != nil
   339  }
   340  
   341  // onceSetNextProtoDefaults initializes TLSNextProto.
   342  // It must be called via t.nextProtoOnce.Do.
   343  func (t *Transport) onceSetNextProtoDefaults() {
   344  	t.tlsNextProtoWasNil = (t.TLSNextProto == nil)
   345  	if strings.Contains(os.Getenv("GODEBUG"), "http2client=0") {
   346  		return
   347  	}
   348  
   349  	// If they've already configured http2 with
   350  	// golang.org/x/net/http2 instead of the bundled copy, try to
   351  	// get at its http2.Transport value (via the "https"
   352  	// altproto map) so we can call CloseIdleConnections on it if
   353  	// requested. (Issue 22891)
   354  	altProto, _ := t.altProto.Load().(map[string]RoundTripper)
   355  	if rv := reflect.ValueOf(altProto["https"]); rv.IsValid() && rv.Type().Kind() == reflect.Struct && rv.Type().NumField() == 1 {
   356  		if v := rv.Field(0); v.CanInterface() {
   357  			if h2i, ok := v.Interface().(h2Transport); ok {
   358  				t.h2transport = h2i
   359  				return
   360  			}
   361  		}
   362  	}
   363  
   364  	if t.TLSNextProto != nil {
   365  		// This is the documented way to disable http2 on a
   366  		// Transport.
   367  		return
   368  	}
   369  	if !t.ForceAttemptHTTP2 && (t.TLSClientConfig != nil || t.Dial != nil || t.DialContext != nil || t.hasCustomTLSDialer()) {
   370  		// Be conservative and don't automatically enable
   371  		// http2 if they've specified a custom TLS config or
   372  		// custom dialers. Let them opt-in themselves via
   373  		// http2.ConfigureTransport so we don't surprise them
   374  		// by modifying their tls.Config. Issue 14275.
   375  		// However, if ForceAttemptHTTP2 is true, it overrides the above checks.
   376  		return
   377  	}
   378  	if omitBundledHTTP2 {
   379  		return
   380  	}
   381  	t2, err := http2configureTransport(t)
   382  	if err != nil {
   383  		log.Printf("Error enabling Transport HTTP/2 support: %v", err)
   384  		return
   385  	}
   386  	t.h2transport = t2
   387  
   388  	// Auto-configure the http2.Transport's MaxHeaderListSize from
   389  	// the http.Transport's MaxResponseHeaderBytes. They don't
   390  	// exactly mean the same thing, but they're close.
   391  	//
   392  	// TODO: also add this to x/net/http2.Configure Transport, behind
   393  	// a +build go1.7 build tag:
   394  	if limit1 := t.MaxResponseHeaderBytes; limit1 != 0 && t2.MaxHeaderListSize == 0 {
   395  		const h2max = 1<<32 - 1
   396  		if limit1 >= h2max {
   397  			t2.MaxHeaderListSize = h2max
   398  		} else {
   399  			t2.MaxHeaderListSize = uint32(limit1)
   400  		}
   401  	}
   402  }
   403  
   404  // ProxyFromEnvironment returns the URL of the proxy to use for a
   405  // given request, as indicated by the environment variables
   406  // HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions
   407  // thereof). HTTPS_PROXY takes precedence over HTTP_PROXY for https
   408  // requests.
   409  //
   410  // The environment values may be either a complete URL or a
   411  // "host[:port]", in which case the "http" scheme is assumed.
   412  // An error is returned if the value is a different form.
   413  //
   414  // A nil URL and nil error are returned if no proxy is defined in the
   415  // environment, or a proxy should not be used for the given request,
   416  // as defined by NO_PROXY.
   417  //
   418  // As a special case, if req.URL.Host is "localhost" (with or without
   419  // a port number), then a nil URL and nil error will be returned.
   420  func ProxyFromEnvironment(req *Request) (*url.URL, error) {
   421  	return envProxyFunc()(req.URL)
   422  }
   423  
   424  // ProxyURL returns a proxy function (for use in a Transport)
   425  // that always returns the same URL.
   426  func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error) {
   427  	return func(*Request) (*url.URL, error) {
   428  		return fixedURL, nil
   429  	}
   430  }
   431  
   432  // transportRequest is a wrapper around a *Request that adds
   433  // optional extra headers to write and stores any error to return
   434  // from roundTrip.
   435  type transportRequest struct {
   436  	*Request                        // original request, not to be mutated
   437  	extra    Header                 // extra headers to write, or nil
   438  	trace    *httptrace.ClientTrace // optional
   439  
   440  	mu  sync.Mutex // guards err
   441  	err error      // first setError value for mapRoundTripError to consider
   442  }
   443  
   444  func (tr *transportRequest) extraHeaders() Header {
   445  	if tr.extra == nil {
   446  		tr.extra = make(Header)
   447  	}
   448  	return tr.extra
   449  }
   450  
   451  func (tr *transportRequest) setError(err error) {
   452  	tr.mu.Lock()
   453  	if tr.err == nil {
   454  		tr.err = err
   455  	}
   456  	tr.mu.Unlock()
   457  }
   458  
   459  // useRegisteredProtocol reports whether an alternate protocol (as registered
   460  // with Transport.RegisterProtocol) should be respected for this request.
   461  func (t *Transport) useRegisteredProtocol(req *Request) bool {
   462  	if req.URL.Scheme == "https" && req.requiresHTTP1() {
   463  		// If this request requires HTTP/1, don't use the
   464  		// "https" alternate protocol, which is used by the
   465  		// HTTP/2 code to take over requests if there's an
   466  		// existing cached HTTP/2 connection.
   467  		return false
   468  	}
   469  	return true
   470  }
   471  
   472  // alternateRoundTripper returns the alternate RoundTripper to use
   473  // for this request if the Request's URL scheme requires one,
   474  // or nil for the normal case of using the Transport.
   475  func (t *Transport) alternateRoundTripper(req *Request) RoundTripper {
   476  	if !t.useRegisteredProtocol(req) {
   477  		return nil
   478  	}
   479  	altProto, _ := t.altProto.Load().(map[string]RoundTripper)
   480  	return altProto[req.URL.Scheme]
   481  }
   482  
   483  // roundTrip implements a RoundTripper over HTTP.
   484  func (t *Transport) roundTrip(req *Request) (*Response, error) {
   485  	t.nextProtoOnce.Do(t.onceSetNextProtoDefaults)
   486  	ctx := req.Context()
   487  	trace := httptrace.ContextClientTrace(ctx)
   488  
   489  	if req.URL == nil {
   490  		req.closeBody()
   491  		return nil, errors.New("http: nil Request.URL")
   492  	}
   493  	if req.Header == nil {
   494  		req.closeBody()
   495  		return nil, errors.New("http: nil Request.Header")
   496  	}
   497  	scheme := req.URL.Scheme
   498  	isHTTP := scheme == "http" || scheme == "https"
   499  	if isHTTP {
   500  		for k, vv := range req.Header {
   501  			if !httpguts.ValidHeaderFieldName(k) {
   502  				req.closeBody()
   503  				return nil, fmt.Errorf("net/http: invalid header field name %q", k)
   504  			}
   505  			for _, v := range vv {
   506  				if !httpguts.ValidHeaderFieldValue(v) {
   507  					req.closeBody()
   508  					return nil, fmt.Errorf("net/http: invalid header field value %q for key %v", v, k)
   509  				}
   510  			}
   511  		}
   512  	}
   513  
   514  	if altRT := t.alternateRoundTripper(req); altRT != nil {
   515  		if resp, err := altRT.RoundTrip(req); err != ErrSkipAltProtocol {
   516  			return resp, err
   517  		}
   518  	}
   519  	if !isHTTP {
   520  		req.closeBody()
   521  		return nil, &badStringError{"unsupported protocol scheme", scheme}
   522  	}
   523  	if req.Method != "" && !validMethod(req.Method) {
   524  		req.closeBody()
   525  		return nil, fmt.Errorf("net/http: invalid method %q", req.Method)
   526  	}
   527  	if req.URL.Host == "" {
   528  		req.closeBody()
   529  		return nil, errors.New("http: no Host in request URL")
   530  	}
   531  
   532  	for {
   533  		select {
   534  		case <-ctx.Done():
   535  			req.closeBody()
   536  			return nil, ctx.Err()
   537  		default:
   538  		}
   539  
   540  		// treq gets modified by roundTrip, so we need to recreate for each retry.
   541  		treq := &transportRequest{Request: req, trace: trace}
   542  		cm, err := t.connectMethodForRequest(treq)
   543  		if err != nil {
   544  			req.closeBody()
   545  			return nil, err
   546  		}
   547  
   548  		// Get the cached or newly-created connection to either the
   549  		// host (for http or https), the http proxy, or the http proxy
   550  		// pre-CONNECTed to https server. In any case, we'll be ready
   551  		// to send it requests.
   552  		pconn, err := t.getConn(treq, cm)
   553  		if err != nil {
   554  			t.setReqCanceler(req, nil)
   555  			req.closeBody()
   556  			return nil, err
   557  		}
   558  
   559  		var resp *Response
   560  		if pconn.alt != nil {
   561  			// HTTP/2 path.
   562  			t.setReqCanceler(req, nil) // not cancelable with CancelRequest
   563  			resp, err = pconn.alt.RoundTrip(req)
   564  		} else {
   565  			resp, err = pconn.roundTrip(treq)
   566  		}
   567  		if err == nil {
   568  			return resp, nil
   569  		}
   570  
   571  		// Failed. Clean up and determine whether to retry.
   572  
   573  		_, isH2DialError := pconn.alt.(http2erringRoundTripper)
   574  		if http2isNoCachedConnError(err) || isH2DialError {
   575  			if t.removeIdleConn(pconn) {
   576  				t.decConnsPerHost(pconn.cacheKey)
   577  			}
   578  		}
   579  		if !pconn.shouldRetryRequest(req, err) {
   580  			// Issue 16465: return underlying net.Conn.Read error from peek,
   581  			// as we've historically done.
   582  			if e, ok := err.(transportReadFromServerError); ok {
   583  				err = e.err
   584  			}
   585  			return nil, err
   586  		}
   587  		testHookRoundTripRetried()
   588  
   589  		// Rewind the body if we're able to.
   590  		if req.GetBody != nil {
   591  			newReq := *req
   592  			var err error
   593  			newReq.Body, err = req.GetBody()
   594  			if err != nil {
   595  				return nil, err
   596  			}
   597  			req = &newReq
   598  		}
   599  	}
   600  }
   601  
   602  // shouldRetryRequest reports whether we should retry sending a failed
   603  // HTTP request on a new connection. The non-nil input error is the
   604  // error from roundTrip.
   605  func (pc *persistConn) shouldRetryRequest(req *Request, err error) bool {
   606  	if http2isNoCachedConnError(err) {
   607  		// Issue 16582: if the user started a bunch of
   608  		// requests at once, they can all pick the same conn
   609  		// and violate the server's max concurrent streams.
   610  		// Instead, match the HTTP/1 behavior for now and dial
   611  		// again to get a new TCP connection, rather than failing
   612  		// this request.
   613  		return true
   614  	}
   615  	if err == errMissingHost {
   616  		// User error.
   617  		return false
   618  	}
   619  	if !pc.isReused() {
   620  		// This was a fresh connection. There's no reason the server
   621  		// should've hung up on us.
   622  		//
   623  		// Also, if we retried now, we could loop forever
   624  		// creating new connections and retrying if the server
   625  		// is just hanging up on us because it doesn't like
   626  		// our request (as opposed to sending an error).
   627  		return false
   628  	}
   629  	if _, ok := err.(nothingWrittenError); ok {
   630  		// We never wrote anything, so it's safe to retry, if there's no body or we
   631  		// can "rewind" the body with GetBody.
   632  		return req.outgoingLength() == 0 || req.GetBody != nil
   633  	}
   634  	if !req.isReplayable() {
   635  		// Don't retry non-idempotent requests.
   636  		return false
   637  	}
   638  	if _, ok := err.(transportReadFromServerError); ok {
   639  		// We got some non-EOF net.Conn.Read failure reading
   640  		// the 1st response byte from the server.
   641  		return true
   642  	}
   643  	if err == errServerClosedIdle {
   644  		// The server replied with io.EOF while we were trying to
   645  		// read the response. Probably an unfortunately keep-alive
   646  		// timeout, just as the client was writing a request.
   647  		return true
   648  	}
   649  	return false // conservatively
   650  }
   651  
   652  // ErrSkipAltProtocol is a sentinel error value defined by Transport.RegisterProtocol.
   653  var ErrSkipAltProtocol = errors.New("net/http: skip alternate protocol")
   654  
   655  // RegisterProtocol registers a new protocol with scheme.
   656  // The Transport will pass requests using the given scheme to rt.
   657  // It is rt's responsibility to simulate HTTP request semantics.
   658  //
   659  // RegisterProtocol can be used by other packages to provide
   660  // implementations of protocol schemes like "ftp" or "file".
   661  //
   662  // If rt.RoundTrip returns ErrSkipAltProtocol, the Transport will
   663  // handle the RoundTrip itself for that one request, as if the
   664  // protocol were not registered.
   665  func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper) {
   666  	t.altMu.Lock()
   667  	defer t.altMu.Unlock()
   668  	oldMap, _ := t.altProto.Load().(map[string]RoundTripper)
   669  	if _, exists := oldMap[scheme]; exists {
   670  		panic("protocol " + scheme + " already registered")
   671  	}
   672  	newMap := make(map[string]RoundTripper)
   673  	for k, v := range oldMap {
   674  		newMap[k] = v
   675  	}
   676  	newMap[scheme] = rt
   677  	t.altProto.Store(newMap)
   678  }
   679  
   680  // CloseIdleConnections closes any connections which were previously
   681  // connected from previous requests but are now sitting idle in
   682  // a "keep-alive" state. It does not interrupt any connections currently
   683  // in use.
   684  func (t *Transport) CloseIdleConnections() {
   685  	t.nextProtoOnce.Do(t.onceSetNextProtoDefaults)
   686  	t.idleMu.Lock()
   687  	m := t.idleConn
   688  	t.idleConn = nil
   689  	t.closeIdle = true // close newly idle connections
   690  	t.idleLRU = connLRU{}
   691  	t.idleMu.Unlock()
   692  	for _, conns := range m {
   693  		for _, pconn := range conns {
   694  			pconn.close(errCloseIdleConns)
   695  		}
   696  	}
   697  	if t2 := t.h2transport; t2 != nil {
   698  		t2.CloseIdleConnections()
   699  	}
   700  }
   701  
   702  // CancelRequest cancels an in-flight request by closing its connection.
   703  // CancelRequest should only be called after RoundTrip has returned.
   704  //
   705  // Deprecated: Use Request.WithContext to create a request with a
   706  // cancelable context instead. CancelRequest cannot cancel HTTP/2
   707  // requests.
   708  func (t *Transport) CancelRequest(req *Request) {
   709  	t.cancelRequest(req, errRequestCanceled)
   710  }
   711  
   712  // Cancel an in-flight request, recording the error value.
   713  func (t *Transport) cancelRequest(req *Request, err error) {
   714  	t.reqMu.Lock()
   715  	cancel := t.reqCanceler[req]
   716  	delete(t.reqCanceler, req)
   717  	t.reqMu.Unlock()
   718  	if cancel != nil {
   719  		cancel(err)
   720  	}
   721  }
   722  
   723  //
   724  // Private implementation past this point.
   725  //
   726  
   727  var (
   728  	// proxyConfigOnce guards proxyConfig
   729  	envProxyOnce      sync.Once
   730  	envProxyFuncValue func(*url.URL) (*url.URL, error)
   731  )
   732  
   733  // defaultProxyConfig returns a ProxyConfig value looked up
   734  // from the environment. This mitigates expensive lookups
   735  // on some platforms (e.g. Windows).
   736  func envProxyFunc() func(*url.URL) (*url.URL, error) {
   737  	envProxyOnce.Do(func() {
   738  		envProxyFuncValue = httpproxy.FromEnvironment().ProxyFunc()
   739  	})
   740  	return envProxyFuncValue
   741  }
   742  
   743  // resetProxyConfig is used by tests.
   744  func resetProxyConfig() {
   745  	envProxyOnce = sync.Once{}
   746  	envProxyFuncValue = nil
   747  }
   748  
   749  func (t *Transport) connectMethodForRequest(treq *transportRequest) (cm connectMethod, err error) {
   750  	cm.targetScheme = treq.URL.Scheme
   751  	cm.targetAddr = canonicalAddr(treq.URL)
   752  	if t.Proxy != nil {
   753  		cm.proxyURL, err = t.Proxy(treq.Request)
   754  	}
   755  	cm.onlyH1 = treq.requiresHTTP1()
   756  	return cm, err
   757  }
   758  
   759  // proxyAuth returns the Proxy-Authorization header to set
   760  // on requests, if applicable.
   761  func (cm *connectMethod) proxyAuth() string {
   762  	if cm.proxyURL == nil {
   763  		return ""
   764  	}
   765  	if u := cm.proxyURL.User; u != nil {
   766  		username := u.Username()
   767  		password, _ := u.Password()
   768  		return "Basic " + basicAuth(username, password)
   769  	}
   770  	return ""
   771  }
   772  
   773  // error values for debugging and testing, not seen by users.
   774  var (
   775  	errKeepAlivesDisabled = errors.New("http: putIdleConn: keep alives disabled")
   776  	errConnBroken         = errors.New("http: putIdleConn: connection is in bad state")
   777  	errCloseIdle          = errors.New("http: putIdleConn: CloseIdleConnections was called")
   778  	errTooManyIdle        = errors.New("http: putIdleConn: too many idle connections")
   779  	errTooManyIdleHost    = errors.New("http: putIdleConn: too many idle connections for host")
   780  	errCloseIdleConns     = errors.New("http: CloseIdleConnections called")
   781  	errReadLoopExiting    = errors.New("http: persistConn.readLoop exiting")
   782  	errIdleConnTimeout    = errors.New("http: idle connection timeout")
   783  
   784  	// errServerClosedIdle is not seen by users for idempotent requests, but may be
   785  	// seen by a user if the server shuts down an idle connection and sends its FIN
   786  	// in flight with already-written POST body bytes from the client.
   787  	// See https://github.com/golang/go/issues/19943#issuecomment-355607646
   788  	errServerClosedIdle = errors.New("http: server closed idle connection")
   789  )
   790  
   791  // transportReadFromServerError is used by Transport.readLoop when the
   792  // 1 byte peek read fails and we're actually anticipating a response.
   793  // Usually this is just due to the inherent keep-alive shut down race,
   794  // where the server closed the connection at the same time the client
   795  // wrote. The underlying err field is usually io.EOF or some
   796  // ECONNRESET sort of thing which varies by platform. But it might be
   797  // the user's custom net.Conn.Read error too, so we carry it along for
   798  // them to return from Transport.RoundTrip.
   799  type transportReadFromServerError struct {
   800  	err error
   801  }
   802  
   803  func (e transportReadFromServerError) Unwrap() error { return e.err }
   804  
   805  func (e transportReadFromServerError) Error() string {
   806  	return fmt.Sprintf("net/http: Transport failed to read from server: %v", e.err)
   807  }
   808  
   809  func (t *Transport) putOrCloseIdleConn(pconn *persistConn) {
   810  	if err := t.tryPutIdleConn(pconn); err != nil {
   811  		pconn.close(err)
   812  	}
   813  }
   814  
   815  func (t *Transport) maxIdleConnsPerHost() int {
   816  	if v := t.MaxIdleConnsPerHost; v != 0 {
   817  		return v
   818  	}
   819  	return DefaultMaxIdleConnsPerHost
   820  }
   821  
   822  // tryPutIdleConn adds pconn to the list of idle persistent connections awaiting
   823  // a new request.
   824  // If pconn is no longer needed or not in a good state, tryPutIdleConn returns
   825  // an error explaining why it wasn't registered.
   826  // tryPutIdleConn does not close pconn. Use putOrCloseIdleConn instead for that.
   827  func (t *Transport) tryPutIdleConn(pconn *persistConn) error {
   828  	if t.DisableKeepAlives || t.MaxIdleConnsPerHost < 0 {
   829  		return errKeepAlivesDisabled
   830  	}
   831  	if pconn.isBroken() {
   832  		return errConnBroken
   833  	}
   834  	pconn.markReused()
   835  
   836  	t.idleMu.Lock()
   837  	defer t.idleMu.Unlock()
   838  
   839  	// HTTP/2 (pconn.alt != nil) connections do not come out of the idle list,
   840  	// because multiple goroutines can use them simultaneously.
   841  	// If this is an HTTP/2 connection being “returned,” we're done.
   842  	if pconn.alt != nil && t.idleLRU.m[pconn] != nil {
   843  		return nil
   844  	}
   845  
   846  	// Deliver pconn to goroutine waiting for idle connection, if any.
   847  	// (They may be actively dialing, but this conn is ready first.
   848  	// Chrome calls this socket late binding.
   849  	// See https://insouciant.org/tech/connection-management-in-chromium/.)
   850  	key := pconn.cacheKey
   851  	if q, ok := t.idleConnWait[key]; ok {
   852  		done := false
   853  		if pconn.alt == nil {
   854  			// HTTP/1.
   855  			// Loop over the waiting list until we find a w that isn't done already, and hand it pconn.
   856  			for q.len() > 0 {
   857  				w := q.popFront()
   858  				if w.tryDeliver(pconn, nil) {
   859  					done = true
   860  					break
   861  				}
   862  			}
   863  		} else {
   864  			// HTTP/2.
   865  			// Can hand the same pconn to everyone in the waiting list,
   866  			// and we still won't be done: we want to put it in the idle
   867  			// list unconditionally, for any future clients too.
   868  			for q.len() > 0 {
   869  				w := q.popFront()
   870  				w.tryDeliver(pconn, nil)
   871  			}
   872  		}
   873  		if q.len() == 0 {
   874  			delete(t.idleConnWait, key)
   875  		} else {
   876  			t.idleConnWait[key] = q
   877  		}
   878  		if done {
   879  			return nil
   880  		}
   881  	}
   882  
   883  	if t.closeIdle {
   884  		return errCloseIdle
   885  	}
   886  	if t.idleConn == nil {
   887  		t.idleConn = make(map[connectMethodKey][]*persistConn)
   888  	}
   889  	idles := t.idleConn[key]
   890  	if len(idles) >= t.maxIdleConnsPerHost() {
   891  		return errTooManyIdleHost
   892  	}
   893  	for _, exist := range idles {
   894  		if exist == pconn {
   895  			log.Fatalf("dup idle pconn %p in freelist", pconn)
   896  		}
   897  	}
   898  	t.idleConn[key] = append(idles, pconn)
   899  	t.idleLRU.add(pconn)
   900  	if t.MaxIdleConns != 0 && t.idleLRU.len() > t.MaxIdleConns {
   901  		oldest := t.idleLRU.removeOldest()
   902  		oldest.close(errTooManyIdle)
   903  		t.removeIdleConnLocked(oldest)
   904  	}
   905  
   906  	// Set idle timer, but only for HTTP/1 (pconn.alt == nil).
   907  	// The HTTP/2 implementation manages the idle timer itself
   908  	// (see idleConnTimeout in h2_bundle.go).
   909  	if t.IdleConnTimeout > 0 && pconn.alt == nil {
   910  		if pconn.idleTimer != nil {
   911  			pconn.idleTimer.Reset(t.IdleConnTimeout)
   912  		} else {
   913  			pconn.idleTimer = time.AfterFunc(t.IdleConnTimeout, pconn.closeConnIfStillIdle)
   914  		}
   915  	}
   916  	pconn.idleAt = time.Now()
   917  	return nil
   918  }
   919  
   920  // queueForIdleConn queues w to receive the next idle connection for w.cm.
   921  // As an optimization hint to the caller, queueForIdleConn reports whether
   922  // it successfully delivered an already-idle connection.
   923  func (t *Transport) queueForIdleConn(w *wantConn) (delivered bool) {
   924  	if t.DisableKeepAlives {
   925  		return false
   926  	}
   927  
   928  	t.idleMu.Lock()
   929  	defer t.idleMu.Unlock()
   930  
   931  	// Stop closing connections that become idle - we might want one.
   932  	// (That is, undo the effect of t.CloseIdleConnections.)
   933  	t.closeIdle = false
   934  
   935  	if w == nil {
   936  		// Happens in test hook.
   937  		return false
   938  	}
   939  
   940  	// If IdleConnTimeout is set, calculate the oldest
   941  	// persistConn.idleAt time we're willing to use a cached idle
   942  	// conn.
   943  	var oldTime time.Time
   944  	if t.IdleConnTimeout > 0 {
   945  		oldTime = time.Now().Add(-t.IdleConnTimeout)
   946  	}
   947  
   948  	// Look for most recently-used idle connection.
   949  	if list, ok := t.idleConn[w.key]; ok {
   950  		stop := false
   951  		delivered := false
   952  		for len(list) > 0 && !stop {
   953  			pconn := list[len(list)-1]
   954  
   955  			// See whether this connection has been idle too long, considering
   956  			// only the wall time (the Round(0)), in case this is a laptop or VM
   957  			// coming out of suspend with previously cached idle connections.
   958  			tooOld := !oldTime.IsZero() && pconn.idleAt.Round(0).Before(oldTime)
   959  			if tooOld {
   960  				// Async cleanup. Launch in its own goroutine (as if a
   961  				// time.AfterFunc called it); it acquires idleMu, which we're
   962  				// holding, and does a synchronous net.Conn.Close.
   963  				go pconn.closeConnIfStillIdle()
   964  			}
   965  			if pconn.isBroken() || tooOld {
   966  				// If either persistConn.readLoop has marked the connection
   967  				// broken, but Transport.removeIdleConn has not yet removed it
   968  				// from the idle list, or if this persistConn is too old (it was
   969  				// idle too long), then ignore it and look for another. In both
   970  				// cases it's already in the process of being closed.
   971  				list = list[:len(list)-1]
   972  				continue
   973  			}
   974  			delivered = w.tryDeliver(pconn, nil)
   975  			if delivered {
   976  				if pconn.alt != nil {
   977  					// HTTP/2: multiple clients can share pconn.
   978  					// Leave it in the list.
   979  				} else {
   980  					// HTTP/1: only one client can use pconn.
   981  					// Remove it from the list.
   982  					t.idleLRU.remove(pconn)
   983  					list = list[:len(list)-1]
   984  				}
   985  			}
   986  			stop = true
   987  		}
   988  		if len(list) > 0 {
   989  			t.idleConn[w.key] = list
   990  		} else {
   991  			delete(t.idleConn, w.key)
   992  		}
   993  		if stop {
   994  			return delivered
   995  		}
   996  	}
   997  
   998  	// Register to receive next connection that becomes idle.
   999  	if t.idleConnWait == nil {
  1000  		t.idleConnWait = make(map[connectMethodKey]wantConnQueue)
  1001  	}
  1002  	q := t.idleConnWait[w.key]
  1003  	q.cleanFront()
  1004  	q.pushBack(w)
  1005  	t.idleConnWait[w.key] = q
  1006  	return false
  1007  }
  1008  
  1009  // removeIdleConn marks pconn as dead.
  1010  func (t *Transport) removeIdleConn(pconn *persistConn) bool {
  1011  	t.idleMu.Lock()
  1012  	defer t.idleMu.Unlock()
  1013  	return t.removeIdleConnLocked(pconn)
  1014  }
  1015  
  1016  // t.idleMu must be held.
  1017  func (t *Transport) removeIdleConnLocked(pconn *persistConn) bool {
  1018  	if pconn.idleTimer != nil {
  1019  		pconn.idleTimer.Stop()
  1020  	}
  1021  	t.idleLRU.remove(pconn)
  1022  	key := pconn.cacheKey
  1023  	pconns := t.idleConn[key]
  1024  	var removed bool
  1025  	switch len(pconns) {
  1026  	case 0:
  1027  		// Nothing
  1028  	case 1:
  1029  		if pconns[0] == pconn {
  1030  			delete(t.idleConn, key)
  1031  			removed = true
  1032  		}
  1033  	default:
  1034  		for i, v := range pconns {
  1035  			if v != pconn {
  1036  				continue
  1037  			}
  1038  			// Slide down, keeping most recently-used
  1039  			// conns at the end.
  1040  			copy(pconns[i:], pconns[i+1:])
  1041  			t.idleConn[key] = pconns[:len(pconns)-1]
  1042  			removed = true
  1043  			break
  1044  		}
  1045  	}
  1046  	return removed
  1047  }
  1048  
  1049  func (t *Transport) setReqCanceler(r *Request, fn func(error)) {
  1050  	t.reqMu.Lock()
  1051  	defer t.reqMu.Unlock()
  1052  	if t.reqCanceler == nil {
  1053  		t.reqCanceler = make(map[*Request]func(error))
  1054  	}
  1055  	if fn != nil {
  1056  		t.reqCanceler[r] = fn
  1057  	} else {
  1058  		delete(t.reqCanceler, r)
  1059  	}
  1060  }
  1061  
  1062  // replaceReqCanceler replaces an existing cancel function. If there is no cancel function
  1063  // for the request, we don't set the function and return false.
  1064  // Since CancelRequest will clear the canceler, we can use the return value to detect if
  1065  // the request was canceled since the last setReqCancel call.
  1066  func (t *Transport) replaceReqCanceler(r *Request, fn func(error)) bool {
  1067  	t.reqMu.Lock()
  1068  	defer t.reqMu.Unlock()
  1069  	_, ok := t.reqCanceler[r]
  1070  	if !ok {
  1071  		return false
  1072  	}
  1073  	if fn != nil {
  1074  		t.reqCanceler[r] = fn
  1075  	} else {
  1076  		delete(t.reqCanceler, r)
  1077  	}
  1078  	return true
  1079  }
  1080  
  1081  var zeroDialer net.Dialer
  1082  
  1083  func (t *Transport) dial(ctx context.Context, network, addr string) (net.Conn, error) {
  1084  	if t.DialContext != nil {
  1085  		return t.DialContext(ctx, network, addr)
  1086  	}
  1087  	if t.Dial != nil {
  1088  		c, err := t.Dial(network, addr)
  1089  		if c == nil && err == nil {
  1090  			err = errors.New("net/http: Transport.Dial hook returned (nil, nil)")
  1091  		}
  1092  		return c, err
  1093  	}
  1094  	return zeroDialer.DialContext(ctx, network, addr)
  1095  }
  1096  
  1097  // A wantConn records state about a wanted connection
  1098  // (that is, an active call to getConn).
  1099  // The conn may be gotten by dialing or by finding an idle connection,
  1100  // or a cancellation may make the conn no longer wanted.
  1101  // These three options are racing against each other and use
  1102  // wantConn to coordinate and agree about the winning outcome.
  1103  type wantConn struct {
  1104  	cm    connectMethod
  1105  	key   connectMethodKey // cm.key()
  1106  	ctx   context.Context  // context for dial
  1107  	ready chan struct{}    // closed when pc, err pair is delivered
  1108  
  1109  	// hooks for testing to know when dials are done
  1110  	// beforeDial is called in the getConn goroutine when the dial is queued.
  1111  	// afterDial is called when the dial is completed or cancelled.
  1112  	beforeDial func()
  1113  	afterDial  func()
  1114  
  1115  	mu  sync.Mutex // protects pc, err, close(ready)
  1116  	pc  *persistConn
  1117  	err error
  1118  }
  1119  
  1120  // waiting reports whether w is still waiting for an answer (connection or error).
  1121  func (w *wantConn) waiting() bool {
  1122  	select {
  1123  	case <-w.ready:
  1124  		return false
  1125  	default:
  1126  		return true
  1127  	}
  1128  }
  1129  
  1130  // tryDeliver attempts to deliver pc, err to w and reports whether it succeeded.
  1131  func (w *wantConn) tryDeliver(pc *persistConn, err error) bool {
  1132  	w.mu.Lock()
  1133  	defer w.mu.Unlock()
  1134  
  1135  	if w.pc != nil || w.err != nil {
  1136  		return false
  1137  	}
  1138  
  1139  	w.pc = pc
  1140  	w.err = err
  1141  	if w.pc == nil && w.err == nil {
  1142  		panic("net/http: internal error: misuse of tryDeliver")
  1143  	}
  1144  	close(w.ready)
  1145  	return true
  1146  }
  1147  
  1148  // cancel marks w as no longer wanting a result (for example, due to cancellation).
  1149  // If a connection has been delivered already, cancel returns it with t.putOrCloseIdleConn.
  1150  func (w *wantConn) cancel(t *Transport, err error) {
  1151  	w.mu.Lock()
  1152  	if w.pc == nil && w.err == nil {
  1153  		close(w.ready) // catch misbehavior in future delivery
  1154  	}
  1155  	pc := w.pc
  1156  	w.pc = nil
  1157  	w.err = err
  1158  	w.mu.Unlock()
  1159  
  1160  	if pc != nil {
  1161  		t.putOrCloseIdleConn(pc)
  1162  	}
  1163  }
  1164  
  1165  // A wantConnQueue is a queue of wantConns.
  1166  type wantConnQueue struct {
  1167  	// This is a queue, not a deque.
  1168  	// It is split into two stages - head[headPos:] and tail.
  1169  	// popFront is trivial (headPos++) on the first stage, and
  1170  	// pushBack is trivial (append) on the second stage.
  1171  	// If the first stage is empty, popFront can swap the
  1172  	// first and second stages to remedy the situation.
  1173  	//
  1174  	// This two-stage split is analogous to the use of two lists
  1175  	// in Okasaki's purely functional queue but without the
  1176  	// overhead of reversing the list when swapping stages.
  1177  	head    []*wantConn
  1178  	headPos int
  1179  	tail    []*wantConn
  1180  }
  1181  
  1182  // len returns the number of items in the queue.
  1183  func (q *wantConnQueue) len() int {
  1184  	return len(q.head) - q.headPos + len(q.tail)
  1185  }
  1186  
  1187  // pushBack adds w to the back of the queue.
  1188  func (q *wantConnQueue) pushBack(w *wantConn) {
  1189  	q.tail = append(q.tail, w)
  1190  }
  1191  
  1192  // popFront removes and returns the wantConn at the front of the queue.
  1193  func (q *wantConnQueue) popFront() *wantConn {
  1194  	if q.headPos >= len(q.head) {
  1195  		if len(q.tail) == 0 {
  1196  			return nil
  1197  		}
  1198  		// Pick up tail as new head, clear tail.
  1199  		q.head, q.headPos, q.tail = q.tail, 0, q.head[:0]
  1200  	}
  1201  	w := q.head[q.headPos]
  1202  	q.head[q.headPos] = nil
  1203  	q.headPos++
  1204  	return w
  1205  }
  1206  
  1207  // peekFront returns the wantConn at the front of the queue without removing it.
  1208  func (q *wantConnQueue) peekFront() *wantConn {
  1209  	if q.headPos < len(q.head) {
  1210  		return q.head[q.headPos]
  1211  	}
  1212  	if len(q.tail) > 0 {
  1213  		return q.tail[0]
  1214  	}
  1215  	return nil
  1216  }
  1217  
  1218  // cleanFront pops any wantConns that are no longer waiting from the head of the
  1219  // queue, reporting whether any were popped.
  1220  func (q *wantConnQueue) cleanFront() (cleaned bool) {
  1221  	for {
  1222  		w := q.peekFront()
  1223  		if w == nil || w.waiting() {
  1224  			return cleaned
  1225  		}
  1226  		q.popFront()
  1227  		cleaned = true
  1228  	}
  1229  }
  1230  
  1231  func (t *Transport) customDialTLS(ctx context.Context, network, addr string) (conn net.Conn, err error) {
  1232  	if t.DialTLSContext != nil {
  1233  		conn, err = t.DialTLSContext(ctx, network, addr)
  1234  	} else {
  1235  		conn, err = t.DialTLS(network, addr)
  1236  	}
  1237  	if conn == nil && err == nil {
  1238  		err = errors.New("net/http: Transport.DialTLS or DialTLSContext returned (nil, nil)")
  1239  	}
  1240  	return
  1241  }
  1242  
  1243  // getConn dials and creates a new persistConn to the target as
  1244  // specified in the connectMethod. This includes doing a proxy CONNECT
  1245  // and/or setting up TLS.  If this doesn't return an error, the persistConn
  1246  // is ready to write requests to.
  1247  func (t *Transport) getConn(treq *transportRequest, cm connectMethod) (pc *persistConn, err error) {
  1248  	req := treq.Request
  1249  	trace := treq.trace
  1250  	ctx := req.Context()
  1251  	if trace != nil && trace.GetConn != nil {
  1252  		trace.GetConn(cm.addr())
  1253  	}
  1254  
  1255  	w := &wantConn{
  1256  		cm:         cm,
  1257  		key:        cm.key(),
  1258  		ctx:        ctx,
  1259  		ready:      make(chan struct{}, 1),
  1260  		beforeDial: testHookPrePendingDial,
  1261  		afterDial:  testHookPostPendingDial,
  1262  	}
  1263  	defer func() {
  1264  		if err != nil {
  1265  			w.cancel(t, err)
  1266  		}
  1267  	}()
  1268  
  1269  	// Queue for idle connection.
  1270  	if delivered := t.queueForIdleConn(w); delivered {
  1271  		pc := w.pc
  1272  		// Trace only for HTTP/1.
  1273  		// HTTP/2 calls trace.GotConn itself.
  1274  		if pc.alt == nil && trace != nil && trace.GotConn != nil {
  1275  			trace.GotConn(pc.gotIdleConnTrace(pc.idleAt))
  1276  		}
  1277  		// set request canceler to some non-nil function so we
  1278  		// can detect whether it was cleared between now and when
  1279  		// we enter roundTrip
  1280  		t.setReqCanceler(req, func(error) {})
  1281  		return pc, nil
  1282  	}
  1283  
  1284  	cancelc := make(chan error, 1)
  1285  	t.setReqCanceler(req, func(err error) { cancelc <- err })
  1286  
  1287  	// Queue for permission to dial.
  1288  	t.queueForDial(w)
  1289  
  1290  	// Wait for completion or cancellation.
  1291  	select {
  1292  	case <-w.ready:
  1293  		// Trace success but only for HTTP/1.
  1294  		// HTTP/2 calls trace.GotConn itself.
  1295  		if w.pc != nil && w.pc.alt == nil && trace != nil && trace.GotConn != nil {
  1296  			trace.GotConn(httptrace.GotConnInfo{Conn: w.pc.conn, Reused: w.pc.isReused()})
  1297  		}
  1298  		if w.err != nil {
  1299  			// If the request has been cancelled, that's probably
  1300  			// what caused w.err; if so, prefer to return the
  1301  			// cancellation error (see golang.org/issue/16049).
  1302  			select {
  1303  			case <-req.Cancel:
  1304  				return nil, errRequestCanceledConn
  1305  			case <-req.Context().Done():
  1306  				return nil, req.Context().Err()
  1307  			case err := <-cancelc:
  1308  				if err == errRequestCanceled {
  1309  					err = errRequestCanceledConn
  1310  				}
  1311  				return nil, err
  1312  			default:
  1313  				// return below
  1314  			}
  1315  		}
  1316  		return w.pc, w.err
  1317  	case <-req.Cancel:
  1318  		return nil, errRequestCanceledConn
  1319  	case <-req.Context().Done():
  1320  		return nil, req.Context().Err()
  1321  	case err := <-cancelc:
  1322  		if err == errRequestCanceled {
  1323  			err = errRequestCanceledConn
  1324  		}
  1325  		return nil, err
  1326  	}
  1327  }
  1328  
  1329  // queueForDial queues w to wait for permission to begin dialing.
  1330  // Once w receives permission to dial, it will do so in a separate goroutine.
  1331  func (t *Transport) queueForDial(w *wantConn) {
  1332  	w.beforeDial()
  1333  	if t.MaxConnsPerHost <= 0 {
  1334  		go t.dialConnFor(w)
  1335  		return
  1336  	}
  1337  
  1338  	t.connsPerHostMu.Lock()
  1339  	defer t.connsPerHostMu.Unlock()
  1340  
  1341  	if n := t.connsPerHost[w.key]; n < t.MaxConnsPerHost {
  1342  		if t.connsPerHost == nil {
  1343  			t.connsPerHost = make(map[connectMethodKey]int)
  1344  		}
  1345  		t.connsPerHost[w.key] = n + 1
  1346  		go t.dialConnFor(w)
  1347  		return
  1348  	}
  1349  
  1350  	if t.connsPerHostWait == nil {
  1351  		t.connsPerHostWait = make(map[connectMethodKey]wantConnQueue)
  1352  	}
  1353  	q := t.connsPerHostWait[w.key]
  1354  	q.cleanFront()
  1355  	q.pushBack(w)
  1356  	t.connsPerHostWait[w.key] = q
  1357  }
  1358  
  1359  // dialConnFor dials on behalf of w and delivers the result to w.
  1360  // dialConnFor has received permission to dial w.cm and is counted in t.connCount[w.cm.key()].
  1361  // If the dial is cancelled or unsuccessful, dialConnFor decrements t.connCount[w.cm.key()].
  1362  func (t *Transport) dialConnFor(w *wantConn) {
  1363  	defer w.afterDial()
  1364  
  1365  	pc, err := t.dialConn(w.ctx, w.cm)
  1366  	delivered := w.tryDeliver(pc, err)
  1367  	if err == nil && (!delivered || pc.alt != nil) {
  1368  		// pconn was not passed to w,
  1369  		// or it is HTTP/2 and can be shared.
  1370  		// Add to the idle connection pool.
  1371  		t.putOrCloseIdleConn(pc)
  1372  	}
  1373  	if err != nil {
  1374  		t.decConnsPerHost(w.key)
  1375  	}
  1376  }
  1377  
  1378  // decConnsPerHost decrements the per-host connection count for key,
  1379  // which may in turn give a different waiting goroutine permission to dial.
  1380  func (t *Transport) decConnsPerHost(key connectMethodKey) {
  1381  	if t.MaxConnsPerHost <= 0 {
  1382  		return
  1383  	}
  1384  
  1385  	t.connsPerHostMu.Lock()
  1386  	defer t.connsPerHostMu.Unlock()
  1387  	n := t.connsPerHost[key]
  1388  	if n == 0 {
  1389  		// Shouldn't happen, but if it does, the counting is buggy and could
  1390  		// easily lead to a silent deadlock, so report the problem loudly.
  1391  		panic("net/http: internal error: connCount underflow")
  1392  	}
  1393  
  1394  	// Can we hand this count to a goroutine still waiting to dial?
  1395  	// (Some goroutines on the wait list may have timed out or
  1396  	// gotten a connection another way. If they're all gone,
  1397  	// we don't want to kick off any spurious dial operations.)
  1398  	if q := t.connsPerHostWait[key]; q.len() > 0 {
  1399  		done := false
  1400  		for q.len() > 0 {
  1401  			w := q.popFront()
  1402  			if w.waiting() {
  1403  				go t.dialConnFor(w)
  1404  				done = true
  1405  				break
  1406  			}
  1407  		}
  1408  		if q.len() == 0 {
  1409  			delete(t.connsPerHostWait, key)
  1410  		} else {
  1411  			// q is a value (like a slice), so we have to store
  1412  			// the updated q back into the map.
  1413  			t.connsPerHostWait[key] = q
  1414  		}
  1415  		if done {
  1416  			return
  1417  		}
  1418  	}
  1419  
  1420  	// Otherwise, decrement the recorded count.
  1421  	if n--; n == 0 {
  1422  		delete(t.connsPerHost, key)
  1423  	} else {
  1424  		t.connsPerHost[key] = n
  1425  	}
  1426  }
  1427  
  1428  // Add TLS to a persistent connection, i.e. negotiate a TLS session. If pconn is already a TLS
  1429  // tunnel, this function establishes a nested TLS session inside the encrypted channel.
  1430  // The remote endpoint's name may be overridden by TLSClientConfig.ServerName.
  1431  func (pconn *persistConn) addTLS(name string, trace *httptrace.ClientTrace) error {
  1432  	// Initiate TLS and check remote host name against certificate.
  1433  	cfg := cloneTLSConfig(pconn.t.TLSClientConfig)
  1434  	if cfg.ServerName == "" {
  1435  		cfg.ServerName = name
  1436  	}
  1437  	if pconn.cacheKey.onlyH1 {
  1438  		cfg.NextProtos = nil
  1439  	}
  1440  	plainConn := pconn.conn
  1441  	tlsConn := tls.Client(plainConn, cfg)
  1442  	errc := make(chan error, 2)
  1443  	var timer *time.Timer // for canceling TLS handshake
  1444  	if d := pconn.t.TLSHandshakeTimeout; d != 0 {
  1445  		timer = time.AfterFunc(d, func() {
  1446  			errc <- tlsHandshakeTimeoutError{}
  1447  		})
  1448  	}
  1449  	go func() {
  1450  		if trace != nil && trace.TLSHandshakeStart != nil {
  1451  			trace.TLSHandshakeStart()
  1452  		}
  1453  		err := tlsConn.Handshake()
  1454  		if timer != nil {
  1455  			timer.Stop()
  1456  		}
  1457  		errc <- err
  1458  	}()
  1459  	if err := <-errc; err != nil {
  1460  		plainConn.Close()
  1461  		if trace != nil && trace.TLSHandshakeDone != nil {
  1462  			trace.TLSHandshakeDone(tls.ConnectionState{}, err)
  1463  		}
  1464  		return err
  1465  	}
  1466  	cs := tlsConn.ConnectionState()
  1467  	if trace != nil && trace.TLSHandshakeDone != nil {
  1468  		trace.TLSHandshakeDone(cs, nil)
  1469  	}
  1470  	pconn.tlsState = &cs
  1471  	pconn.conn = tlsConn
  1472  	return nil
  1473  }
  1474  
  1475  func (t *Transport) dialConn(ctx context.Context, cm connectMethod) (pconn *persistConn, err error) {
  1476  	pconn = &persistConn{
  1477  		t:             t,
  1478  		cacheKey:      cm.key(),
  1479  		reqch:         make(chan requestAndChan, 1),
  1480  		writech:       make(chan writeRequest, 1),
  1481  		closech:       make(chan struct{}),
  1482  		writeErrCh:    make(chan error, 1),
  1483  		writeLoopDone: make(chan struct{}),
  1484  	}
  1485  	trace := httptrace.ContextClientTrace(ctx)
  1486  	wrapErr := func(err error) error {
  1487  		if cm.proxyURL != nil {
  1488  			// Return a typed error, per Issue 16997
  1489  			return &net.OpError{Op: "proxyconnect", Net: "tcp", Err: err}
  1490  		}
  1491  		return err
  1492  	}
  1493  	if cm.scheme() == "https" && t.hasCustomTLSDialer() {
  1494  		var err error
  1495  		pconn.conn, err = t.customDialTLS(ctx, "tcp", cm.addr())
  1496  		if err != nil {
  1497  			return nil, wrapErr(err)
  1498  		}
  1499  		if tc, ok := pconn.conn.(*tls.Conn); ok {
  1500  			// Handshake here, in case DialTLS didn't. TLSNextProto below
  1501  			// depends on it for knowing the connection state.
  1502  			if trace != nil && trace.TLSHandshakeStart != nil {
  1503  				trace.TLSHandshakeStart()
  1504  			}
  1505  			if err := tc.Handshake(); err != nil {
  1506  				go pconn.conn.Close()
  1507  				if trace != nil && trace.TLSHandshakeDone != nil {
  1508  					trace.TLSHandshakeDone(tls.ConnectionState{}, err)
  1509  				}
  1510  				return nil, err
  1511  			}
  1512  			cs := tc.ConnectionState()
  1513  			if trace != nil && trace.TLSHandshakeDone != nil {
  1514  				trace.TLSHandshakeDone(cs, nil)
  1515  			}
  1516  			pconn.tlsState = &cs
  1517  		}
  1518  	} else {
  1519  		conn, err := t.dial(ctx, "tcp", cm.addr())
  1520  		if err != nil {
  1521  			return nil, wrapErr(err)
  1522  		}
  1523  		pconn.conn = conn
  1524  		if cm.scheme() == "https" {
  1525  			var firstTLSHost string
  1526  			if firstTLSHost, _, err = net.SplitHostPort(cm.addr()); err != nil {
  1527  				return nil, wrapErr(err)
  1528  			}
  1529  			if err = pconn.addTLS(firstTLSHost, trace); err != nil {
  1530  				return nil, wrapErr(err)
  1531  			}
  1532  		}
  1533  	}
  1534  
  1535  	// Proxy setup.
  1536  	switch {
  1537  	case cm.proxyURL == nil:
  1538  		// Do nothing. Not using a proxy.
  1539  	case cm.proxyURL.Scheme == "socks5":
  1540  		conn := pconn.conn
  1541  		d := socksNewDialer("tcp", conn.RemoteAddr().String())
  1542  		if u := cm.proxyURL.User; u != nil {
  1543  			auth := &socksUsernamePassword{
  1544  				Username: u.Username(),
  1545  			}
  1546  			auth.Password, _ = u.Password()
  1547  			d.AuthMethods = []socksAuthMethod{
  1548  				socksAuthMethodNotRequired,
  1549  				socksAuthMethodUsernamePassword,
  1550  			}
  1551  			d.Authenticate = auth.Authenticate
  1552  		}
  1553  		if _, err := d.DialWithConn(ctx, conn, "tcp", cm.targetAddr); err != nil {
  1554  			conn.Close()
  1555  			return nil, err
  1556  		}
  1557  	case cm.targetScheme == "http":
  1558  		pconn.isProxy = true
  1559  		if pa := cm.proxyAuth(); pa != "" {
  1560  			pconn.mutateHeaderFunc = func(h Header) {
  1561  				h.Set("Proxy-Authorization", pa)
  1562  			}
  1563  		}
  1564  	case cm.targetScheme == "https":
  1565  		conn := pconn.conn
  1566  		hdr := t.ProxyConnectHeader
  1567  		if hdr == nil {
  1568  			hdr = make(Header)
  1569  		}
  1570  		if pa := cm.proxyAuth(); pa != "" {
  1571  			hdr = hdr.Clone()
  1572  			hdr.Set("Proxy-Authorization", pa)
  1573  		}
  1574  		connectReq := &Request{
  1575  			Method: "CONNECT",
  1576  			URL:    &url.URL{Opaque: cm.targetAddr},
  1577  			Host:   cm.targetAddr,
  1578  			Header: hdr,
  1579  		}
  1580  
  1581  		// If there's no done channel (no deadline or cancellation
  1582  		// from the caller possible), at least set some (long)
  1583  		// timeout here. This will make sure we don't block forever
  1584  		// and leak a goroutine if the connection stops replying
  1585  		// after the TCP connect.
  1586  		connectCtx := ctx
  1587  		if ctx.Done() == nil {
  1588  			newCtx, cancel := context.WithTimeout(ctx, 1*time.Minute)
  1589  			defer cancel()
  1590  			connectCtx = newCtx
  1591  		}
  1592  
  1593  		didReadResponse := make(chan struct{}) // closed after CONNECT write+read is done or fails
  1594  		var (
  1595  			resp *Response
  1596  			err  error // write or read error
  1597  		)
  1598  		// Write the CONNECT request & read the response.
  1599  		go func() {
  1600  			defer close(didReadResponse)
  1601  			err = connectReq.Write(conn)
  1602  			if err != nil {
  1603  				return
  1604  			}
  1605  			// Okay to use and discard buffered reader here, because
  1606  			// TLS server will not speak until spoken to.
  1607  			br := bufio.NewReader(conn)
  1608  			resp, err = ReadResponse(br, connectReq)
  1609  		}()
  1610  		select {
  1611  		case <-connectCtx.Done():
  1612  			conn.Close()
  1613  			<-didReadResponse
  1614  			return nil, connectCtx.Err()
  1615  		case <-didReadResponse:
  1616  			// resp or err now set
  1617  		}
  1618  		if err != nil {
  1619  			conn.Close()
  1620  			return nil, err
  1621  		}
  1622  		if resp.StatusCode != 200 {
  1623  			f := strings.SplitN(resp.Status, " ", 2)
  1624  			conn.Close()
  1625  			if len(f) < 2 {
  1626  				return nil, errors.New("unknown status code")
  1627  			}
  1628  			return nil, errors.New(f[1])
  1629  		}
  1630  	}
  1631  
  1632  	if cm.proxyURL != nil && cm.targetScheme == "https" {
  1633  		if err := pconn.addTLS(cm.tlsHost(), trace); err != nil {
  1634  			return nil, err
  1635  		}
  1636  	}
  1637  
  1638  	if s := pconn.tlsState; s != nil && s.NegotiatedProtocolIsMutual && s.NegotiatedProtocol != "" {
  1639  		if next, ok := t.TLSNextProto[s.NegotiatedProtocol]; ok {
  1640  			return &persistConn{t: t, cacheKey: pconn.cacheKey, alt: next(cm.targetAddr, pconn.conn.(*tls.Conn))}, nil
  1641  		}
  1642  	}
  1643  
  1644  	pconn.br = bufio.NewReaderSize(pconn, t.readBufferSize())
  1645  	pconn.bw = bufio.NewWriterSize(persistConnWriter{pconn}, t.writeBufferSize())
  1646  
  1647  	go pconn.readLoop()
  1648  	go pconn.writeLoop()
  1649  	return pconn, nil
  1650  }
  1651  
  1652  // persistConnWriter is the io.Writer written to by pc.bw.
  1653  // It accumulates the number of bytes written to the underlying conn,
  1654  // so the retry logic can determine whether any bytes made it across
  1655  // the wire.
  1656  // This is exactly 1 pointer field wide so it can go into an interface
  1657  // without allocation.
  1658  type persistConnWriter struct {
  1659  	pc *persistConn
  1660  }
  1661  
  1662  func (w persistConnWriter) Write(p []byte) (n int, err error) {
  1663  	n, err = w.pc.conn.Write(p)
  1664  	w.pc.nwrite += int64(n)
  1665  	return
  1666  }
  1667  
  1668  // ReadFrom exposes persistConnWriter's underlying Conn to io.Copy and if
  1669  // the Conn implements io.ReaderFrom, it can take advantage of optimizations
  1670  // such as sendfile.
  1671  func (w persistConnWriter) ReadFrom(r io.Reader) (n int64, err error) {
  1672  	n, err = io.Copy(w.pc.conn, r)
  1673  	w.pc.nwrite += n
  1674  	return
  1675  }
  1676  
  1677  var _ io.ReaderFrom = (*persistConnWriter)(nil)
  1678  
  1679  // connectMethod is the map key (in its String form) for keeping persistent
  1680  // TCP connections alive for subsequent HTTP requests.
  1681  //
  1682  // A connect method may be of the following types:
  1683  //
  1684  //	connectMethod.key().String()      Description
  1685  //	------------------------------    -------------------------
  1686  //	|http|foo.com                     http directly to server, no proxy
  1687  //	|https|foo.com                    https directly to server, no proxy
  1688  //	|https,h1|foo.com                 https directly to server w/o HTTP/2, no proxy
  1689  //	http://proxy.com|https|foo.com    http to proxy, then CONNECT to foo.com
  1690  //	http://proxy.com|http             http to proxy, http to anywhere after that
  1691  //	socks5://proxy.com|http|foo.com   socks5 to proxy, then http to foo.com
  1692  //	socks5://proxy.com|https|foo.com  socks5 to proxy, then https to foo.com
  1693  //	https://proxy.com|https|foo.com   https to proxy, then CONNECT to foo.com
  1694  //	https://proxy.com|http            https to proxy, http to anywhere after that
  1695  //
  1696  type connectMethod struct {
  1697  	proxyURL     *url.URL // nil for no proxy, else full proxy URL
  1698  	targetScheme string   // "http" or "https"
  1699  	// If proxyURL specifies an http or https proxy, and targetScheme is http (not https),
  1700  	// then targetAddr is not included in the connect method key, because the socket can
  1701  	// be reused for different targetAddr values.
  1702  	targetAddr string
  1703  	onlyH1     bool // whether to disable HTTP/2 and force HTTP/1
  1704  }
  1705  
  1706  func (cm *connectMethod) key() connectMethodKey {
  1707  	proxyStr := ""
  1708  	targetAddr := cm.targetAddr
  1709  	if cm.proxyURL != nil {
  1710  		proxyStr = cm.proxyURL.String()
  1711  		if (cm.proxyURL.Scheme == "http" || cm.proxyURL.Scheme == "https") && cm.targetScheme == "http" {
  1712  			targetAddr = ""
  1713  		}
  1714  	}
  1715  	return connectMethodKey{
  1716  		proxy:  proxyStr,
  1717  		scheme: cm.targetScheme,
  1718  		addr:   targetAddr,
  1719  		onlyH1: cm.onlyH1,
  1720  	}
  1721  }
  1722  
  1723  // scheme returns the first hop scheme: http, https, or socks5
  1724  func (cm *connectMethod) scheme() string {
  1725  	if cm.proxyURL != nil {
  1726  		return cm.proxyURL.Scheme
  1727  	}
  1728  	return cm.targetScheme
  1729  }
  1730  
  1731  // addr returns the first hop "host:port" to which we need to TCP connect.
  1732  func (cm *connectMethod) addr() string {
  1733  	if cm.proxyURL != nil {
  1734  		return canonicalAddr(cm.proxyURL)
  1735  	}
  1736  	return cm.targetAddr
  1737  }
  1738  
  1739  // tlsHost returns the host name to match against the peer's
  1740  // TLS certificate.
  1741  func (cm *connectMethod) tlsHost() string {
  1742  	h := cm.targetAddr
  1743  	if hasPort(h) {
  1744  		h = h[:strings.LastIndex(h, ":")]
  1745  	}
  1746  	return h
  1747  }
  1748  
  1749  // connectMethodKey is the map key version of connectMethod, with a
  1750  // stringified proxy URL (or the empty string) instead of a pointer to
  1751  // a URL.
  1752  type connectMethodKey struct {
  1753  	proxy, scheme, addr string
  1754  	onlyH1              bool
  1755  }
  1756  
  1757  func (k connectMethodKey) String() string {
  1758  	// Only used by tests.
  1759  	var h1 string
  1760  	if k.onlyH1 {
  1761  		h1 = ",h1"
  1762  	}
  1763  	return fmt.Sprintf("%s|%s%s|%s", k.proxy, k.scheme, h1, k.addr)
  1764  }
  1765  
  1766  // persistConn wraps a connection, usually a persistent one
  1767  // (but may be used for non-keep-alive requests as well)
  1768  type persistConn struct {
  1769  	// alt optionally specifies the TLS NextProto RoundTripper.
  1770  	// This is used for HTTP/2 today and future protocols later.
  1771  	// If it's non-nil, the rest of the fields are unused.
  1772  	alt RoundTripper
  1773  
  1774  	t         *Transport
  1775  	cacheKey  connectMethodKey
  1776  	conn      net.Conn
  1777  	tlsState  *tls.ConnectionState
  1778  	br        *bufio.Reader       // from conn
  1779  	bw        *bufio.Writer       // to conn
  1780  	nwrite    int64               // bytes written
  1781  	reqch     chan requestAndChan // written by roundTrip; read by readLoop
  1782  	writech   chan writeRequest   // written by roundTrip; read by writeLoop
  1783  	closech   chan struct{}       // closed when conn closed
  1784  	isProxy   bool
  1785  	sawEOF    bool  // whether we've seen EOF from conn; owned by readLoop
  1786  	readLimit int64 // bytes allowed to be read; owned by readLoop
  1787  	// writeErrCh passes the request write error (usually nil)
  1788  	// from the writeLoop goroutine to the readLoop which passes
  1789  	// it off to the res.Body reader, which then uses it to decide
  1790  	// whether or not a connection can be reused. Issue 7569.
  1791  	writeErrCh chan error
  1792  
  1793  	writeLoopDone chan struct{} // closed when write loop ends
  1794  
  1795  	// Both guarded by Transport.idleMu:
  1796  	idleAt    time.Time   // time it last become idle
  1797  	idleTimer *time.Timer // holding an AfterFunc to close it
  1798  
  1799  	mu                   sync.Mutex // guards following fields
  1800  	numExpectedResponses int
  1801  	closed               error // set non-nil when conn is closed, before closech is closed
  1802  	canceledErr          error // set non-nil if conn is canceled
  1803  	broken               bool  // an error has happened on this connection; marked broken so it's not reused.
  1804  	reused               bool  // whether conn has had successful request/response and is being reused.
  1805  	// mutateHeaderFunc is an optional func to modify extra
  1806  	// headers on each outbound request before it's written. (the
  1807  	// original Request given to RoundTrip is not modified)
  1808  	mutateHeaderFunc func(Header)
  1809  }
  1810  
  1811  func (pc *persistConn) maxHeaderResponseSize() int64 {
  1812  	if v := pc.t.MaxResponseHeaderBytes; v != 0 {
  1813  		return v
  1814  	}
  1815  	return 10 << 20 // conservative default; same as http2
  1816  }
  1817  
  1818  func (pc *persistConn) Read(p []byte) (n int, err error) {
  1819  	if pc.readLimit <= 0 {
  1820  		return 0, fmt.Errorf("read limit of %d bytes exhausted", pc.maxHeaderResponseSize())
  1821  	}
  1822  	if int64(len(p)) > pc.readLimit {
  1823  		p = p[:pc.readLimit]
  1824  	}
  1825  	n, err = pc.conn.Read(p)
  1826  	if err == io.EOF {
  1827  		pc.sawEOF = true
  1828  	}
  1829  	pc.readLimit -= int64(n)
  1830  	return
  1831  }
  1832  
  1833  // isBroken reports whether this connection is in a known broken state.
  1834  func (pc *persistConn) isBroken() bool {
  1835  	pc.mu.Lock()
  1836  	b := pc.closed != nil
  1837  	pc.mu.Unlock()
  1838  	return b
  1839  }
  1840  
  1841  // canceled returns non-nil if the connection was closed due to
  1842  // CancelRequest or due to context cancellation.
  1843  func (pc *persistConn) canceled() error {
  1844  	pc.mu.Lock()
  1845  	defer pc.mu.Unlock()
  1846  	return pc.canceledErr
  1847  }
  1848  
  1849  // isReused reports whether this connection has been used before.
  1850  func (pc *persistConn) isReused() bool {
  1851  	pc.mu.Lock()
  1852  	r := pc.reused
  1853  	pc.mu.Unlock()
  1854  	return r
  1855  }
  1856  
  1857  func (pc *persistConn) gotIdleConnTrace(idleAt time.Time) (t httptrace.GotConnInfo) {
  1858  	pc.mu.Lock()
  1859  	defer pc.mu.Unlock()
  1860  	t.Reused = pc.reused
  1861  	t.Conn = pc.conn
  1862  	t.WasIdle = true
  1863  	if !idleAt.IsZero() {
  1864  		t.IdleTime = time.Since(idleAt)
  1865  	}
  1866  	return
  1867  }
  1868  
  1869  func (pc *persistConn) cancelRequest(err error) {
  1870  	pc.mu.Lock()
  1871  	defer pc.mu.Unlock()
  1872  	pc.canceledErr = err
  1873  	pc.closeLocked(errRequestCanceled)
  1874  }
  1875  
  1876  // closeConnIfStillIdle closes the connection if it's still sitting idle.
  1877  // This is what's called by the persistConn's idleTimer, and is run in its
  1878  // own goroutine.
  1879  func (pc *persistConn) closeConnIfStillIdle() {
  1880  	t := pc.t
  1881  	t.idleMu.Lock()
  1882  	defer t.idleMu.Unlock()
  1883  	if _, ok := t.idleLRU.m[pc]; !ok {
  1884  		// Not idle.
  1885  		return
  1886  	}
  1887  	t.removeIdleConnLocked(pc)
  1888  	pc.close(errIdleConnTimeout)
  1889  }
  1890  
  1891  // mapRoundTripError returns the appropriate error value for
  1892  // persistConn.roundTrip.
  1893  //
  1894  // The provided err is the first error that (*persistConn).roundTrip
  1895  // happened to receive from its select statement.
  1896  //
  1897  // The startBytesWritten value should be the value of pc.nwrite before the roundTrip
  1898  // started writing the request.
  1899  func (pc *persistConn) mapRoundTripError(req *transportRequest, startBytesWritten int64, err error) error {
  1900  	if err == nil {
  1901  		return nil
  1902  	}
  1903  
  1904  	// If the request was canceled, that's better than network
  1905  	// failures that were likely the result of tearing down the
  1906  	// connection.
  1907  	if cerr := pc.canceled(); cerr != nil {
  1908  		return cerr
  1909  	}
  1910  
  1911  	// See if an error was set explicitly.
  1912  	req.mu.Lock()
  1913  	reqErr := req.err
  1914  	req.mu.Unlock()
  1915  	if reqErr != nil {
  1916  		return reqErr
  1917  	}
  1918  
  1919  	if err == errServerClosedIdle {
  1920  		// Don't decorate
  1921  		return err
  1922  	}
  1923  
  1924  	if _, ok := err.(transportReadFromServerError); ok {
  1925  		// Don't decorate
  1926  		return err
  1927  	}
  1928  	if pc.isBroken() {
  1929  		<-pc.writeLoopDone
  1930  		if pc.nwrite == startBytesWritten {
  1931  			return nothingWrittenError{err}
  1932  		}
  1933  		return fmt.Errorf("net/http: HTTP/1.x transport connection broken: %v", err)
  1934  	}
  1935  	return err
  1936  }
  1937  
  1938  // errCallerOwnsConn is an internal sentinel error used when we hand
  1939  // off a writable response.Body to the caller. We use this to prevent
  1940  // closing a net.Conn that is now owned by the caller.
  1941  var errCallerOwnsConn = errors.New("read loop ending; caller owns writable underlying conn")
  1942  
  1943  func (pc *persistConn) readLoop() {
  1944  	closeErr := errReadLoopExiting // default value, if not changed below
  1945  	defer func() {
  1946  		pc.close(closeErr)
  1947  		pc.t.removeIdleConn(pc)
  1948  	}()
  1949  
  1950  	tryPutIdleConn := func(trace *httptrace.ClientTrace) bool {
  1951  		if err := pc.t.tryPutIdleConn(pc); err != nil {
  1952  			closeErr = err
  1953  			if trace != nil && trace.PutIdleConn != nil && err != errKeepAlivesDisabled {
  1954  				trace.PutIdleConn(err)
  1955  			}
  1956  			return false
  1957  		}
  1958  		if trace != nil && trace.PutIdleConn != nil {
  1959  			trace.PutIdleConn(nil)
  1960  		}
  1961  		return true
  1962  	}
  1963  
  1964  	// eofc is used to block caller goroutines reading from Response.Body
  1965  	// at EOF until this goroutines has (potentially) added the connection
  1966  	// back to the idle pool.
  1967  	eofc := make(chan struct{})
  1968  	defer close(eofc) // unblock reader on errors
  1969  
  1970  	// Read this once, before loop starts. (to avoid races in tests)
  1971  	testHookMu.Lock()
  1972  	testHookReadLoopBeforeNextRead := testHookReadLoopBeforeNextRead
  1973  	testHookMu.Unlock()
  1974  
  1975  	alive := true
  1976  	for alive {
  1977  		pc.readLimit = pc.maxHeaderResponseSize()
  1978  		_, err := pc.br.Peek(1)
  1979  
  1980  		pc.mu.Lock()
  1981  		if pc.numExpectedResponses == 0 {
  1982  			pc.readLoopPeekFailLocked(err)
  1983  			pc.mu.Unlock()
  1984  			return
  1985  		}
  1986  		pc.mu.Unlock()
  1987  
  1988  		rc := <-pc.reqch
  1989  		trace := httptrace.ContextClientTrace(rc.req.Context())
  1990  
  1991  		var resp *Response
  1992  		if err == nil {
  1993  			resp, err = pc.readResponse(rc, trace)
  1994  		} else {
  1995  			err = transportReadFromServerError{err}
  1996  			closeErr = err
  1997  		}
  1998  
  1999  		if err != nil {
  2000  			if pc.readLimit <= 0 {
  2001  				err = fmt.Errorf("net/http: server response headers exceeded %d bytes; aborted", pc.maxHeaderResponseSize())
  2002  			}
  2003  
  2004  			select {
  2005  			case rc.ch <- responseAndError{err: err}:
  2006  			case <-rc.callerGone:
  2007  				return
  2008  			}
  2009  			return
  2010  		}
  2011  		pc.readLimit = maxInt64 // effectively no limit for response bodies
  2012  
  2013  		pc.mu.Lock()
  2014  		pc.numExpectedResponses--
  2015  		pc.mu.Unlock()
  2016  
  2017  		bodyWritable := resp.bodyIsWritable()
  2018  		hasBody := rc.req.Method != "HEAD" && resp.ContentLength != 0
  2019  
  2020  		if resp.Close || rc.req.Close || resp.StatusCode <= 199 || bodyWritable {
  2021  			// Don't do keep-alive on error if either party requested a close
  2022  			// or we get an unexpected informational (1xx) response.
  2023  			// StatusCode 100 is already handled above.
  2024  			alive = false
  2025  		}
  2026  
  2027  		if !hasBody || bodyWritable {
  2028  			pc.t.setReqCanceler(rc.req, nil)
  2029  
  2030  			// Put the idle conn back into the pool before we send the response
  2031  			// so if they process it quickly and make another request, they'll
  2032  			// get this same conn. But we use the unbuffered channel 'rc'
  2033  			// to guarantee that persistConn.roundTrip got out of its select
  2034  			// potentially waiting for this persistConn to close.
  2035  			// but after
  2036  			alive = alive &&
  2037  				!pc.sawEOF &&
  2038  				pc.wroteRequest() &&
  2039  				tryPutIdleConn(trace)
  2040  
  2041  			if bodyWritable {
  2042  				closeErr = errCallerOwnsConn
  2043  			}
  2044  
  2045  			select {
  2046  			case rc.ch <- responseAndError{res: resp}:
  2047  			case <-rc.callerGone:
  2048  				return
  2049  			}
  2050  
  2051  			// Now that they've read from the unbuffered channel, they're safely
  2052  			// out of the select that also waits on this goroutine to die, so
  2053  			// we're allowed to exit now if needed (if alive is false)
  2054  			testHookReadLoopBeforeNextRead()
  2055  			continue
  2056  		}
  2057  
  2058  		waitForBodyRead := make(chan bool, 2)
  2059  		body := &bodyEOFSignal{
  2060  			body: resp.Body,
  2061  			earlyCloseFn: func() error {
  2062  				waitForBodyRead <- false
  2063  				<-eofc // will be closed by deferred call at the end of the function
  2064  				return nil
  2065  
  2066  			},
  2067  			fn: func(err error) error {
  2068  				isEOF := err == io.EOF
  2069  				waitForBodyRead <- isEOF
  2070  				if isEOF {
  2071  					<-eofc // see comment above eofc declaration
  2072  				} else if err != nil {
  2073  					if cerr := pc.canceled(); cerr != nil {
  2074  						return cerr
  2075  					}
  2076  				}
  2077  				return err
  2078  			},
  2079  		}
  2080  
  2081  		resp.Body = body
  2082  		if rc.addedGzip && strings.EqualFold(resp.Header.Get("Content-Encoding"), "gzip") {
  2083  			resp.Body = &gzipReader{body: body}
  2084  			resp.Header.Del("Content-Encoding")
  2085  			resp.Header.Del("Content-Length")
  2086  			resp.ContentLength = -1
  2087  			resp.Uncompressed = true
  2088  		}
  2089  
  2090  		select {
  2091  		case rc.ch <- responseAndError{res: resp}:
  2092  		case <-rc.callerGone:
  2093  			return
  2094  		}
  2095  
  2096  		// Before looping back to the top of this function and peeking on
  2097  		// the bufio.Reader, wait for the caller goroutine to finish
  2098  		// reading the response body. (or for cancellation or death)
  2099  		select {
  2100  		case bodyEOF := <-waitForBodyRead:
  2101  			pc.t.setReqCanceler(rc.req, nil) // before pc might return to idle pool
  2102  			alive = alive &&
  2103  				bodyEOF &&
  2104  				!pc.sawEOF &&
  2105  				pc.wroteRequest() &&
  2106  				tryPutIdleConn(trace)
  2107  			if bodyEOF {
  2108  				eofc <- struct{}{}
  2109  			}
  2110  		case <-rc.req.Cancel:
  2111  			alive = false
  2112  			pc.t.CancelRequest(rc.req)
  2113  		case <-rc.req.Context().Done():
  2114  			alive = false
  2115  			pc.t.cancelRequest(rc.req, rc.req.Context().Err())
  2116  		case <-pc.closech:
  2117  			alive = false
  2118  		}
  2119  
  2120  		testHookReadLoopBeforeNextRead()
  2121  	}
  2122  }
  2123  
  2124  func (pc *persistConn) readLoopPeekFailLocked(peekErr error) {
  2125  	if pc.closed != nil {
  2126  		return
  2127  	}
  2128  	if n := pc.br.Buffered(); n > 0 {
  2129  		buf, _ := pc.br.Peek(n)
  2130  		if is408Message(buf) {
  2131  			pc.closeLocked(errServerClosedIdle)
  2132  			return
  2133  		} else {
  2134  			log.Printf("Unsolicited response received on idle HTTP channel starting with %q; err=%v", buf, peekErr)
  2135  		}
  2136  	}
  2137  	if peekErr == io.EOF {
  2138  		// common case.
  2139  		pc.closeLocked(errServerClosedIdle)
  2140  	} else {
  2141  		pc.closeLocked(fmt.Errorf("readLoopPeekFailLocked: %v", peekErr))
  2142  	}
  2143  }
  2144  
  2145  // is408Message reports whether buf has the prefix of an
  2146  // HTTP 408 Request Timeout response.
  2147  // See golang.org/issue/32310.
  2148  func is408Message(buf []byte) bool {
  2149  	if len(buf) < len("HTTP/1.x 408") {
  2150  		return false
  2151  	}
  2152  	if string(buf[:7]) != "HTTP/1." {
  2153  		return false
  2154  	}
  2155  	return string(buf[8:12]) == " 408"
  2156  }
  2157  
  2158  // readResponse reads an HTTP response (or two, in the case of "Expect:
  2159  // 100-continue") from the server. It returns the final non-100 one.
  2160  // trace is optional.
  2161  func (pc *persistConn) readResponse(rc requestAndChan, trace *httptrace.ClientTrace) (resp *Response, err error) {
  2162  	if trace != nil && trace.GotFirstResponseByte != nil {
  2163  		if peek, err := pc.br.Peek(1); err == nil && len(peek) == 1 {
  2164  			trace.GotFirstResponseByte()
  2165  		}
  2166  	}
  2167  	num1xx := 0               // number of informational 1xx headers received
  2168  	const max1xxResponses = 5 // arbitrary bound on number of informational responses
  2169  
  2170  	continueCh := rc.continueCh
  2171  	for {
  2172  		resp, err = ReadResponse(pc.br, rc.req)
  2173  		if err != nil {
  2174  			return
  2175  		}
  2176  		resCode := resp.StatusCode
  2177  		if continueCh != nil {
  2178  			if resCode == 100 {
  2179  				if trace != nil && trace.Got100Continue != nil {
  2180  					trace.Got100Continue()
  2181  				}
  2182  				continueCh <- struct{}{}
  2183  				continueCh = nil
  2184  			} else if resCode >= 200 {
  2185  				close(continueCh)
  2186  				continueCh = nil
  2187  			}
  2188  		}
  2189  		is1xx := 100 <= resCode && resCode <= 199
  2190  		// treat 101 as a terminal status, see issue 26161
  2191  		is1xxNonTerminal := is1xx && resCode != StatusSwitchingProtocols
  2192  		if is1xxNonTerminal {
  2193  			num1xx++
  2194  			if num1xx > max1xxResponses {
  2195  				return nil, errors.New("net/http: too many 1xx informational responses")
  2196  			}
  2197  			pc.readLimit = pc.maxHeaderResponseSize() // reset the limit
  2198  			if trace != nil && trace.Got1xxResponse != nil {
  2199  				if err := trace.Got1xxResponse(resCode, textproto.MIMEHeader(resp.Header)); err != nil {
  2200  					return nil, err
  2201  				}
  2202  			}
  2203  			continue
  2204  		}
  2205  		break
  2206  	}
  2207  	if resp.isProtocolSwitch() {
  2208  		resp.Body = newReadWriteCloserBody(pc.br, pc.conn)
  2209  	}
  2210  
  2211  	resp.TLS = pc.tlsState
  2212  	return
  2213  }
  2214  
  2215  // waitForContinue returns the function to block until
  2216  // any response, timeout or connection close. After any of them,
  2217  // the function returns a bool which indicates if the body should be sent.
  2218  func (pc *persistConn) waitForContinue(continueCh <-chan struct{}) func() bool {
  2219  	if continueCh == nil {
  2220  		return nil
  2221  	}
  2222  	return func() bool {
  2223  		timer := time.NewTimer(pc.t.ExpectContinueTimeout)
  2224  		defer timer.Stop()
  2225  
  2226  		select {
  2227  		case _, ok := <-continueCh:
  2228  			return ok
  2229  		case <-timer.C:
  2230  			return true
  2231  		case <-pc.closech:
  2232  			return false
  2233  		}
  2234  	}
  2235  }
  2236  
  2237  func newReadWriteCloserBody(br *bufio.Reader, rwc io.ReadWriteCloser) io.ReadWriteCloser {
  2238  	body := &readWriteCloserBody{ReadWriteCloser: rwc}
  2239  	if br.Buffered() != 0 {
  2240  		body.br = br
  2241  	}
  2242  	return body
  2243  }
  2244  
  2245  // readWriteCloserBody is the Response.Body type used when we want to
  2246  // give users write access to the Body through the underlying
  2247  // connection (TCP, unless using custom dialers). This is then
  2248  // the concrete type for a Response.Body on the 101 Switching
  2249  // Protocols response, as used by WebSockets, h2c, etc.
  2250  type readWriteCloserBody struct {
  2251  	br *bufio.Reader // used until empty
  2252  	io.ReadWriteCloser
  2253  }
  2254  
  2255  func (b *readWriteCloserBody) Read(p []byte) (n int, err error) {
  2256  	if b.br != nil {
  2257  		if n := b.br.Buffered(); len(p) > n {
  2258  			p = p[:n]
  2259  		}
  2260  		n, err = b.br.Read(p)
  2261  		if b.br.Buffered() == 0 {
  2262  			b.br = nil
  2263  		}
  2264  		return n, err
  2265  	}
  2266  	return b.ReadWriteCloser.Read(p)
  2267  }
  2268  
  2269  // nothingWrittenError wraps a write errors which ended up writing zero bytes.
  2270  type nothingWrittenError struct {
  2271  	error
  2272  }
  2273  
  2274  func (pc *persistConn) writeLoop() {
  2275  	defer close(pc.writeLoopDone)
  2276  	for {
  2277  		select {
  2278  		case wr := <-pc.writech:
  2279  			startBytesWritten := pc.nwrite
  2280  			err := wr.req.Request.write(pc.bw, pc.isProxy, wr.req.extra, pc.waitForContinue(wr.continueCh))
  2281  			if bre, ok := err.(requestBodyReadError); ok {
  2282  				err = bre.error
  2283  				// Errors reading from the user's
  2284  				// Request.Body are high priority.
  2285  				// Set it here before sending on the
  2286  				// channels below or calling
  2287  				// pc.close() which tears town
  2288  				// connections and causes other
  2289  				// errors.
  2290  				wr.req.setError(err)
  2291  			}
  2292  			if err == nil {
  2293  				err = pc.bw.Flush()
  2294  			}
  2295  			if err != nil {
  2296  				wr.req.Request.closeBody()
  2297  				if pc.nwrite == startBytesWritten {
  2298  					err = nothingWrittenError{err}
  2299  				}
  2300  			}
  2301  			pc.writeErrCh <- err // to the body reader, which might recycle us
  2302  			wr.ch <- err         // to the roundTrip function
  2303  			if err != nil {
  2304  				pc.close(err)
  2305  				return
  2306  			}
  2307  		case <-pc.closech:
  2308  			return
  2309  		}
  2310  	}
  2311  }
  2312  
  2313  // maxWriteWaitBeforeConnReuse is how long the a Transport RoundTrip
  2314  // will wait to see the Request's Body.Write result after getting a
  2315  // response from the server. See comments in (*persistConn).wroteRequest.
  2316  const maxWriteWaitBeforeConnReuse = 50 * time.Millisecond
  2317  
  2318  // wroteRequest is a check before recycling a connection that the previous write
  2319  // (from writeLoop above) happened and was successful.
  2320  func (pc *persistConn) wroteRequest() bool {
  2321  	select {
  2322  	case err := <-pc.writeErrCh:
  2323  		// Common case: the write happened well before the response, so
  2324  		// avoid creating a timer.
  2325  		return err == nil
  2326  	default:
  2327  		// Rare case: the request was written in writeLoop above but
  2328  		// before it could send to pc.writeErrCh, the reader read it
  2329  		// all, processed it, and called us here. In this case, give the
  2330  		// write goroutine a bit of time to finish its send.
  2331  		//
  2332  		// Less rare case: We also get here in the legitimate case of
  2333  		// Issue 7569, where the writer is still writing (or stalled),
  2334  		// but the server has already replied. In this case, we don't
  2335  		// want to wait too long, and we want to return false so this
  2336  		// connection isn't re-used.
  2337  		t := time.NewTimer(maxWriteWaitBeforeConnReuse)
  2338  		defer t.Stop()
  2339  		select {
  2340  		case err := <-pc.writeErrCh:
  2341  			return err == nil
  2342  		case <-t.C:
  2343  			return false
  2344  		}
  2345  	}
  2346  }
  2347  
  2348  // responseAndError is how the goroutine reading from an HTTP/1 server
  2349  // communicates with the goroutine doing the RoundTrip.
  2350  type responseAndError struct {
  2351  	res *Response // else use this response (see res method)
  2352  	err error
  2353  }
  2354  
  2355  type requestAndChan struct {
  2356  	req *Request
  2357  	ch  chan responseAndError // unbuffered; always send in select on callerGone
  2358  
  2359  	// whether the Transport (as opposed to the user client code)
  2360  	// added the Accept-Encoding gzip header. If the Transport
  2361  	// set it, only then do we transparently decode the gzip.
  2362  	addedGzip bool
  2363  
  2364  	// Optional blocking chan for Expect: 100-continue (for send).
  2365  	// If the request has an "Expect: 100-continue" header and
  2366  	// the server responds 100 Continue, readLoop send a value
  2367  	// to writeLoop via this chan.
  2368  	continueCh chan<- struct{}
  2369  
  2370  	callerGone <-chan struct{} // closed when roundTrip caller has returned
  2371  }
  2372  
  2373  // A writeRequest is sent by the readLoop's goroutine to the
  2374  // writeLoop's goroutine to write a request while the read loop
  2375  // concurrently waits on both the write response and the server's
  2376  // reply.
  2377  type writeRequest struct {
  2378  	req *transportRequest
  2379  	ch  chan<- error
  2380  
  2381  	// Optional blocking chan for Expect: 100-continue (for receive).
  2382  	// If not nil, writeLoop blocks sending request body until
  2383  	// it receives from this chan.
  2384  	continueCh <-chan struct{}
  2385  }
  2386  
  2387  type httpError struct {
  2388  	err     string
  2389  	timeout bool
  2390  }
  2391  
  2392  func (e *httpError) Error() string   { return e.err }
  2393  func (e *httpError) Timeout() bool   { return e.timeout }
  2394  func (e *httpError) Temporary() bool { return true }
  2395  
  2396  var errTimeout error = &httpError{err: "net/http: timeout awaiting response headers", timeout: true}
  2397  
  2398  // errRequestCanceled is set to be identical to the one from h2 to facilitate
  2399  // testing.
  2400  var errRequestCanceled = http2errRequestCanceled
  2401  var errRequestCanceledConn = errors.New("net/http: request canceled while waiting for connection") // TODO: unify?
  2402  
  2403  func nop() {}
  2404  
  2405  // testHooks. Always non-nil.
  2406  var (
  2407  	testHookEnterRoundTrip   = nop
  2408  	testHookWaitResLoop      = nop
  2409  	testHookRoundTripRetried = nop
  2410  	testHookPrePendingDial   = nop
  2411  	testHookPostPendingDial  = nop
  2412  
  2413  	testHookMu                     sync.Locker = fakeLocker{} // guards following
  2414  	testHookReadLoopBeforeNextRead             = nop
  2415  )
  2416  
  2417  func (pc *persistConn) roundTrip(req *transportRequest) (resp *Response, err error) {
  2418  	testHookEnterRoundTrip()
  2419  	if !pc.t.replaceReqCanceler(req.Request, pc.cancelRequest) {
  2420  		pc.t.putOrCloseIdleConn(pc)
  2421  		return nil, errRequestCanceled
  2422  	}
  2423  	pc.mu.Lock()
  2424  	pc.numExpectedResponses++
  2425  	headerFn := pc.mutateHeaderFunc
  2426  	pc.mu.Unlock()
  2427  
  2428  	if headerFn != nil {
  2429  		headerFn(req.extraHeaders())
  2430  	}
  2431  
  2432  	// Ask for a compressed version if the caller didn't set their
  2433  	// own value for Accept-Encoding. We only attempt to
  2434  	// uncompress the gzip stream if we were the layer that
  2435  	// requested it.
  2436  	requestedGzip := false
  2437  	if !pc.t.DisableCompression &&
  2438  		req.Header.Get("Accept-Encoding") == "" &&
  2439  		req.Header.Get("Range") == "" &&
  2440  		req.Method != "HEAD" {
  2441  		// Request gzip only, not deflate. Deflate is ambiguous and
  2442  		// not as universally supported anyway.
  2443  		// See: https://zlib.net/zlib_faq.html#faq39
  2444  		//
  2445  		// Note that we don't request this for HEAD requests,
  2446  		// due to a bug in nginx:
  2447  		//   https://trac.nginx.org/nginx/ticket/358
  2448  		//   https://golang.org/issue/5522
  2449  		//
  2450  		// We don't request gzip if the request is for a range, since
  2451  		// auto-decoding a portion of a gzipped document will just fail
  2452  		// anyway. See https://golang.org/issue/8923
  2453  		requestedGzip = true
  2454  		req.extraHeaders().Set("Accept-Encoding", "gzip")
  2455  	}
  2456  
  2457  	var continueCh chan struct{}
  2458  	if req.ProtoAtLeast(1, 1) && req.Body != nil && req.expectsContinue() {
  2459  		continueCh = make(chan struct{}, 1)
  2460  	}
  2461  
  2462  	if pc.t.DisableKeepAlives && !req.wantsClose() {
  2463  		req.extraHeaders().Set("Connection", "close")
  2464  	}
  2465  
  2466  	gone := make(chan struct{})
  2467  	defer close(gone)
  2468  
  2469  	defer func() {
  2470  		if err != nil {
  2471  			pc.t.setReqCanceler(req.Request, nil)
  2472  		}
  2473  	}()
  2474  
  2475  	const debugRoundTrip = false
  2476  
  2477  	// Write the request concurrently with waiting for a response,
  2478  	// in case the server decides to reply before reading our full
  2479  	// request body.
  2480  	startBytesWritten := pc.nwrite
  2481  	writeErrCh := make(chan error, 1)
  2482  	pc.writech <- writeRequest{req, writeErrCh, continueCh}
  2483  
  2484  	resc := make(chan responseAndError)
  2485  	pc.reqch <- requestAndChan{
  2486  		req:        req.Request,
  2487  		ch:         resc,
  2488  		addedGzip:  requestedGzip,
  2489  		continueCh: continueCh,
  2490  		callerGone: gone,
  2491  	}
  2492  
  2493  	var respHeaderTimer <-chan time.Time
  2494  	cancelChan := req.Request.Cancel
  2495  	ctxDoneChan := req.Context().Done()
  2496  	for {
  2497  		testHookWaitResLoop()
  2498  		select {
  2499  		case err := <-writeErrCh:
  2500  			if debugRoundTrip {
  2501  				req.logf("writeErrCh resv: %T/%#v", err, err)
  2502  			}
  2503  			if err != nil {
  2504  				pc.close(fmt.Errorf("write error: %v", err))
  2505  				return nil, pc.mapRoundTripError(req, startBytesWritten, err)
  2506  			}
  2507  			if d := pc.t.ResponseHeaderTimeout; d > 0 {
  2508  				if debugRoundTrip {
  2509  					req.logf("starting timer for %v", d)
  2510  				}
  2511  				timer := time.NewTimer(d)
  2512  				defer timer.Stop() // prevent leaks
  2513  				respHeaderTimer = timer.C
  2514  			}
  2515  		case <-pc.closech:
  2516  			if debugRoundTrip {
  2517  				req.logf("closech recv: %T %#v", pc.closed, pc.closed)
  2518  			}
  2519  			return nil, pc.mapRoundTripError(req, startBytesWritten, pc.closed)
  2520  		case <-respHeaderTimer:
  2521  			if debugRoundTrip {
  2522  				req.logf("timeout waiting for response headers.")
  2523  			}
  2524  			pc.close(errTimeout)
  2525  			return nil, errTimeout
  2526  		case re := <-resc:
  2527  			if (re.res == nil) == (re.err == nil) {
  2528  				panic(fmt.Sprintf("internal error: exactly one of res or err should be set; nil=%v", re.res == nil))
  2529  			}
  2530  			if debugRoundTrip {
  2531  				req.logf("resc recv: %p, %T/%#v", re.res, re.err, re.err)
  2532  			}
  2533  			if re.err != nil {
  2534  				return nil, pc.mapRoundTripError(req, startBytesWritten, re.err)
  2535  			}
  2536  			return re.res, nil
  2537  		case <-cancelChan:
  2538  			pc.t.CancelRequest(req.Request)
  2539  			cancelChan = nil
  2540  		case <-ctxDoneChan:
  2541  			pc.t.cancelRequest(req.Request, req.Context().Err())
  2542  			cancelChan = nil
  2543  			ctxDoneChan = nil
  2544  		}
  2545  	}
  2546  }
  2547  
  2548  // tLogKey is a context WithValue key for test debugging contexts containing
  2549  // a t.Logf func. See export_test.go's Request.WithT method.
  2550  type tLogKey struct{}
  2551  
  2552  func (tr *transportRequest) logf(format string, args ...interface{}) {
  2553  	if logf, ok := tr.Request.Context().Value(tLogKey{}).(func(string, ...interface{})); ok {
  2554  		logf(time.Now().Format(time.RFC3339Nano)+": "+format, args...)
  2555  	}
  2556  }
  2557  
  2558  // markReused marks this connection as having been successfully used for a
  2559  // request and response.
  2560  func (pc *persistConn) markReused() {
  2561  	pc.mu.Lock()
  2562  	pc.reused = true
  2563  	pc.mu.Unlock()
  2564  }
  2565  
  2566  // close closes the underlying TCP connection and closes
  2567  // the pc.closech channel.
  2568  //
  2569  // The provided err is only for testing and debugging; in normal
  2570  // circumstances it should never be seen by users.
  2571  func (pc *persistConn) close(err error) {
  2572  	pc.mu.Lock()
  2573  	defer pc.mu.Unlock()
  2574  	pc.closeLocked(err)
  2575  }
  2576  
  2577  func (pc *persistConn) closeLocked(err error) {
  2578  	if err == nil {
  2579  		panic("nil error")
  2580  	}
  2581  	pc.broken = true
  2582  	if pc.closed == nil {
  2583  		pc.closed = err
  2584  		pc.t.decConnsPerHost(pc.cacheKey)
  2585  		// Close HTTP/1 (pc.alt == nil) connection.
  2586  		// HTTP/2 closes its connection itself.
  2587  		if pc.alt == nil {
  2588  			if err != errCallerOwnsConn {
  2589  				pc.conn.Close()
  2590  			}
  2591  			close(pc.closech)
  2592  		}
  2593  	}
  2594  	pc.mutateHeaderFunc = nil
  2595  }
  2596  
  2597  var portMap = map[string]string{
  2598  	"http":   "80",
  2599  	"https":  "443",
  2600  	"socks5": "1080",
  2601  }
  2602  
  2603  // canonicalAddr returns url.Host but always with a ":port" suffix
  2604  func canonicalAddr(url *url.URL) string {
  2605  	addr := url.Hostname()
  2606  	if v, err := idnaASCII(addr); err == nil {
  2607  		addr = v
  2608  	}
  2609  	port := url.Port()
  2610  	if port == "" {
  2611  		port = portMap[url.Scheme]
  2612  	}
  2613  	return net.JoinHostPort(addr, port)
  2614  }
  2615  
  2616  // bodyEOFSignal is used by the HTTP/1 transport when reading response
  2617  // bodies to make sure we see the end of a response body before
  2618  // proceeding and reading on the connection again.
  2619  //
  2620  // It wraps a ReadCloser but runs fn (if non-nil) at most
  2621  // once, right before its final (error-producing) Read or Close call
  2622  // returns. fn should return the new error to return from Read or Close.
  2623  //
  2624  // If earlyCloseFn is non-nil and Close is called before io.EOF is
  2625  // seen, earlyCloseFn is called instead of fn, and its return value is
  2626  // the return value from Close.
  2627  type bodyEOFSignal struct {
  2628  	body         io.ReadCloser
  2629  	mu           sync.Mutex        // guards following 4 fields
  2630  	closed       bool              // whether Close has been called
  2631  	rerr         error             // sticky Read error
  2632  	fn           func(error) error // err will be nil on Read io.EOF
  2633  	earlyCloseFn func() error      // optional alt Close func used if io.EOF not seen
  2634  }
  2635  
  2636  var errReadOnClosedResBody = errors.New("http: read on closed response body")
  2637  
  2638  func (es *bodyEOFSignal) Read(p []byte) (n int, err error) {
  2639  	es.mu.Lock()
  2640  	closed, rerr := es.closed, es.rerr
  2641  	es.mu.Unlock()
  2642  	if closed {
  2643  		return 0, errReadOnClosedResBody
  2644  	}
  2645  	if rerr != nil {
  2646  		return 0, rerr
  2647  	}
  2648  
  2649  	n, err = es.body.Read(p)
  2650  	if err != nil {
  2651  		es.mu.Lock()
  2652  		defer es.mu.Unlock()
  2653  		if es.rerr == nil {
  2654  			es.rerr = err
  2655  		}
  2656  		err = es.condfn(err)
  2657  	}
  2658  	return
  2659  }
  2660  
  2661  func (es *bodyEOFSignal) Close() error {
  2662  	es.mu.Lock()
  2663  	defer es.mu.Unlock()
  2664  	if es.closed {
  2665  		return nil
  2666  	}
  2667  	es.closed = true
  2668  	if es.earlyCloseFn != nil && es.rerr != io.EOF {
  2669  		return es.earlyCloseFn()
  2670  	}
  2671  	err := es.body.Close()
  2672  	return es.condfn(err)
  2673  }
  2674  
  2675  // caller must hold es.mu.
  2676  func (es *bodyEOFSignal) condfn(err error) error {
  2677  	if es.fn == nil {
  2678  		return err
  2679  	}
  2680  	err = es.fn(err)
  2681  	es.fn = nil
  2682  	return err
  2683  }
  2684  
  2685  // gzipReader wraps a response body so it can lazily
  2686  // call gzip.NewReader on the first call to Read
  2687  type gzipReader struct {
  2688  	body *bodyEOFSignal // underlying HTTP/1 response body framing
  2689  	zr   *gzip.Reader   // lazily-initialized gzip reader
  2690  	zerr error          // any error from gzip.NewReader; sticky
  2691  }
  2692  
  2693  func (gz *gzipReader) Read(p []byte) (n int, err error) {
  2694  	if gz.zr == nil {
  2695  		if gz.zerr == nil {
  2696  			gz.zr, gz.zerr = gzip.NewReader(gz.body)
  2697  		}
  2698  		if gz.zerr != nil {
  2699  			return 0, gz.zerr
  2700  		}
  2701  	}
  2702  
  2703  	gz.body.mu.Lock()
  2704  	if gz.body.closed {
  2705  		err = errReadOnClosedResBody
  2706  	}
  2707  	gz.body.mu.Unlock()
  2708  
  2709  	if err != nil {
  2710  		return 0, err
  2711  	}
  2712  	return gz.zr.Read(p)
  2713  }
  2714  
  2715  func (gz *gzipReader) Close() error {
  2716  	return gz.body.Close()
  2717  }
  2718  
  2719  type tlsHandshakeTimeoutError struct{}
  2720  
  2721  func (tlsHandshakeTimeoutError) Timeout() bool   { return true }
  2722  func (tlsHandshakeTimeoutError) Temporary() bool { return true }
  2723  func (tlsHandshakeTimeoutError) Error() string   { return "net/http: TLS handshake timeout" }
  2724  
  2725  // fakeLocker is a sync.Locker which does nothing. It's used to guard
  2726  // test-only fields when not under test, to avoid runtime atomic
  2727  // overhead.
  2728  type fakeLocker struct{}
  2729  
  2730  func (fakeLocker) Lock()   {}
  2731  func (fakeLocker) Unlock() {}
  2732  
  2733  // cloneTLSConfig returns a shallow clone of cfg, or a new zero tls.Config if
  2734  // cfg is nil. This is safe to call even if cfg is in active use by a TLS
  2735  // client or server.
  2736  func cloneTLSConfig(cfg *tls.Config) *tls.Config {
  2737  	if cfg == nil {
  2738  		return &tls.Config{}
  2739  	}
  2740  	return cfg.Clone()
  2741  }
  2742  
  2743  type connLRU struct {
  2744  	ll *list.List // list.Element.Value type is of *persistConn
  2745  	m  map[*persistConn]*list.Element
  2746  }
  2747  
  2748  // add adds pc to the head of the linked list.
  2749  func (cl *connLRU) add(pc *persistConn) {
  2750  	if cl.ll == nil {
  2751  		cl.ll = list.New()
  2752  		cl.m = make(map[*persistConn]*list.Element)
  2753  	}
  2754  	ele := cl.ll.PushFront(pc)
  2755  	if _, ok := cl.m[pc]; ok {
  2756  		panic("persistConn was already in LRU")
  2757  	}
  2758  	cl.m[pc] = ele
  2759  }
  2760  
  2761  func (cl *connLRU) removeOldest() *persistConn {
  2762  	ele := cl.ll.Back()
  2763  	pc := ele.Value.(*persistConn)
  2764  	cl.ll.Remove(ele)
  2765  	delete(cl.m, pc)
  2766  	return pc
  2767  }
  2768  
  2769  // remove removes pc from cl.
  2770  func (cl *connLRU) remove(pc *persistConn) {
  2771  	if ele, ok := cl.m[pc]; ok {
  2772  		cl.ll.Remove(ele)
  2773  		delete(cl.m, pc)
  2774  	}
  2775  }
  2776  
  2777  // len returns the number of items in the cache.
  2778  func (cl *connLRU) len() int {
  2779  	return len(cl.m)
  2780  }
  2781  

View as plain text