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