github.com/ooni/oohttp@v0.7.2/transport.go (about)

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