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