...

Source file src/net/http/transport.go

Documentation: net/http

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

View as plain text