Source file src/net/http/transport.go

Documentation: net/http

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

View as plain text