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

View as plain text