github.com/miolini/go@v0.0.0-20160405192216-fca68c8cb408/src/net/http/transport.go (about)

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // HTTP client implementation. See RFC 2616.
     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  	"crypto/tls"
    16  	"errors"
    17  	"fmt"
    18  	"io"
    19  	"log"
    20  	"net"
    21  	"net/url"
    22  	"os"
    23  	"strings"
    24  	"sync"
    25  	"time"
    26  )
    27  
    28  // DefaultTransport is the default implementation of Transport and is
    29  // used by DefaultClient. It establishes network connections as needed
    30  // and caches them for reuse by subsequent calls. It uses HTTP proxies
    31  // as directed by the $HTTP_PROXY and $NO_PROXY (or $http_proxy and
    32  // $no_proxy) environment variables.
    33  var DefaultTransport RoundTripper = &Transport{
    34  	Proxy: ProxyFromEnvironment,
    35  	Dial: (&net.Dialer{
    36  		Timeout:   30 * time.Second,
    37  		KeepAlive: 30 * time.Second,
    38  	}).Dial,
    39  	TLSHandshakeTimeout:   10 * time.Second,
    40  	ExpectContinueTimeout: 1 * time.Second,
    41  }
    42  
    43  // DefaultMaxIdleConnsPerHost is the default value of Transport's
    44  // MaxIdleConnsPerHost.
    45  const DefaultMaxIdleConnsPerHost = 2
    46  
    47  // Transport is an implementation of RoundTripper that supports HTTP,
    48  // HTTPS, and HTTP proxies (for either HTTP or HTTPS with CONNECT).
    49  //
    50  // By default, Transport caches connections for future re-use.
    51  // This may leave many open connections when accessing many hosts.
    52  // This behavior can be managed using Transport's CloseIdleConnections method
    53  // and the MaxIdleConnsPerHost and DisableKeepAlives fields.
    54  //
    55  // Transports should be reused instead of created as needed.
    56  // Transports are safe for concurrent use by multiple goroutines.
    57  //
    58  // A Transport is a low-level primitive for making HTTP and HTTPS requests.
    59  // For high-level functionality, such as cookies and redirects, see Client.
    60  //
    61  // Transport uses HTTP/1.1 for HTTP URLs and either HTTP/1.1 or HTTP/2
    62  // for HTTPS URLs, depending on whether the server supports HTTP/2.
    63  // See the package docs for more about HTTP/2.
    64  type Transport struct {
    65  	idleMu     sync.Mutex
    66  	wantIdle   bool // user has requested to close all idle conns
    67  	idleConn   map[connectMethodKey][]*persistConn
    68  	idleConnCh map[connectMethodKey]chan *persistConn
    69  
    70  	reqMu       sync.Mutex
    71  	reqCanceler map[*Request]func()
    72  
    73  	altMu    sync.RWMutex
    74  	altProto map[string]RoundTripper // nil or map of URI scheme => RoundTripper
    75  
    76  	// Proxy specifies a function to return a proxy for a given
    77  	// Request. If the function returns a non-nil error, the
    78  	// request is aborted with the provided error.
    79  	// If Proxy is nil or returns a nil *URL, no proxy is used.
    80  	Proxy func(*Request) (*url.URL, error)
    81  
    82  	// Dial specifies the dial function for creating unencrypted
    83  	// TCP connections.
    84  	// If Dial is nil, net.Dial is used.
    85  	Dial func(network, addr string) (net.Conn, error)
    86  
    87  	// DialTLS specifies an optional dial function for creating
    88  	// TLS connections for non-proxied HTTPS requests.
    89  	//
    90  	// If DialTLS is nil, Dial and TLSClientConfig are used.
    91  	//
    92  	// If DialTLS is set, the Dial hook is not used for HTTPS
    93  	// requests and the TLSClientConfig and TLSHandshakeTimeout
    94  	// are ignored. The returned net.Conn is assumed to already be
    95  	// past the TLS handshake.
    96  	DialTLS func(network, addr string) (net.Conn, error)
    97  
    98  	// TLSClientConfig specifies the TLS configuration to use with
    99  	// tls.Client. If nil, the default configuration is used.
   100  	TLSClientConfig *tls.Config
   101  
   102  	// TLSHandshakeTimeout specifies the maximum amount of time waiting to
   103  	// wait for a TLS handshake. Zero means no timeout.
   104  	TLSHandshakeTimeout time.Duration
   105  
   106  	// DisableKeepAlives, if true, prevents re-use of TCP connections
   107  	// between different HTTP requests.
   108  	DisableKeepAlives bool
   109  
   110  	// DisableCompression, if true, prevents the Transport from
   111  	// requesting compression with an "Accept-Encoding: gzip"
   112  	// request header when the Request contains no existing
   113  	// Accept-Encoding value. If the Transport requests gzip on
   114  	// its own and gets a gzipped response, it's transparently
   115  	// decoded in the Response.Body. However, if the user
   116  	// explicitly requested gzip it is not automatically
   117  	// uncompressed.
   118  	DisableCompression bool
   119  
   120  	// MaxIdleConnsPerHost, if non-zero, controls the maximum idle
   121  	// (keep-alive) connections to keep per-host. If zero,
   122  	// DefaultMaxIdleConnsPerHost is used.
   123  	MaxIdleConnsPerHost int
   124  
   125  	// ResponseHeaderTimeout, if non-zero, specifies the amount of
   126  	// time to wait for a server's response headers after fully
   127  	// writing the request (including its body, if any). This
   128  	// time does not include the time to read the response body.
   129  	ResponseHeaderTimeout time.Duration
   130  
   131  	// ExpectContinueTimeout, if non-zero, specifies the amount of
   132  	// time to wait for a server's first response headers after fully
   133  	// writing the request headers if the request has an
   134  	// "Expect: 100-continue" header. Zero means no timeout.
   135  	// This time does not include the time to send the request header.
   136  	ExpectContinueTimeout time.Duration
   137  
   138  	// TLSNextProto specifies how the Transport switches to an
   139  	// alternate protocol (such as HTTP/2) after a TLS NPN/ALPN
   140  	// protocol negotiation. If Transport dials an TLS connection
   141  	// with a non-empty protocol name and TLSNextProto contains a
   142  	// map entry for that key (such as "h2"), then the func is
   143  	// called with the request's authority (such as "example.com"
   144  	// or "example.com:1234") and the TLS connection. The function
   145  	// must return a RoundTripper that then handles the request.
   146  	// If TLSNextProto is nil, HTTP/2 support is enabled automatically.
   147  	TLSNextProto map[string]func(authority string, c *tls.Conn) RoundTripper
   148  
   149  	// MaxResponseHeaderBytes specifies a limit on how many
   150  	// response bytes are allowed in the server's response
   151  	// header.
   152  	//
   153  	// Zero means to use a default limit.
   154  	MaxResponseHeaderBytes int64
   155  
   156  	// nextProtoOnce guards initialization of TLSNextProto and
   157  	// h2transport (via onceSetNextProtoDefaults)
   158  	nextProtoOnce sync.Once
   159  	h2transport   *http2Transport // non-nil if http2 wired up
   160  
   161  	// TODO: tunable on global max cached connections
   162  	// TODO: tunable on timeout on cached connections
   163  	// TODO: tunable on max per-host TCP dials in flight (Issue 13957)
   164  }
   165  
   166  // onceSetNextProtoDefaults initializes TLSNextProto.
   167  // It must be called via t.nextProtoOnce.Do.
   168  func (t *Transport) onceSetNextProtoDefaults() {
   169  	if strings.Contains(os.Getenv("GODEBUG"), "http2client=0") {
   170  		return
   171  	}
   172  	if t.TLSNextProto != nil {
   173  		// This is the documented way to disable http2 on a
   174  		// Transport.
   175  		return
   176  	}
   177  	if t.TLSClientConfig != nil {
   178  		// Be conservative for now (for Go 1.6) at least and
   179  		// don't automatically enable http2 if they've
   180  		// specified a custom TLS config. Let them opt-in
   181  		// themselves via http2.ConfigureTransport so we don't
   182  		// surprise them by modifying their tls.Config.
   183  		// Issue 14275.
   184  		return
   185  	}
   186  	if t.ExpectContinueTimeout != 0 && t != DefaultTransport {
   187  		// ExpectContinueTimeout is unsupported in http2, so
   188  		// if they explicitly asked for it (as opposed to just
   189  		// using the DefaultTransport, which sets it), then
   190  		// disable http2 for now.
   191  		//
   192  		// Issue 13851. (and changed in Issue 14391)
   193  		return
   194  	}
   195  	t2, err := http2configureTransport(t)
   196  	if err != nil {
   197  		log.Printf("Error enabling Transport HTTP/2 support: %v", err)
   198  		return
   199  	}
   200  	t.h2transport = t2
   201  
   202  	// Auto-configure the http2.Transport's MaxHeaderListSize from
   203  	// the http.Transport's MaxResponseHeaderBytes. They don't
   204  	// exactly mean the same thing, but they're close.
   205  	//
   206  	// TODO: also add this to x/net/http2.Configure Transport, behind
   207  	// a +build go1.7 build tag:
   208  	if limit1 := t.MaxResponseHeaderBytes; limit1 != 0 && t2.MaxHeaderListSize == 0 {
   209  		const h2max = 1<<32 - 1
   210  		if limit1 >= h2max {
   211  			t2.MaxHeaderListSize = h2max
   212  		} else {
   213  			t2.MaxHeaderListSize = uint32(limit1)
   214  		}
   215  	}
   216  }
   217  
   218  // ProxyFromEnvironment returns the URL of the proxy to use for a
   219  // given request, as indicated by the environment variables
   220  // HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions
   221  // thereof). HTTPS_PROXY takes precedence over HTTP_PROXY for https
   222  // requests.
   223  //
   224  // The environment values may be either a complete URL or a
   225  // "host[:port]", in which case the "http" scheme is assumed.
   226  // An error is returned if the value is a different form.
   227  //
   228  // A nil URL and nil error are returned if no proxy is defined in the
   229  // environment, or a proxy should not be used for the given request,
   230  // as defined by NO_PROXY.
   231  //
   232  // As a special case, if req.URL.Host is "localhost" (with or without
   233  // a port number), then a nil URL and nil error will be returned.
   234  func ProxyFromEnvironment(req *Request) (*url.URL, error) {
   235  	var proxy string
   236  	if req.URL.Scheme == "https" {
   237  		proxy = httpsProxyEnv.Get()
   238  	}
   239  	if proxy == "" {
   240  		proxy = httpProxyEnv.Get()
   241  	}
   242  	if proxy == "" {
   243  		return nil, nil
   244  	}
   245  	if !useProxy(canonicalAddr(req.URL)) {
   246  		return nil, nil
   247  	}
   248  	proxyURL, err := url.Parse(proxy)
   249  	if err != nil || !strings.HasPrefix(proxyURL.Scheme, "http") {
   250  		// proxy was bogus. Try prepending "http://" to it and
   251  		// see if that parses correctly. If not, we fall
   252  		// through and complain about the original one.
   253  		if proxyURL, err := url.Parse("http://" + proxy); err == nil {
   254  			return proxyURL, nil
   255  		}
   256  	}
   257  	if err != nil {
   258  		return nil, fmt.Errorf("invalid proxy address %q: %v", proxy, err)
   259  	}
   260  	return proxyURL, nil
   261  }
   262  
   263  // ProxyURL returns a proxy function (for use in a Transport)
   264  // that always returns the same URL.
   265  func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error) {
   266  	return func(*Request) (*url.URL, error) {
   267  		return fixedURL, nil
   268  	}
   269  }
   270  
   271  // transportRequest is a wrapper around a *Request that adds
   272  // optional extra headers to write.
   273  type transportRequest struct {
   274  	*Request        // original request, not to be mutated
   275  	extra    Header // extra headers to write, or nil
   276  }
   277  
   278  func (tr *transportRequest) extraHeaders() Header {
   279  	if tr.extra == nil {
   280  		tr.extra = make(Header)
   281  	}
   282  	return tr.extra
   283  }
   284  
   285  // RoundTrip implements the RoundTripper interface.
   286  //
   287  // For higher-level HTTP client support (such as handling of cookies
   288  // and redirects), see Get, Post, and the Client type.
   289  func (t *Transport) RoundTrip(req *Request) (*Response, error) {
   290  	t.nextProtoOnce.Do(t.onceSetNextProtoDefaults)
   291  	if req.URL == nil {
   292  		req.closeBody()
   293  		return nil, errors.New("http: nil Request.URL")
   294  	}
   295  	if req.Header == nil {
   296  		req.closeBody()
   297  		return nil, errors.New("http: nil Request.Header")
   298  	}
   299  	scheme := req.URL.Scheme
   300  	isHTTP := scheme == "http" || scheme == "https"
   301  	if isHTTP {
   302  		for k, vv := range req.Header {
   303  			if !validHeaderName(k) {
   304  				return nil, fmt.Errorf("net/http: invalid header field name %q", k)
   305  			}
   306  			for _, v := range vv {
   307  				if !validHeaderValue(v) {
   308  					return nil, fmt.Errorf("net/http: invalid header field value %q for key %v", v, k)
   309  				}
   310  			}
   311  		}
   312  	}
   313  	// TODO(bradfitz): switch to atomic.Value for this map instead of RWMutex
   314  	t.altMu.RLock()
   315  	altRT := t.altProto[scheme]
   316  	t.altMu.RUnlock()
   317  	if altRT != nil {
   318  		if resp, err := altRT.RoundTrip(req); err != ErrSkipAltProtocol {
   319  			return resp, err
   320  		}
   321  	}
   322  	if !isHTTP {
   323  		req.closeBody()
   324  		return nil, &badStringError{"unsupported protocol scheme", scheme}
   325  	}
   326  	if req.Method != "" && !validMethod(req.Method) {
   327  		return nil, fmt.Errorf("net/http: invalid method %q", req.Method)
   328  	}
   329  	if req.URL.Host == "" {
   330  		req.closeBody()
   331  		return nil, errors.New("http: no Host in request URL")
   332  	}
   333  
   334  	for {
   335  		// treq gets modified by roundTrip, so we need to recreate for each retry.
   336  		treq := &transportRequest{Request: req}
   337  		cm, err := t.connectMethodForRequest(treq)
   338  		if err != nil {
   339  			req.closeBody()
   340  			return nil, err
   341  		}
   342  
   343  		// Get the cached or newly-created connection to either the
   344  		// host (for http or https), the http proxy, or the http proxy
   345  		// pre-CONNECTed to https server. In any case, we'll be ready
   346  		// to send it requests.
   347  		pconn, err := t.getConn(req, cm)
   348  		if err != nil {
   349  			t.setReqCanceler(req, nil)
   350  			req.closeBody()
   351  			return nil, err
   352  		}
   353  
   354  		var resp *Response
   355  		if pconn.alt != nil {
   356  			// HTTP/2 path.
   357  			t.setReqCanceler(req, nil) // not cancelable with CancelRequest
   358  			resp, err = pconn.alt.RoundTrip(req)
   359  		} else {
   360  			resp, err = pconn.roundTrip(treq)
   361  		}
   362  		if err == nil {
   363  			return resp, nil
   364  		}
   365  		if err := checkTransportResend(err, req, pconn); err != nil {
   366  			return nil, err
   367  		}
   368  		testHookRoundTripRetried()
   369  	}
   370  }
   371  
   372  // checkTransportResend checks whether a failed HTTP request can be
   373  // resent on a new connection. The non-nil input error is the error from
   374  // roundTrip, which might be wrapped in a beforeRespHeaderError error.
   375  //
   376  // The return value is either nil to retry the request, the provided
   377  // err unmodified, or the unwrapped error inside a
   378  // beforeRespHeaderError.
   379  func checkTransportResend(err error, req *Request, pconn *persistConn) error {
   380  	brhErr, ok := err.(beforeRespHeaderError)
   381  	if !ok {
   382  		return err
   383  	}
   384  	err = brhErr.error // unwrap the custom error in case we return it
   385  	if err != errMissingHost && pconn.isReused() && req.isReplayable() {
   386  		// If we try to reuse a connection that the server is in the process of
   387  		// closing, we may end up successfully writing out our request (or a
   388  		// portion of our request) only to find a connection error when we try to
   389  		// read from (or finish writing to) the socket.
   390  
   391  		// There can be a race between the socket pool checking whether a socket
   392  		// is still connected, receiving the FIN, and sending/reading data on a
   393  		// reused socket. If we receive the FIN between the connectedness check
   394  		// and writing/reading from the socket, we may first learn the socket is
   395  		// disconnected when we get a ERR_SOCKET_NOT_CONNECTED. This will most
   396  		// likely happen when trying to retrieve its IP address. See
   397  		// http://crbug.com/105824 for more details.
   398  
   399  		// We resend a request only if we reused a keep-alive connection and did
   400  		// not yet receive any header data. This automatically prevents an
   401  		// infinite resend loop because we'll run out of the cached keep-alive
   402  		// connections eventually.
   403  		return nil
   404  	}
   405  	return err
   406  }
   407  
   408  // ErrSkipAltProtocol is a sentinel error value defined by Transport.RegisterProtocol.
   409  var ErrSkipAltProtocol = errors.New("net/http: skip alternate protocol")
   410  
   411  // RegisterProtocol registers a new protocol with scheme.
   412  // The Transport will pass requests using the given scheme to rt.
   413  // It is rt's responsibility to simulate HTTP request semantics.
   414  //
   415  // RegisterProtocol can be used by other packages to provide
   416  // implementations of protocol schemes like "ftp" or "file".
   417  //
   418  // If rt.RoundTrip returns ErrSkipAltProtocol, the Transport will
   419  // handle the RoundTrip itself for that one request, as if the
   420  // protocol were not registered.
   421  func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper) {
   422  	t.altMu.Lock()
   423  	defer t.altMu.Unlock()
   424  	if t.altProto == nil {
   425  		t.altProto = make(map[string]RoundTripper)
   426  	}
   427  	if _, exists := t.altProto[scheme]; exists {
   428  		panic("protocol " + scheme + " already registered")
   429  	}
   430  	t.altProto[scheme] = rt
   431  }
   432  
   433  // CloseIdleConnections closes any connections which were previously
   434  // connected from previous requests but are now sitting idle in
   435  // a "keep-alive" state. It does not interrupt any connections currently
   436  // in use.
   437  func (t *Transport) CloseIdleConnections() {
   438  	t.nextProtoOnce.Do(t.onceSetNextProtoDefaults)
   439  	t.idleMu.Lock()
   440  	m := t.idleConn
   441  	t.idleConn = nil
   442  	t.idleConnCh = nil
   443  	t.wantIdle = true
   444  	t.idleMu.Unlock()
   445  	for _, conns := range m {
   446  		for _, pconn := range conns {
   447  			pconn.close(errCloseIdleConns)
   448  		}
   449  	}
   450  	if t2 := t.h2transport; t2 != nil {
   451  		t2.CloseIdleConnections()
   452  	}
   453  }
   454  
   455  // CancelRequest cancels an in-flight request by closing its connection.
   456  // CancelRequest should only be called after RoundTrip has returned.
   457  //
   458  // Deprecated: Use Request.Cancel instead. CancelRequest cannot cancel
   459  // HTTP/2 requests.
   460  func (t *Transport) CancelRequest(req *Request) {
   461  	t.reqMu.Lock()
   462  	cancel := t.reqCanceler[req]
   463  	delete(t.reqCanceler, req)
   464  	t.reqMu.Unlock()
   465  	if cancel != nil {
   466  		cancel()
   467  	}
   468  }
   469  
   470  //
   471  // Private implementation past this point.
   472  //
   473  
   474  var (
   475  	httpProxyEnv = &envOnce{
   476  		names: []string{"HTTP_PROXY", "http_proxy"},
   477  	}
   478  	httpsProxyEnv = &envOnce{
   479  		names: []string{"HTTPS_PROXY", "https_proxy"},
   480  	}
   481  	noProxyEnv = &envOnce{
   482  		names: []string{"NO_PROXY", "no_proxy"},
   483  	}
   484  )
   485  
   486  // envOnce looks up an environment variable (optionally by multiple
   487  // names) once. It mitigates expensive lookups on some platforms
   488  // (e.g. Windows).
   489  type envOnce struct {
   490  	names []string
   491  	once  sync.Once
   492  	val   string
   493  }
   494  
   495  func (e *envOnce) Get() string {
   496  	e.once.Do(e.init)
   497  	return e.val
   498  }
   499  
   500  func (e *envOnce) init() {
   501  	for _, n := range e.names {
   502  		e.val = os.Getenv(n)
   503  		if e.val != "" {
   504  			return
   505  		}
   506  	}
   507  }
   508  
   509  // reset is used by tests
   510  func (e *envOnce) reset() {
   511  	e.once = sync.Once{}
   512  	e.val = ""
   513  }
   514  
   515  func (t *Transport) connectMethodForRequest(treq *transportRequest) (cm connectMethod, err error) {
   516  	cm.targetScheme = treq.URL.Scheme
   517  	cm.targetAddr = canonicalAddr(treq.URL)
   518  	if t.Proxy != nil {
   519  		cm.proxyURL, err = t.Proxy(treq.Request)
   520  	}
   521  	return cm, err
   522  }
   523  
   524  // proxyAuth returns the Proxy-Authorization header to set
   525  // on requests, if applicable.
   526  func (cm *connectMethod) proxyAuth() string {
   527  	if cm.proxyURL == nil {
   528  		return ""
   529  	}
   530  	if u := cm.proxyURL.User; u != nil {
   531  		username := u.Username()
   532  		password, _ := u.Password()
   533  		return "Basic " + basicAuth(username, password)
   534  	}
   535  	return ""
   536  }
   537  
   538  // error values for debugging and testing, not seen by users.
   539  var (
   540  	errKeepAlivesDisabled = errors.New("http: putIdleConn: keep alives disabled")
   541  	errConnBroken         = errors.New("http: putIdleConn: connection is in bad state")
   542  	errWantIdle           = errors.New("http: putIdleConn: CloseIdleConnections was called")
   543  	errTooManyIdle        = errors.New("http: putIdleConn: too many idle connections")
   544  	errCloseIdleConns     = errors.New("http: CloseIdleConnections called")
   545  	errReadLoopExiting    = errors.New("http: persistConn.readLoop exiting")
   546  	errServerClosedIdle   = errors.New("http: server closed idle conn")
   547  )
   548  
   549  func (t *Transport) putOrCloseIdleConn(pconn *persistConn) {
   550  	if err := t.tryPutIdleConn(pconn); err != nil {
   551  		pconn.close(err)
   552  	}
   553  }
   554  
   555  // tryPutIdleConn adds pconn to the list of idle persistent connections awaiting
   556  // a new request.
   557  // If pconn is no longer needed or not in a good state, tryPutIdleConn returns
   558  // an error explaining why it wasn't registered.
   559  // tryPutIdleConn does not close pconn. Use putOrCloseIdleConn instead for that.
   560  func (t *Transport) tryPutIdleConn(pconn *persistConn) error {
   561  	if t.DisableKeepAlives || t.MaxIdleConnsPerHost < 0 {
   562  		return errKeepAlivesDisabled
   563  	}
   564  	if pconn.isBroken() {
   565  		return errConnBroken
   566  	}
   567  	key := pconn.cacheKey
   568  	max := t.MaxIdleConnsPerHost
   569  	if max == 0 {
   570  		max = DefaultMaxIdleConnsPerHost
   571  	}
   572  	pconn.markReused()
   573  
   574  	t.idleMu.Lock()
   575  	defer t.idleMu.Unlock()
   576  
   577  	waitingDialer := t.idleConnCh[key]
   578  	select {
   579  	case waitingDialer <- pconn:
   580  		// We're done with this pconn and somebody else is
   581  		// currently waiting for a conn of this type (they're
   582  		// actively dialing, but this conn is ready
   583  		// first). Chrome calls this socket late binding. See
   584  		// https://insouciant.org/tech/connection-management-in-chromium/
   585  		return nil
   586  	default:
   587  		if waitingDialer != nil {
   588  			// They had populated this, but their dial won
   589  			// first, so we can clean up this map entry.
   590  			delete(t.idleConnCh, key)
   591  		}
   592  	}
   593  	if t.wantIdle {
   594  		return errWantIdle
   595  	}
   596  	if t.idleConn == nil {
   597  		t.idleConn = make(map[connectMethodKey][]*persistConn)
   598  	}
   599  	if len(t.idleConn[key]) >= max {
   600  		return errTooManyIdle
   601  	}
   602  	for _, exist := range t.idleConn[key] {
   603  		if exist == pconn {
   604  			log.Fatalf("dup idle pconn %p in freelist", pconn)
   605  		}
   606  	}
   607  	t.idleConn[key] = append(t.idleConn[key], pconn)
   608  	return nil
   609  }
   610  
   611  // getIdleConnCh returns a channel to receive and return idle
   612  // persistent connection for the given connectMethod.
   613  // It may return nil, if persistent connections are not being used.
   614  func (t *Transport) getIdleConnCh(cm connectMethod) chan *persistConn {
   615  	if t.DisableKeepAlives {
   616  		return nil
   617  	}
   618  	key := cm.key()
   619  	t.idleMu.Lock()
   620  	defer t.idleMu.Unlock()
   621  	t.wantIdle = false
   622  	if t.idleConnCh == nil {
   623  		t.idleConnCh = make(map[connectMethodKey]chan *persistConn)
   624  	}
   625  	ch, ok := t.idleConnCh[key]
   626  	if !ok {
   627  		ch = make(chan *persistConn)
   628  		t.idleConnCh[key] = ch
   629  	}
   630  	return ch
   631  }
   632  
   633  func (t *Transport) getIdleConn(cm connectMethod) (pconn *persistConn) {
   634  	key := cm.key()
   635  	t.idleMu.Lock()
   636  	defer t.idleMu.Unlock()
   637  	if t.idleConn == nil {
   638  		return nil
   639  	}
   640  	for {
   641  		pconns, ok := t.idleConn[key]
   642  		if !ok {
   643  			return nil
   644  		}
   645  		if len(pconns) == 1 {
   646  			pconn = pconns[0]
   647  			delete(t.idleConn, key)
   648  		} else {
   649  			// 2 or more cached connections; pop last
   650  			// TODO: queue?
   651  			pconn = pconns[len(pconns)-1]
   652  			t.idleConn[key] = pconns[:len(pconns)-1]
   653  		}
   654  		if !pconn.isBroken() {
   655  			return
   656  		}
   657  	}
   658  }
   659  
   660  func (t *Transport) setReqCanceler(r *Request, fn func()) {
   661  	t.reqMu.Lock()
   662  	defer t.reqMu.Unlock()
   663  	if t.reqCanceler == nil {
   664  		t.reqCanceler = make(map[*Request]func())
   665  	}
   666  	if fn != nil {
   667  		t.reqCanceler[r] = fn
   668  	} else {
   669  		delete(t.reqCanceler, r)
   670  	}
   671  }
   672  
   673  // replaceReqCanceler replaces an existing cancel function. If there is no cancel function
   674  // for the request, we don't set the function and return false.
   675  // Since CancelRequest will clear the canceler, we can use the return value to detect if
   676  // the request was canceled since the last setReqCancel call.
   677  func (t *Transport) replaceReqCanceler(r *Request, fn func()) bool {
   678  	t.reqMu.Lock()
   679  	defer t.reqMu.Unlock()
   680  	_, ok := t.reqCanceler[r]
   681  	if !ok {
   682  		return false
   683  	}
   684  	if fn != nil {
   685  		t.reqCanceler[r] = fn
   686  	} else {
   687  		delete(t.reqCanceler, r)
   688  	}
   689  	return true
   690  }
   691  
   692  func (t *Transport) dial(network, addr string) (net.Conn, error) {
   693  	if t.Dial != nil {
   694  		c, err := t.Dial(network, addr)
   695  		if c == nil && err == nil {
   696  			err = errors.New("net/http: Transport.Dial hook returned (nil, nil)")
   697  		}
   698  		return c, err
   699  	}
   700  	return net.Dial(network, addr)
   701  }
   702  
   703  // getConn dials and creates a new persistConn to the target as
   704  // specified in the connectMethod. This includes doing a proxy CONNECT
   705  // and/or setting up TLS.  If this doesn't return an error, the persistConn
   706  // is ready to write requests to.
   707  func (t *Transport) getConn(req *Request, cm connectMethod) (*persistConn, error) {
   708  	if pc := t.getIdleConn(cm); pc != nil {
   709  		// set request canceler to some non-nil function so we
   710  		// can detect whether it was cleared between now and when
   711  		// we enter roundTrip
   712  		t.setReqCanceler(req, func() {})
   713  		return pc, nil
   714  	}
   715  
   716  	type dialRes struct {
   717  		pc  *persistConn
   718  		err error
   719  	}
   720  	dialc := make(chan dialRes)
   721  
   722  	// Copy these hooks so we don't race on the postPendingDial in
   723  	// the goroutine we launch. Issue 11136.
   724  	testHookPrePendingDial := testHookPrePendingDial
   725  	testHookPostPendingDial := testHookPostPendingDial
   726  
   727  	handlePendingDial := func() {
   728  		testHookPrePendingDial()
   729  		go func() {
   730  			if v := <-dialc; v.err == nil {
   731  				t.putOrCloseIdleConn(v.pc)
   732  			}
   733  			testHookPostPendingDial()
   734  		}()
   735  	}
   736  
   737  	cancelc := make(chan struct{})
   738  	t.setReqCanceler(req, func() { close(cancelc) })
   739  
   740  	go func() {
   741  		pc, err := t.dialConn(cm)
   742  		dialc <- dialRes{pc, err}
   743  	}()
   744  
   745  	idleConnCh := t.getIdleConnCh(cm)
   746  	select {
   747  	case v := <-dialc:
   748  		// Our dial finished.
   749  		return v.pc, v.err
   750  	case pc := <-idleConnCh:
   751  		// Another request finished first and its net.Conn
   752  		// became available before our dial. Or somebody
   753  		// else's dial that they didn't use.
   754  		// But our dial is still going, so give it away
   755  		// when it finishes:
   756  		handlePendingDial()
   757  		return pc, nil
   758  	case <-req.Cancel:
   759  		handlePendingDial()
   760  		return nil, errRequestCanceledConn
   761  	case <-req.Context().Done():
   762  		handlePendingDial()
   763  		return nil, errRequestCanceledConn
   764  	case <-cancelc:
   765  		handlePendingDial()
   766  		return nil, errRequestCanceledConn
   767  	}
   768  }
   769  
   770  func (t *Transport) dialConn(cm connectMethod) (*persistConn, error) {
   771  	pconn := &persistConn{
   772  		t:          t,
   773  		cacheKey:   cm.key(),
   774  		reqch:      make(chan requestAndChan, 1),
   775  		writech:    make(chan writeRequest, 1),
   776  		closech:    make(chan struct{}),
   777  		writeErrCh: make(chan error, 1),
   778  	}
   779  	tlsDial := t.DialTLS != nil && cm.targetScheme == "https" && cm.proxyURL == nil
   780  	if tlsDial {
   781  		var err error
   782  		pconn.conn, err = t.DialTLS("tcp", cm.addr())
   783  		if err != nil {
   784  			return nil, err
   785  		}
   786  		if pconn.conn == nil {
   787  			return nil, errors.New("net/http: Transport.DialTLS returned (nil, nil)")
   788  		}
   789  		if tc, ok := pconn.conn.(*tls.Conn); ok {
   790  			// Handshake here, in case DialTLS didn't. TLSNextProto below
   791  			// depends on it for knowing the connection state.
   792  			if err := tc.Handshake(); err != nil {
   793  				go pconn.conn.Close()
   794  				return nil, err
   795  			}
   796  			cs := tc.ConnectionState()
   797  			pconn.tlsState = &cs
   798  		}
   799  	} else {
   800  		conn, err := t.dial("tcp", cm.addr())
   801  		if err != nil {
   802  			if cm.proxyURL != nil {
   803  				err = fmt.Errorf("http: error connecting to proxy %s: %v", cm.proxyURL, err)
   804  			}
   805  			return nil, err
   806  		}
   807  		pconn.conn = conn
   808  	}
   809  
   810  	// Proxy setup.
   811  	switch {
   812  	case cm.proxyURL == nil:
   813  		// Do nothing. Not using a proxy.
   814  	case cm.targetScheme == "http":
   815  		pconn.isProxy = true
   816  		if pa := cm.proxyAuth(); pa != "" {
   817  			pconn.mutateHeaderFunc = func(h Header) {
   818  				h.Set("Proxy-Authorization", pa)
   819  			}
   820  		}
   821  	case cm.targetScheme == "https":
   822  		conn := pconn.conn
   823  		connectReq := &Request{
   824  			Method: "CONNECT",
   825  			URL:    &url.URL{Opaque: cm.targetAddr},
   826  			Host:   cm.targetAddr,
   827  			Header: make(Header),
   828  		}
   829  		if pa := cm.proxyAuth(); pa != "" {
   830  			connectReq.Header.Set("Proxy-Authorization", pa)
   831  		}
   832  		connectReq.Write(conn)
   833  
   834  		// Read response.
   835  		// Okay to use and discard buffered reader here, because
   836  		// TLS server will not speak until spoken to.
   837  		br := bufio.NewReader(conn)
   838  		resp, err := ReadResponse(br, connectReq)
   839  		if err != nil {
   840  			conn.Close()
   841  			return nil, err
   842  		}
   843  		if resp.StatusCode != 200 {
   844  			f := strings.SplitN(resp.Status, " ", 2)
   845  			conn.Close()
   846  			return nil, errors.New(f[1])
   847  		}
   848  	}
   849  
   850  	if cm.targetScheme == "https" && !tlsDial {
   851  		// Initiate TLS and check remote host name against certificate.
   852  		cfg := cloneTLSClientConfig(t.TLSClientConfig)
   853  		if cfg.ServerName == "" {
   854  			cfg.ServerName = cm.tlsHost()
   855  		}
   856  		plainConn := pconn.conn
   857  		tlsConn := tls.Client(plainConn, cfg)
   858  		errc := make(chan error, 2)
   859  		var timer *time.Timer // for canceling TLS handshake
   860  		if d := t.TLSHandshakeTimeout; d != 0 {
   861  			timer = time.AfterFunc(d, func() {
   862  				errc <- tlsHandshakeTimeoutError{}
   863  			})
   864  		}
   865  		go func() {
   866  			err := tlsConn.Handshake()
   867  			if timer != nil {
   868  				timer.Stop()
   869  			}
   870  			errc <- err
   871  		}()
   872  		if err := <-errc; err != nil {
   873  			plainConn.Close()
   874  			return nil, err
   875  		}
   876  		if !cfg.InsecureSkipVerify {
   877  			if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil {
   878  				plainConn.Close()
   879  				return nil, err
   880  			}
   881  		}
   882  		cs := tlsConn.ConnectionState()
   883  		pconn.tlsState = &cs
   884  		pconn.conn = tlsConn
   885  	}
   886  
   887  	if s := pconn.tlsState; s != nil && s.NegotiatedProtocolIsMutual && s.NegotiatedProtocol != "" {
   888  		if next, ok := t.TLSNextProto[s.NegotiatedProtocol]; ok {
   889  			return &persistConn{alt: next(cm.targetAddr, pconn.conn.(*tls.Conn))}, nil
   890  		}
   891  	}
   892  
   893  	pconn.br = bufio.NewReader(pconn)
   894  	pconn.bw = bufio.NewWriter(pconn.conn)
   895  	go pconn.readLoop()
   896  	go pconn.writeLoop()
   897  	return pconn, nil
   898  }
   899  
   900  // useProxy reports whether requests to addr should use a proxy,
   901  // according to the NO_PROXY or no_proxy environment variable.
   902  // addr is always a canonicalAddr with a host and port.
   903  func useProxy(addr string) bool {
   904  	if len(addr) == 0 {
   905  		return true
   906  	}
   907  	host, _, err := net.SplitHostPort(addr)
   908  	if err != nil {
   909  		return false
   910  	}
   911  	if host == "localhost" {
   912  		return false
   913  	}
   914  	if ip := net.ParseIP(host); ip != nil {
   915  		if ip.IsLoopback() {
   916  			return false
   917  		}
   918  	}
   919  
   920  	no_proxy := noProxyEnv.Get()
   921  	if no_proxy == "*" {
   922  		return false
   923  	}
   924  
   925  	addr = strings.ToLower(strings.TrimSpace(addr))
   926  	if hasPort(addr) {
   927  		addr = addr[:strings.LastIndex(addr, ":")]
   928  	}
   929  
   930  	for _, p := range strings.Split(no_proxy, ",") {
   931  		p = strings.ToLower(strings.TrimSpace(p))
   932  		if len(p) == 0 {
   933  			continue
   934  		}
   935  		if hasPort(p) {
   936  			p = p[:strings.LastIndex(p, ":")]
   937  		}
   938  		if addr == p {
   939  			return false
   940  		}
   941  		if p[0] == '.' && (strings.HasSuffix(addr, p) || addr == p[1:]) {
   942  			// no_proxy ".foo.com" matches "bar.foo.com" or "foo.com"
   943  			return false
   944  		}
   945  		if p[0] != '.' && strings.HasSuffix(addr, p) && addr[len(addr)-len(p)-1] == '.' {
   946  			// no_proxy "foo.com" matches "bar.foo.com"
   947  			return false
   948  		}
   949  	}
   950  	return true
   951  }
   952  
   953  // connectMethod is the map key (in its String form) for keeping persistent
   954  // TCP connections alive for subsequent HTTP requests.
   955  //
   956  // A connect method may be of the following types:
   957  //
   958  // Cache key form                Description
   959  // -----------------             -------------------------
   960  // |http|foo.com                 http directly to server, no proxy
   961  // |https|foo.com                https directly to server, no proxy
   962  // http://proxy.com|https|foo.com  http to proxy, then CONNECT to foo.com
   963  // http://proxy.com|http           http to proxy, http to anywhere after that
   964  //
   965  // Note: no support to https to the proxy yet.
   966  //
   967  type connectMethod struct {
   968  	proxyURL     *url.URL // nil for no proxy, else full proxy URL
   969  	targetScheme string   // "http" or "https"
   970  	targetAddr   string   // Not used if proxy + http targetScheme (4th example in table)
   971  }
   972  
   973  func (cm *connectMethod) key() connectMethodKey {
   974  	proxyStr := ""
   975  	targetAddr := cm.targetAddr
   976  	if cm.proxyURL != nil {
   977  		proxyStr = cm.proxyURL.String()
   978  		if cm.targetScheme == "http" {
   979  			targetAddr = ""
   980  		}
   981  	}
   982  	return connectMethodKey{
   983  		proxy:  proxyStr,
   984  		scheme: cm.targetScheme,
   985  		addr:   targetAddr,
   986  	}
   987  }
   988  
   989  // addr returns the first hop "host:port" to which we need to TCP connect.
   990  func (cm *connectMethod) addr() string {
   991  	if cm.proxyURL != nil {
   992  		return canonicalAddr(cm.proxyURL)
   993  	}
   994  	return cm.targetAddr
   995  }
   996  
   997  // tlsHost returns the host name to match against the peer's
   998  // TLS certificate.
   999  func (cm *connectMethod) tlsHost() string {
  1000  	h := cm.targetAddr
  1001  	if hasPort(h) {
  1002  		h = h[:strings.LastIndex(h, ":")]
  1003  	}
  1004  	return h
  1005  }
  1006  
  1007  // connectMethodKey is the map key version of connectMethod, with a
  1008  // stringified proxy URL (or the empty string) instead of a pointer to
  1009  // a URL.
  1010  type connectMethodKey struct {
  1011  	proxy, scheme, addr string
  1012  }
  1013  
  1014  func (k connectMethodKey) String() string {
  1015  	// Only used by tests.
  1016  	return fmt.Sprintf("%s|%s|%s", k.proxy, k.scheme, k.addr)
  1017  }
  1018  
  1019  // persistConn wraps a connection, usually a persistent one
  1020  // (but may be used for non-keep-alive requests as well)
  1021  type persistConn struct {
  1022  	// alt optionally specifies the TLS NextProto RoundTripper.
  1023  	// This is used for HTTP/2 today and future protocols later.
  1024  	// If it's non-nil, the rest of the fields are unused.
  1025  	alt RoundTripper
  1026  
  1027  	t         *Transport
  1028  	cacheKey  connectMethodKey
  1029  	conn      net.Conn
  1030  	tlsState  *tls.ConnectionState
  1031  	br        *bufio.Reader       // from conn
  1032  	bw        *bufio.Writer       // to conn
  1033  	reqch     chan requestAndChan // written by roundTrip; read by readLoop
  1034  	writech   chan writeRequest   // written by roundTrip; read by writeLoop
  1035  	closech   chan struct{}       // closed when conn closed
  1036  	isProxy   bool
  1037  	sawEOF    bool  // whether we've seen EOF from conn; owned by readLoop
  1038  	readLimit int64 // bytes allowed to be read; owned by readLoop
  1039  	// writeErrCh passes the request write error (usually nil)
  1040  	// from the writeLoop goroutine to the readLoop which passes
  1041  	// it off to the res.Body reader, which then uses it to decide
  1042  	// whether or not a connection can be reused. Issue 7569.
  1043  	writeErrCh chan error
  1044  
  1045  	mu                   sync.Mutex // guards following fields
  1046  	numExpectedResponses int
  1047  	closed               error // set non-nil when conn is closed, before closech is closed
  1048  	broken               bool  // an error has happened on this connection; marked broken so it's not reused.
  1049  	canceled             bool  // whether this conn was broken due a CancelRequest
  1050  	reused               bool  // whether conn has had successful request/response and is being reused.
  1051  	// mutateHeaderFunc is an optional func to modify extra
  1052  	// headers on each outbound request before it's written. (the
  1053  	// original Request given to RoundTrip is not modified)
  1054  	mutateHeaderFunc func(Header)
  1055  }
  1056  
  1057  func (pc *persistConn) maxHeaderResponseSize() int64 {
  1058  	if v := pc.t.MaxResponseHeaderBytes; v != 0 {
  1059  		return v
  1060  	}
  1061  	return 10 << 20 // conservative default; same as http2
  1062  }
  1063  
  1064  func (pc *persistConn) Read(p []byte) (n int, err error) {
  1065  	if pc.readLimit <= 0 {
  1066  		return 0, fmt.Errorf("read limit of %d bytes exhausted", pc.maxHeaderResponseSize())
  1067  	}
  1068  	if int64(len(p)) > pc.readLimit {
  1069  		p = p[:pc.readLimit]
  1070  	}
  1071  	n, err = pc.conn.Read(p)
  1072  	if err == io.EOF {
  1073  		pc.sawEOF = true
  1074  	}
  1075  	pc.readLimit -= int64(n)
  1076  	return
  1077  }
  1078  
  1079  // isBroken reports whether this connection is in a known broken state.
  1080  func (pc *persistConn) isBroken() bool {
  1081  	pc.mu.Lock()
  1082  	b := pc.broken
  1083  	pc.mu.Unlock()
  1084  	return b
  1085  }
  1086  
  1087  // isCanceled reports whether this connection was closed due to CancelRequest.
  1088  func (pc *persistConn) isCanceled() bool {
  1089  	pc.mu.Lock()
  1090  	defer pc.mu.Unlock()
  1091  	return pc.canceled
  1092  }
  1093  
  1094  // isReused reports whether this connection is in a known broken state.
  1095  func (pc *persistConn) isReused() bool {
  1096  	pc.mu.Lock()
  1097  	r := pc.reused
  1098  	pc.mu.Unlock()
  1099  	return r
  1100  }
  1101  
  1102  func (pc *persistConn) cancelRequest() {
  1103  	pc.mu.Lock()
  1104  	defer pc.mu.Unlock()
  1105  	pc.canceled = true
  1106  	pc.closeLocked(errRequestCanceled)
  1107  }
  1108  
  1109  func (pc *persistConn) readLoop() {
  1110  	closeErr := errReadLoopExiting // default value, if not changed below
  1111  	defer func() { pc.close(closeErr) }()
  1112  
  1113  	tryPutIdleConn := func() bool {
  1114  		if err := pc.t.tryPutIdleConn(pc); err != nil {
  1115  			closeErr = err
  1116  			return false
  1117  		}
  1118  		return true
  1119  	}
  1120  
  1121  	// eofc is used to block caller goroutines reading from Response.Body
  1122  	// at EOF until this goroutines has (potentially) added the connection
  1123  	// back to the idle pool.
  1124  	eofc := make(chan struct{})
  1125  	defer close(eofc) // unblock reader on errors
  1126  
  1127  	// Read this once, before loop starts. (to avoid races in tests)
  1128  	testHookMu.Lock()
  1129  	testHookReadLoopBeforeNextRead := testHookReadLoopBeforeNextRead
  1130  	testHookMu.Unlock()
  1131  
  1132  	alive := true
  1133  	for alive {
  1134  		pc.readLimit = pc.maxHeaderResponseSize()
  1135  		_, err := pc.br.Peek(1)
  1136  		if err != nil {
  1137  			err = beforeRespHeaderError{err}
  1138  		}
  1139  
  1140  		pc.mu.Lock()
  1141  		if pc.numExpectedResponses == 0 {
  1142  			pc.readLoopPeekFailLocked(err)
  1143  			pc.mu.Unlock()
  1144  			return
  1145  		}
  1146  		pc.mu.Unlock()
  1147  
  1148  		rc := <-pc.reqch
  1149  
  1150  		var resp *Response
  1151  		if err == nil {
  1152  			resp, err = pc.readResponse(rc)
  1153  		}
  1154  
  1155  		if err != nil {
  1156  			if pc.readLimit <= 0 {
  1157  				err = fmt.Errorf("net/http: server response headers exceeded %d bytes; aborted", pc.maxHeaderResponseSize())
  1158  			}
  1159  			// If we won't be able to retry this request later (from the
  1160  			// roundTrip goroutine), mark it as done now.
  1161  			// BEFORE the send on rc.ch, as the client might re-use the
  1162  			// same *Request pointer, and we don't want to set call
  1163  			// t.setReqCanceler from this persistConn while the Transport
  1164  			// potentially spins up a different persistConn for the
  1165  			// caller's subsequent request.
  1166  			if checkTransportResend(err, rc.req, pc) != nil {
  1167  				pc.t.setReqCanceler(rc.req, nil)
  1168  			}
  1169  			select {
  1170  			case rc.ch <- responseAndError{err: err}:
  1171  			case <-rc.callerGone:
  1172  				return
  1173  			}
  1174  			return
  1175  		}
  1176  		pc.readLimit = maxInt64 // effictively no limit for response bodies
  1177  
  1178  		pc.mu.Lock()
  1179  		pc.numExpectedResponses--
  1180  		pc.mu.Unlock()
  1181  
  1182  		hasBody := rc.req.Method != "HEAD" && resp.ContentLength != 0
  1183  
  1184  		if resp.Close || rc.req.Close || resp.StatusCode <= 199 {
  1185  			// Don't do keep-alive on error if either party requested a close
  1186  			// or we get an unexpected informational (1xx) response.
  1187  			// StatusCode 100 is already handled above.
  1188  			alive = false
  1189  		}
  1190  
  1191  		if !hasBody {
  1192  			pc.t.setReqCanceler(rc.req, nil)
  1193  
  1194  			// Put the idle conn back into the pool before we send the response
  1195  			// so if they process it quickly and make another request, they'll
  1196  			// get this same conn. But we use the unbuffered channel 'rc'
  1197  			// to guarantee that persistConn.roundTrip got out of its select
  1198  			// potentially waiting for this persistConn to close.
  1199  			// but after
  1200  			alive = alive &&
  1201  				!pc.sawEOF &&
  1202  				pc.wroteRequest() &&
  1203  				tryPutIdleConn()
  1204  
  1205  			select {
  1206  			case rc.ch <- responseAndError{res: resp}:
  1207  			case <-rc.callerGone:
  1208  				return
  1209  			}
  1210  
  1211  			// Now that they've read from the unbuffered channel, they're safely
  1212  			// out of the select that also waits on this goroutine to die, so
  1213  			// we're allowed to exit now if needed (if alive is false)
  1214  			testHookReadLoopBeforeNextRead()
  1215  			continue
  1216  		}
  1217  
  1218  		waitForBodyRead := make(chan bool, 2)
  1219  		body := &bodyEOFSignal{
  1220  			body: resp.Body,
  1221  			earlyCloseFn: func() error {
  1222  				waitForBodyRead <- false
  1223  				return nil
  1224  
  1225  			},
  1226  			fn: func(err error) error {
  1227  				isEOF := err == io.EOF
  1228  				waitForBodyRead <- isEOF
  1229  				if isEOF {
  1230  					<-eofc // see comment above eofc declaration
  1231  				} else if err != nil && pc.isCanceled() {
  1232  					return errRequestCanceled
  1233  				}
  1234  				return err
  1235  			},
  1236  		}
  1237  
  1238  		resp.Body = body
  1239  		if rc.addedGzip && resp.Header.Get("Content-Encoding") == "gzip" {
  1240  			resp.Body = &gzipReader{body: body}
  1241  			resp.Header.Del("Content-Encoding")
  1242  			resp.Header.Del("Content-Length")
  1243  			resp.ContentLength = -1
  1244  		}
  1245  
  1246  		select {
  1247  		case rc.ch <- responseAndError{res: resp}:
  1248  		case <-rc.callerGone:
  1249  			return
  1250  		}
  1251  
  1252  		// Before looping back to the top of this function and peeking on
  1253  		// the bufio.Reader, wait for the caller goroutine to finish
  1254  		// reading the response body. (or for cancelation or death)
  1255  		select {
  1256  		case bodyEOF := <-waitForBodyRead:
  1257  			pc.t.setReqCanceler(rc.req, nil) // before pc might return to idle pool
  1258  			alive = alive &&
  1259  				bodyEOF &&
  1260  				!pc.sawEOF &&
  1261  				pc.wroteRequest() &&
  1262  				tryPutIdleConn()
  1263  			if bodyEOF {
  1264  				eofc <- struct{}{}
  1265  			}
  1266  		case <-rc.req.Cancel:
  1267  			alive = false
  1268  			pc.t.CancelRequest(rc.req)
  1269  		case <-rc.req.Context().Done():
  1270  			alive = false
  1271  			pc.t.CancelRequest(rc.req)
  1272  		case <-pc.closech:
  1273  			alive = false
  1274  		}
  1275  
  1276  		testHookReadLoopBeforeNextRead()
  1277  	}
  1278  }
  1279  
  1280  func (pc *persistConn) readLoopPeekFailLocked(peekErr error) {
  1281  	if pc.closed != nil {
  1282  		return
  1283  	}
  1284  	if n := pc.br.Buffered(); n > 0 {
  1285  		buf, _ := pc.br.Peek(n)
  1286  		log.Printf("Unsolicited response received on idle HTTP channel starting with %q; err=%v", buf, peekErr)
  1287  	}
  1288  	if peekErr == io.EOF {
  1289  		// common case.
  1290  		pc.closeLocked(errServerClosedIdle)
  1291  	} else {
  1292  		pc.closeLocked(fmt.Errorf("readLoopPeekFailLocked: %v", peekErr))
  1293  	}
  1294  }
  1295  
  1296  // readResponse reads an HTTP response (or two, in the case of "Expect:
  1297  // 100-continue") from the server. It returns the final non-100 one.
  1298  func (pc *persistConn) readResponse(rc requestAndChan) (resp *Response, err error) {
  1299  	resp, err = ReadResponse(pc.br, rc.req)
  1300  	if err != nil {
  1301  		return
  1302  	}
  1303  	if rc.continueCh != nil {
  1304  		if resp.StatusCode == 100 {
  1305  			rc.continueCh <- struct{}{}
  1306  		} else {
  1307  			close(rc.continueCh)
  1308  		}
  1309  	}
  1310  	if resp.StatusCode == 100 {
  1311  		pc.readLimit = pc.maxHeaderResponseSize() // reset the limit
  1312  		resp, err = ReadResponse(pc.br, rc.req)
  1313  		if err != nil {
  1314  			return
  1315  		}
  1316  	}
  1317  	resp.TLS = pc.tlsState
  1318  	return
  1319  }
  1320  
  1321  // waitForContinue returns the function to block until
  1322  // any response, timeout or connection close. After any of them,
  1323  // the function returns a bool which indicates if the body should be sent.
  1324  func (pc *persistConn) waitForContinue(continueCh <-chan struct{}) func() bool {
  1325  	if continueCh == nil {
  1326  		return nil
  1327  	}
  1328  	return func() bool {
  1329  		timer := time.NewTimer(pc.t.ExpectContinueTimeout)
  1330  		defer timer.Stop()
  1331  
  1332  		select {
  1333  		case _, ok := <-continueCh:
  1334  			return ok
  1335  		case <-timer.C:
  1336  			return true
  1337  		case <-pc.closech:
  1338  			return false
  1339  		}
  1340  	}
  1341  }
  1342  
  1343  func (pc *persistConn) writeLoop() {
  1344  	for {
  1345  		select {
  1346  		case wr := <-pc.writech:
  1347  			if pc.isBroken() {
  1348  				wr.ch <- errors.New("http: can't write HTTP request on broken connection")
  1349  				continue
  1350  			}
  1351  			err := wr.req.Request.write(pc.bw, pc.isProxy, wr.req.extra, pc.waitForContinue(wr.continueCh))
  1352  			if err == nil {
  1353  				err = pc.bw.Flush()
  1354  			}
  1355  			if err != nil {
  1356  				pc.markBroken()
  1357  				wr.req.Request.closeBody()
  1358  			}
  1359  			pc.writeErrCh <- err // to the body reader, which might recycle us
  1360  			wr.ch <- err         // to the roundTrip function
  1361  		case <-pc.closech:
  1362  			return
  1363  		}
  1364  	}
  1365  }
  1366  
  1367  // wroteRequest is a check before recycling a connection that the previous write
  1368  // (from writeLoop above) happened and was successful.
  1369  func (pc *persistConn) wroteRequest() bool {
  1370  	select {
  1371  	case err := <-pc.writeErrCh:
  1372  		// Common case: the write happened well before the response, so
  1373  		// avoid creating a timer.
  1374  		return err == nil
  1375  	default:
  1376  		// Rare case: the request was written in writeLoop above but
  1377  		// before it could send to pc.writeErrCh, the reader read it
  1378  		// all, processed it, and called us here. In this case, give the
  1379  		// write goroutine a bit of time to finish its send.
  1380  		//
  1381  		// Less rare case: We also get here in the legitimate case of
  1382  		// Issue 7569, where the writer is still writing (or stalled),
  1383  		// but the server has already replied. In this case, we don't
  1384  		// want to wait too long, and we want to return false so this
  1385  		// connection isn't re-used.
  1386  		select {
  1387  		case err := <-pc.writeErrCh:
  1388  			return err == nil
  1389  		case <-time.After(50 * time.Millisecond):
  1390  			return false
  1391  		}
  1392  	}
  1393  }
  1394  
  1395  // responseAndError is how the goroutine reading from an HTTP/1 server
  1396  // communicates with the goroutine doing the RoundTrip.
  1397  type responseAndError struct {
  1398  	res *Response // else use this response (see res method)
  1399  	err error
  1400  }
  1401  
  1402  type requestAndChan struct {
  1403  	req *Request
  1404  	ch  chan responseAndError // unbuffered; always send in select on callerGone
  1405  
  1406  	// whether the Transport (as opposed to the user client code)
  1407  	// added the Accept-Encoding gzip header. If the Transport
  1408  	// set it, only then do we transparently decode the gzip.
  1409  	addedGzip bool
  1410  
  1411  	// Optional blocking chan for Expect: 100-continue (for send).
  1412  	// If the request has an "Expect: 100-continue" header and
  1413  	// the server responds 100 Continue, readLoop send a value
  1414  	// to writeLoop via this chan.
  1415  	continueCh chan<- struct{}
  1416  
  1417  	callerGone <-chan struct{} // closed when roundTrip caller has returned
  1418  }
  1419  
  1420  // A writeRequest is sent by the readLoop's goroutine to the
  1421  // writeLoop's goroutine to write a request while the read loop
  1422  // concurrently waits on both the write response and the server's
  1423  // reply.
  1424  type writeRequest struct {
  1425  	req *transportRequest
  1426  	ch  chan<- error
  1427  
  1428  	// Optional blocking chan for Expect: 100-continue (for receive).
  1429  	// If not nil, writeLoop blocks sending request body until
  1430  	// it receives from this chan.
  1431  	continueCh <-chan struct{}
  1432  }
  1433  
  1434  type httpError struct {
  1435  	err     string
  1436  	timeout bool
  1437  }
  1438  
  1439  func (e *httpError) Error() string   { return e.err }
  1440  func (e *httpError) Timeout() bool   { return e.timeout }
  1441  func (e *httpError) Temporary() bool { return true }
  1442  
  1443  var errTimeout error = &httpError{err: "net/http: timeout awaiting response headers", timeout: true}
  1444  var errRequestCanceled = errors.New("net/http: request canceled")
  1445  var errRequestCanceledConn = errors.New("net/http: request canceled while waiting for connection") // TODO: unify?
  1446  
  1447  func nop() {}
  1448  
  1449  // testHooks. Always non-nil.
  1450  var (
  1451  	testHookEnterRoundTrip   = nop
  1452  	testHookWaitResLoop      = nop
  1453  	testHookRoundTripRetried = nop
  1454  	testHookPrePendingDial   = nop
  1455  	testHookPostPendingDial  = nop
  1456  
  1457  	testHookMu                     sync.Locker = fakeLocker{} // guards following
  1458  	testHookReadLoopBeforeNextRead             = nop
  1459  )
  1460  
  1461  // beforeRespHeaderError is used to indicate when an IO error has occurred before
  1462  // any header data was received.
  1463  type beforeRespHeaderError struct {
  1464  	error
  1465  }
  1466  
  1467  func (pc *persistConn) roundTrip(req *transportRequest) (resp *Response, err error) {
  1468  	testHookEnterRoundTrip()
  1469  	if !pc.t.replaceReqCanceler(req.Request, pc.cancelRequest) {
  1470  		pc.t.putOrCloseIdleConn(pc)
  1471  		return nil, errRequestCanceled
  1472  	}
  1473  	pc.mu.Lock()
  1474  	pc.numExpectedResponses++
  1475  	headerFn := pc.mutateHeaderFunc
  1476  	pc.mu.Unlock()
  1477  
  1478  	if headerFn != nil {
  1479  		headerFn(req.extraHeaders())
  1480  	}
  1481  
  1482  	// Ask for a compressed version if the caller didn't set their
  1483  	// own value for Accept-Encoding. We only attempt to
  1484  	// uncompress the gzip stream if we were the layer that
  1485  	// requested it.
  1486  	requestedGzip := false
  1487  	if !pc.t.DisableCompression &&
  1488  		req.Header.Get("Accept-Encoding") == "" &&
  1489  		req.Header.Get("Range") == "" &&
  1490  		req.Method != "HEAD" {
  1491  		// Request gzip only, not deflate. Deflate is ambiguous and
  1492  		// not as universally supported anyway.
  1493  		// See: http://www.gzip.org/zlib/zlib_faq.html#faq38
  1494  		//
  1495  		// Note that we don't request this for HEAD requests,
  1496  		// due to a bug in nginx:
  1497  		//   http://trac.nginx.org/nginx/ticket/358
  1498  		//   https://golang.org/issue/5522
  1499  		//
  1500  		// We don't request gzip if the request is for a range, since
  1501  		// auto-decoding a portion of a gzipped document will just fail
  1502  		// anyway. See https://golang.org/issue/8923
  1503  		requestedGzip = true
  1504  		req.extraHeaders().Set("Accept-Encoding", "gzip")
  1505  	}
  1506  
  1507  	var continueCh chan struct{}
  1508  	if req.ProtoAtLeast(1, 1) && req.Body != nil && req.expectsContinue() {
  1509  		continueCh = make(chan struct{}, 1)
  1510  	}
  1511  
  1512  	if pc.t.DisableKeepAlives {
  1513  		req.extraHeaders().Set("Connection", "close")
  1514  	}
  1515  
  1516  	gone := make(chan struct{})
  1517  	defer close(gone)
  1518  
  1519  	// Write the request concurrently with waiting for a response,
  1520  	// in case the server decides to reply before reading our full
  1521  	// request body.
  1522  	writeErrCh := make(chan error, 1)
  1523  	pc.writech <- writeRequest{req, writeErrCh, continueCh}
  1524  
  1525  	resc := make(chan responseAndError)
  1526  	pc.reqch <- requestAndChan{
  1527  		req:        req.Request,
  1528  		ch:         resc,
  1529  		addedGzip:  requestedGzip,
  1530  		continueCh: continueCh,
  1531  		callerGone: gone,
  1532  	}
  1533  
  1534  	var re responseAndError
  1535  	var respHeaderTimer <-chan time.Time
  1536  	cancelChan := req.Request.Cancel
  1537  WaitResponse:
  1538  	for {
  1539  		testHookWaitResLoop()
  1540  		select {
  1541  		case err := <-writeErrCh:
  1542  			if err != nil {
  1543  				if pc.isCanceled() {
  1544  					err = errRequestCanceled
  1545  				}
  1546  				re = responseAndError{err: beforeRespHeaderError{err}}
  1547  				pc.close(fmt.Errorf("write error: %v", err))
  1548  				break WaitResponse
  1549  			}
  1550  			if d := pc.t.ResponseHeaderTimeout; d > 0 {
  1551  				timer := time.NewTimer(d)
  1552  				defer timer.Stop() // prevent leaks
  1553  				respHeaderTimer = timer.C
  1554  			}
  1555  		case <-pc.closech:
  1556  			var err error
  1557  			if pc.isCanceled() {
  1558  				err = errRequestCanceled
  1559  			} else {
  1560  				err = beforeRespHeaderError{fmt.Errorf("net/http: HTTP/1 transport connection broken: %v", pc.closed)}
  1561  			}
  1562  			re = responseAndError{err: err}
  1563  			break WaitResponse
  1564  		case <-respHeaderTimer:
  1565  			pc.close(errTimeout)
  1566  			re = responseAndError{err: errTimeout}
  1567  			break WaitResponse
  1568  		case re = <-resc:
  1569  			if re.err != nil && pc.isCanceled() {
  1570  				re.err = errRequestCanceled
  1571  			}
  1572  			break WaitResponse
  1573  		case <-cancelChan:
  1574  			pc.t.CancelRequest(req.Request)
  1575  			cancelChan = nil
  1576  		case <-req.Context().Done():
  1577  			pc.t.CancelRequest(req.Request)
  1578  			cancelChan = nil
  1579  		}
  1580  	}
  1581  
  1582  	if re.err != nil {
  1583  		pc.t.setReqCanceler(req.Request, nil)
  1584  	}
  1585  	if (re.res == nil) == (re.err == nil) {
  1586  		panic("internal error: exactly one of res or err should be set")
  1587  	}
  1588  	return re.res, re.err
  1589  }
  1590  
  1591  // markBroken marks a connection as broken (so it's not reused).
  1592  // It differs from close in that it doesn't close the underlying
  1593  // connection for use when it's still being read.
  1594  func (pc *persistConn) markBroken() {
  1595  	pc.mu.Lock()
  1596  	defer pc.mu.Unlock()
  1597  	pc.broken = true
  1598  }
  1599  
  1600  // markReused marks this connection as having been successfully used for a
  1601  // request and response.
  1602  func (pc *persistConn) markReused() {
  1603  	pc.mu.Lock()
  1604  	pc.reused = true
  1605  	pc.mu.Unlock()
  1606  }
  1607  
  1608  // close closes the underlying TCP connection and closes
  1609  // the pc.closech channel.
  1610  //
  1611  // The provided err is only for testing and debugging; in normal
  1612  // circumstances it should never be seen by users.
  1613  func (pc *persistConn) close(err error) {
  1614  	pc.mu.Lock()
  1615  	defer pc.mu.Unlock()
  1616  	pc.closeLocked(err)
  1617  }
  1618  
  1619  func (pc *persistConn) closeLocked(err error) {
  1620  	if err == nil {
  1621  		panic("nil error")
  1622  	}
  1623  	pc.broken = true
  1624  	if pc.closed == nil {
  1625  		pc.closed = err
  1626  		if pc.alt != nil {
  1627  			// Do nothing; can only get here via getConn's
  1628  			// handlePendingDial's putOrCloseIdleConn when
  1629  			// it turns out the abandoned connection in
  1630  			// flight ended up negotiating an alternate
  1631  			// protocol. We don't use the connection
  1632  			// freelist for http2. That's done by the
  1633  			// alternate protocol's RoundTripper.
  1634  		} else {
  1635  			pc.conn.Close()
  1636  			close(pc.closech)
  1637  		}
  1638  	}
  1639  	pc.mutateHeaderFunc = nil
  1640  }
  1641  
  1642  var portMap = map[string]string{
  1643  	"http":  "80",
  1644  	"https": "443",
  1645  }
  1646  
  1647  // canonicalAddr returns url.Host but always with a ":port" suffix
  1648  func canonicalAddr(url *url.URL) string {
  1649  	addr := url.Host
  1650  	if !hasPort(addr) {
  1651  		return addr + ":" + portMap[url.Scheme]
  1652  	}
  1653  	return addr
  1654  }
  1655  
  1656  // bodyEOFSignal is used by the HTTP/1 transport when reading response
  1657  // bodies to make sure we see the end of a response body before
  1658  // proceeding and reading on the connection again.
  1659  //
  1660  // It wraps a ReadCloser but runs fn (if non-nil) at most
  1661  // once, right before its final (error-producing) Read or Close call
  1662  // returns. fn should return the new error to return from Read or Close.
  1663  //
  1664  // If earlyCloseFn is non-nil and Close is called before io.EOF is
  1665  // seen, earlyCloseFn is called instead of fn, and its return value is
  1666  // the return value from Close.
  1667  type bodyEOFSignal struct {
  1668  	body         io.ReadCloser
  1669  	mu           sync.Mutex        // guards following 4 fields
  1670  	closed       bool              // whether Close has been called
  1671  	rerr         error             // sticky Read error
  1672  	fn           func(error) error // err will be nil on Read io.EOF
  1673  	earlyCloseFn func() error      // optional alt Close func used if io.EOF not seen
  1674  }
  1675  
  1676  var errReadOnClosedResBody = errors.New("http: read on closed response body")
  1677  
  1678  func (es *bodyEOFSignal) Read(p []byte) (n int, err error) {
  1679  	es.mu.Lock()
  1680  	closed, rerr := es.closed, es.rerr
  1681  	es.mu.Unlock()
  1682  	if closed {
  1683  		return 0, errReadOnClosedResBody
  1684  	}
  1685  	if rerr != nil {
  1686  		return 0, rerr
  1687  	}
  1688  
  1689  	n, err = es.body.Read(p)
  1690  	if err != nil {
  1691  		es.mu.Lock()
  1692  		defer es.mu.Unlock()
  1693  		if es.rerr == nil {
  1694  			es.rerr = err
  1695  		}
  1696  		err = es.condfn(err)
  1697  	}
  1698  	return
  1699  }
  1700  
  1701  func (es *bodyEOFSignal) Close() error {
  1702  	es.mu.Lock()
  1703  	defer es.mu.Unlock()
  1704  	if es.closed {
  1705  		return nil
  1706  	}
  1707  	es.closed = true
  1708  	if es.earlyCloseFn != nil && es.rerr != io.EOF {
  1709  		return es.earlyCloseFn()
  1710  	}
  1711  	err := es.body.Close()
  1712  	return es.condfn(err)
  1713  }
  1714  
  1715  // caller must hold es.mu.
  1716  func (es *bodyEOFSignal) condfn(err error) error {
  1717  	if es.fn == nil {
  1718  		return err
  1719  	}
  1720  	err = es.fn(err)
  1721  	es.fn = nil
  1722  	return err
  1723  }
  1724  
  1725  // gzipReader wraps a response body so it can lazily
  1726  // call gzip.NewReader on the first call to Read
  1727  type gzipReader struct {
  1728  	body *bodyEOFSignal // underlying HTTP/1 response body framing
  1729  	zr   *gzip.Reader   // lazily-initialized gzip reader
  1730  	zerr error          // any error from gzip.NewReader; sticky
  1731  }
  1732  
  1733  func (gz *gzipReader) Read(p []byte) (n int, err error) {
  1734  	if gz.zr == nil {
  1735  		if gz.zerr == nil {
  1736  			gz.zr, gz.zerr = gzip.NewReader(gz.body)
  1737  		}
  1738  		if gz.zerr != nil {
  1739  			return 0, gz.zerr
  1740  		}
  1741  	}
  1742  
  1743  	gz.body.mu.Lock()
  1744  	if gz.body.closed {
  1745  		err = errReadOnClosedResBody
  1746  	}
  1747  	gz.body.mu.Unlock()
  1748  
  1749  	if err != nil {
  1750  		return 0, err
  1751  	}
  1752  	return gz.zr.Read(p)
  1753  }
  1754  
  1755  func (gz *gzipReader) Close() error {
  1756  	return gz.body.Close()
  1757  }
  1758  
  1759  type readerAndCloser struct {
  1760  	io.Reader
  1761  	io.Closer
  1762  }
  1763  
  1764  type tlsHandshakeTimeoutError struct{}
  1765  
  1766  func (tlsHandshakeTimeoutError) Timeout() bool   { return true }
  1767  func (tlsHandshakeTimeoutError) Temporary() bool { return true }
  1768  func (tlsHandshakeTimeoutError) Error() string   { return "net/http: TLS handshake timeout" }
  1769  
  1770  // fakeLocker is a sync.Locker which does nothing. It's used to guard
  1771  // test-only fields when not under test, to avoid runtime atomic
  1772  // overhead.
  1773  type fakeLocker struct{}
  1774  
  1775  func (fakeLocker) Lock()   {}
  1776  func (fakeLocker) Unlock() {}
  1777  
  1778  // cloneTLSConfig returns a shallow clone of the exported
  1779  // fields of cfg, ignoring the unexported sync.Once, which
  1780  // contains a mutex and must not be copied.
  1781  //
  1782  // The cfg must not be in active use by tls.Server, or else
  1783  // there can still be a race with tls.Server updating SessionTicketKey
  1784  // and our copying it, and also a race with the server setting
  1785  // SessionTicketsDisabled=false on failure to set the random
  1786  // ticket key.
  1787  //
  1788  // If cfg is nil, a new zero tls.Config is returned.
  1789  func cloneTLSConfig(cfg *tls.Config) *tls.Config {
  1790  	if cfg == nil {
  1791  		return &tls.Config{}
  1792  	}
  1793  	return &tls.Config{
  1794  		Rand:                     cfg.Rand,
  1795  		Time:                     cfg.Time,
  1796  		Certificates:             cfg.Certificates,
  1797  		NameToCertificate:        cfg.NameToCertificate,
  1798  		GetCertificate:           cfg.GetCertificate,
  1799  		RootCAs:                  cfg.RootCAs,
  1800  		NextProtos:               cfg.NextProtos,
  1801  		ServerName:               cfg.ServerName,
  1802  		ClientAuth:               cfg.ClientAuth,
  1803  		ClientCAs:                cfg.ClientCAs,
  1804  		InsecureSkipVerify:       cfg.InsecureSkipVerify,
  1805  		CipherSuites:             cfg.CipherSuites,
  1806  		PreferServerCipherSuites: cfg.PreferServerCipherSuites,
  1807  		SessionTicketsDisabled:   cfg.SessionTicketsDisabled,
  1808  		SessionTicketKey:         cfg.SessionTicketKey,
  1809  		ClientSessionCache:       cfg.ClientSessionCache,
  1810  		MinVersion:               cfg.MinVersion,
  1811  		MaxVersion:               cfg.MaxVersion,
  1812  		CurvePreferences:         cfg.CurvePreferences,
  1813  	}
  1814  }
  1815  
  1816  // cloneTLSClientConfig is like cloneTLSConfig but omits
  1817  // the fields SessionTicketsDisabled and SessionTicketKey.
  1818  // This makes it safe to call cloneTLSClientConfig on a config
  1819  // in active use by a server.
  1820  func cloneTLSClientConfig(cfg *tls.Config) *tls.Config {
  1821  	if cfg == nil {
  1822  		return &tls.Config{}
  1823  	}
  1824  	return &tls.Config{
  1825  		Rand:                     cfg.Rand,
  1826  		Time:                     cfg.Time,
  1827  		Certificates:             cfg.Certificates,
  1828  		NameToCertificate:        cfg.NameToCertificate,
  1829  		GetCertificate:           cfg.GetCertificate,
  1830  		RootCAs:                  cfg.RootCAs,
  1831  		NextProtos:               cfg.NextProtos,
  1832  		ServerName:               cfg.ServerName,
  1833  		ClientAuth:               cfg.ClientAuth,
  1834  		ClientCAs:                cfg.ClientCAs,
  1835  		InsecureSkipVerify:       cfg.InsecureSkipVerify,
  1836  		CipherSuites:             cfg.CipherSuites,
  1837  		PreferServerCipherSuites: cfg.PreferServerCipherSuites,
  1838  		ClientSessionCache:       cfg.ClientSessionCache,
  1839  		MinVersion:               cfg.MinVersion,
  1840  		MaxVersion:               cfg.MaxVersion,
  1841  		CurvePreferences:         cfg.CurvePreferences,
  1842  	}
  1843  }