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