github.com/useflyent/fhttp@v0.0.0-20211004035111-333f430cfbbf/http2/transport.go (about)

     1  // Copyright 2015 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  // Transport code.
     6  
     7  package http2
     8  
     9  import (
    10  	"bufio"
    11  	"bytes"
    12  	"context"
    13  	"crypto/rand"
    14  	"crypto/tls"
    15  	"errors"
    16  	"fmt"
    17  	"io"
    18  	"io/ioutil"
    19  	"log"
    20  	"math"
    21  	mathrand "math/rand"
    22  	"net"
    23  	"net/textproto"
    24  	"sort"
    25  	"strconv"
    26  	"strings"
    27  	"sync"
    28  	"sync/atomic"
    29  	"time"
    30  
    31  	http "github.com/useflyent/fhttp"
    32  	"github.com/useflyent/fhttp/httptrace"
    33  
    34  	"github.com/useflyent/fhttp/http2/hpack"
    35  	"golang.org/x/net/http/httpguts"
    36  	"golang.org/x/net/idna"
    37  )
    38  
    39  const (
    40  	// transportDefaultConnFlow is how many connection-level flow control
    41  	// tokens we give the server at start-up, past the default 64k.
    42  	transportDefaultConnFlow = 1 << 30
    43  
    44  	// transportDefaultStreamFlow is how many stream-level flow
    45  	// control tokens we announce to the peer, and how many bytes
    46  	// we buffer per stream.
    47  	transportDefaultStreamFlow = 4 << 20
    48  
    49  	// transportDefaultStreamMinRefresh is the minimum number of bytes we'll send
    50  	// a stream-level WINDOW_UPDATE for at a time.
    51  	transportDefaultStreamMinRefresh = 4 << 10
    52  
    53  	defaultUserAgent = "Go-http-client/2.0"
    54  )
    55  
    56  // Transport is an HTTP/2 Transport.
    57  //
    58  // A Transport internally caches connections to servers. It is safe
    59  // for concurrent use by multiple goroutines.
    60  type Transport struct {
    61  	// DialTLS specifies an optional dial function for creating
    62  	// TLS connections for requests.
    63  	//
    64  	// If DialTLS is nil, tls.Dial is used.
    65  	//
    66  	// If the returned net.Conn has a ConnectionState method like tls.Conn,
    67  	// it will be used to set http.Response.TLS.
    68  	DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error)
    69  
    70  	// TLSClientConfig specifies the TLS configuration to use with
    71  	// tls.Client. If nil, the default configuration is used.
    72  	TLSClientConfig *tls.Config
    73  
    74  	// ConnPool optionally specifies an alternate connection pool to use.
    75  	// If nil, the default is used.
    76  	ConnPool ClientConnPool
    77  
    78  	// DisableCompression, if true, prevents the Transport from
    79  	// requesting compression with an "Accept-Encoding: gzip"
    80  	// request header when the Request contains no existing
    81  	// Accept-Encoding value. If the Transport requests gzip on
    82  	// its own and gets a gzipped response, it's transparently
    83  	// decoded in the Response.Body. However, if the user
    84  	// explicitly requested gzip it is not automatically
    85  	// uncompressed.
    86  	DisableCompression bool
    87  
    88  	// AllowHTTP, if true, permits HTTP/2 requests using the insecure,
    89  	// plain-text "http" scheme. Note that this does not enable h2c support.
    90  	AllowHTTP bool
    91  
    92  	// MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
    93  	// send in the initial settings frame. It is how many bytes
    94  	// of response headers are allowed. Unlike the http2 spec, zero here
    95  	// means to use a default limit (currently 10MB). If you actually
    96  	// want to advertise an unlimited value to the peer, Transport
    97  	// interprets the highest possible value here (0xffffffff or 1<<32-1)
    98  	// to mean no limit.
    99  	MaxHeaderListSize uint32
   100  
   101  	// StrictMaxConcurrentStreams controls whether the server's
   102  	// SETTINGS_MAX_CONCURRENT_STREAMS should be respected
   103  	// globally. If false, new TCP connections are created to the
   104  	// server as needed to keep each under the per-connection
   105  	// SETTINGS_MAX_CONCURRENT_STREAMS limit. If true, the
   106  	// server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as
   107  	// a global limit and callers of RoundTrip block when needed,
   108  	// waiting for their turn.
   109  	StrictMaxConcurrentStreams bool
   110  
   111  	// ReadIdleTimeout is the timeout after which a health check using ping
   112  	// frame will be carried out if no frame is received on the connection.
   113  	// Note that a ping response will is considered a received frame, so if
   114  	// there is no other traffic on the connection, the health check will
   115  	// be performed every ReadIdleTimeout interval.
   116  	// If zero, no health check is performed.
   117  	ReadIdleTimeout time.Duration
   118  
   119  	// PingTimeout is the timeout after which the connection will be closed
   120  	// if a response to Ping is not received.
   121  	// Defaults to 15s.
   122  	PingTimeout time.Duration
   123  
   124  	// PushHandler is called upon receiving PUSH_PROMISEs from the server.
   125  	// If nil, server push is disabled.
   126  	//
   127  	// Unless TLSClientConfig.InsecureSkipVerify is set, the Transport verifies
   128  	// whether the server is authoritative for the received PUSH_PROMISEs. On a
   129  	// TLS connection, this is done by verifing the certificates. On a non-TLS
   130  	// connection, the pushed request must have the same host name as the
   131  	// original one.
   132  	//
   133  	// There is no support for limiting the number of responses
   134  	// that can be concurrently pushed by the server, for example, by setting
   135  	// SETTINGS_MAX_CONCURRENT_STREAMS.
   136  	PushHandler PushHandler
   137  
   138  	// t1, if non-nil, is the standard library Transport using
   139  	// this transport. Its settings are used (but not its
   140  	// RoundTrip method, etc).
   141  	t1 *http.Transport
   142  
   143  	connPoolOnce  sync.Once
   144  	connPoolOrDef ClientConnPool // non-nil version of ConnPool
   145  
   146  	// Settings should not include InitialWindowSize or HeaderTableSize, set that in Transport
   147  	Settings          []Setting
   148  	InitialWindowSize uint32 // if nil, will use global initialWindowSize
   149  	HeaderTableSize   uint32 // if nil, will use global initialHeaderTableSize
   150  }
   151  
   152  func (t *Transport) maxHeaderListSize() uint32 {
   153  	if t.MaxHeaderListSize == 0 {
   154  		return 10 << 20
   155  	}
   156  	if t.MaxHeaderListSize == 0xffffffff {
   157  		return 0
   158  	}
   159  	return t.MaxHeaderListSize
   160  }
   161  
   162  func (t *Transport) disableCompression() bool {
   163  	return t.DisableCompression || (t.t1 != nil && t.t1.DisableCompression)
   164  }
   165  
   166  func (t *Transport) pingTimeout() time.Duration {
   167  	if t.PingTimeout == 0 {
   168  		return 15 * time.Second
   169  	}
   170  	return t.PingTimeout
   171  
   172  }
   173  
   174  // ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2.
   175  // It returns an error if t1 has already been HTTP/2-enabled.
   176  //
   177  // Use ConfigureTransports instead to configure the HTTP/2 Transport.
   178  func ConfigureTransport(t1 *http.Transport) error {
   179  	_, err := ConfigureTransports(t1)
   180  	return err
   181  }
   182  
   183  // ConfigureTransports configures a net/http HTTP/1 Transport to use HTTP/2.
   184  // It returns a new HTTP/2 Transport for further configuration.
   185  // It returns an error if t1 has already been HTTP/2-enabled.
   186  func ConfigureTransports(t1 *http.Transport) (*Transport, error) {
   187  	return configureTransports(t1)
   188  }
   189  
   190  func configureTransports(t1 *http.Transport) (*Transport, error) {
   191  	connPool := new(clientConnPool)
   192  	t2 := &Transport{
   193  		ConnPool: noDialClientConnPool{connPool},
   194  		t1:       t1,
   195  	}
   196  
   197  	connPool.t = t2
   198  	if err := registerHTTPSProtocol(t1, noDialH2RoundTripper{t2}); err != nil {
   199  		return nil, err
   200  	}
   201  	if t1.TLSClientConfig == nil {
   202  		t1.TLSClientConfig = new(tls.Config)
   203  	}
   204  	if !strSliceContains(t1.TLSClientConfig.NextProtos, "h2") {
   205  		t1.TLSClientConfig.NextProtos = append([]string{"h2"}, t1.TLSClientConfig.NextProtos...)
   206  	}
   207  	if !strSliceContains(t1.TLSClientConfig.NextProtos, "http/1.1") {
   208  		t1.TLSClientConfig.NextProtos = append(t1.TLSClientConfig.NextProtos, "http/1.1")
   209  	}
   210  	upgradeFn := func(authority string, c *tls.Conn) http.RoundTripper {
   211  		addr := authorityAddr("https", authority)
   212  		if used, err := connPool.addConnIfNeeded(addr, t2, c); err != nil {
   213  			go c.Close()
   214  			return erringRoundTripper{err}
   215  		} else if !used {
   216  			// Turns out we don't need this c.
   217  			// For example, two goroutines made requests to the same host
   218  			// at the same time, both kicking off TCP dials. (since protocol
   219  			// was unknown)
   220  			go c.Close()
   221  		}
   222  		return t2
   223  	}
   224  	if m := t1.TLSNextProto; len(m) == 0 {
   225  		t1.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{
   226  			"h2": upgradeFn,
   227  		}
   228  	} else {
   229  		m["h2"] = upgradeFn
   230  	}
   231  
   232  	// Auto-configure the http2.Transport's MaxHeaderListSize from
   233  	// the http.Transport's MaxResponseHeaderBytes. They don't
   234  	// exactly mean the same thing, but they're close.
   235  	//
   236  	// TODO: also add this to x/net/http2.Configure Transport, behind
   237  	// a +build go1.7 build tag:
   238  	if limit1 := t1.MaxResponseHeaderBytes; limit1 != 0 && t2.MaxHeaderListSize == 0 {
   239  		const h2max = 1<<32 - 1
   240  		if limit1 >= h2max {
   241  			t2.MaxHeaderListSize = h2max
   242  		} else {
   243  			t2.MaxHeaderListSize = uint32(limit1)
   244  		}
   245  	}
   246  	return t2, nil
   247  }
   248  
   249  func (t *Transport) connPool() ClientConnPool {
   250  	t.connPoolOnce.Do(t.initConnPool)
   251  	return t.connPoolOrDef
   252  }
   253  
   254  func (t *Transport) initConnPool() {
   255  	if t.ConnPool != nil {
   256  		t.connPoolOrDef = t.ConnPool
   257  	} else {
   258  		t.connPoolOrDef = &clientConnPool{t: t}
   259  	}
   260  }
   261  
   262  // ClientConn is the state of a single HTTP/2 client connection to an
   263  // HTTP/2 server.
   264  type ClientConn struct {
   265  	t          *Transport
   266  	tconn      net.Conn             // usually *tls.Conn, except specialized impls
   267  	dialedAddr string               // addr dialed to create tconn; not set with NewClientConn
   268  	tlsState   *tls.ConnectionState // nil only for specialized impls
   269  	reused     uint32               // whether conn is being reused; atomic
   270  	singleUse  bool                 // whether being used for a single http.Request
   271  
   272  	// readLoop goroutine fields:
   273  	readerDone chan struct{} // closed on error
   274  	readerErr  error         // set before readerDone is closed
   275  
   276  	idleTimeout time.Duration // or 0 for never
   277  	idleTimer   *time.Timer
   278  
   279  	mu               sync.Mutex // guards following
   280  	cond             *sync.Cond // hold mu; broadcast on flow/closed changes
   281  	flow             flow       // our conn-level flow control quota (cs.flow is per stream)
   282  	inflow           flow       // peer's conn-level flow control
   283  	closing          bool
   284  	closed           bool
   285  	wantSettingsAck  bool                     // we sent a SETTINGS frame and haven't heard back
   286  	goAway           *GoAwayFrame             // if non-nil, the GoAwayFrame we received
   287  	goAwayDebug      string                   // goAway frame's debug data, retained as a string
   288  	streams          map[uint32]*clientStream // client-initiated
   289  	nextStreamID     uint32
   290  	highestPromiseID uint32                    // highest promise id so far received from server
   291  	pendingRequests  int                       // requests blocked and waiting to be sent because len(streams) == maxConcurrentStreams
   292  	pings            map[[8]byte]chan struct{} // in flight ping data to notification channel
   293  	bw               *bufio.Writer
   294  	br               *bufio.Reader
   295  	fr               *Framer
   296  	lastActive       time.Time
   297  	lastIdle         time.Time // time last idle
   298  	// Settings from peer: (also guarded by mu)
   299  	maxFrameSize          uint32
   300  	maxConcurrentStreams  uint32
   301  	peerMaxHeaderListSize uint64
   302  	initialWindowSize     uint32
   303  
   304  	hbuf    bytes.Buffer // HPACK encoder writes into this
   305  	henc    *hpack.Encoder
   306  	freeBuf [][]byte
   307  
   308  	wmu  sync.Mutex // held while writing; acquire AFTER mu if holding both
   309  	werr error      // first write error that has occurred
   310  }
   311  
   312  // clientStream is the state for a single HTTP/2 stream. One of these
   313  // is created for each Transport.RoundTrip call.
   314  type clientStream struct {
   315  	cc            *ClientConn
   316  	req           *http.Request
   317  	trace         *httptrace.ClientTrace // or nil
   318  	ID            uint32
   319  	resc          chan resAndError
   320  	bufPipe       pipe // buffered pipe with the flow-controlled response payload
   321  	startedWrite  bool // started request body write; guarded by cc.mu
   322  	requestedGzip bool
   323  	on100         func() // optional code to run if get a 100 continue response
   324  
   325  	flow        flow  // guarded by cc.mu
   326  	inflow      flow  // guarded by cc.mu
   327  	bytesRemain int64 // -1 means unknown; owned by transportResponseBody.Read
   328  	readErr     error // sticky read error; owned by transportResponseBody.Read
   329  	stopReqBody error // if non-nil, stop writing req body; guarded by cc.mu
   330  	didReset    bool  // whether we sent a RST_STREAM to the server; guarded by cc.mu
   331  
   332  	peerReset chan struct{} // closed on peer reset
   333  	resetErr  error         // populated before peerReset is closed
   334  
   335  	done chan struct{} // closed when stream remove from cc.streams map; close calls guarded by cc.mu
   336  
   337  	// owned by clientConnReadLoop:
   338  	firstByte    bool  // got the first response byte
   339  	pastHeaders  bool  // got first MetaHeadersFrame (actual headers)
   340  	pastTrailers bool  // got optional second MetaHeadersFrame (trailers)
   341  	gotEndStream bool  // got frame with END_STREAM flag set
   342  	num1xx       uint8 // number of 1xx responses seen
   343  
   344  	trailer    http.Header  // accumulated trailers
   345  	resTrailer *http.Header // client's Response.Trailer
   346  }
   347  
   348  // awaitRequestCancel waits for the user to cancel a request or for the done
   349  // channel to be signaled. A non-nil error is returned only if the request was
   350  // canceled.
   351  func awaitRequestCancel(req *http.Request, done <-chan struct{}) error {
   352  	ctx := req.Context()
   353  	if req.Cancel == nil && ctx.Done() == nil {
   354  		return nil
   355  	}
   356  	select {
   357  	case <-req.Cancel:
   358  		return errRequestCanceled
   359  	case <-ctx.Done():
   360  		return ctx.Err()
   361  	case <-done:
   362  		return nil
   363  	}
   364  }
   365  
   366  var got1xxFuncForTests func(int, textproto.MIMEHeader) error
   367  
   368  // get1xxTraceFunc returns the value of request's httptrace.ClientTrace.Got1xxResponse func,
   369  // if any. It returns nil if not set or if the Go version is too old.
   370  func (cs *clientStream) get1xxTraceFunc() func(int, textproto.MIMEHeader) error {
   371  	if fn := got1xxFuncForTests; fn != nil {
   372  		return fn
   373  	}
   374  	return traceGot1xxResponseFunc(cs.trace)
   375  }
   376  
   377  // awaitRequestCancel waits for the user to cancel a request, its context to
   378  // expire, or for the request to be done (any way it might be removed from the
   379  // cc.streams map: peer reset, successful completion, TCP connection breakage,
   380  // etc). If the request is canceled, then cs will be canceled and closed.
   381  func (cs *clientStream) awaitRequestCancel(req *http.Request) {
   382  	if err := awaitRequestCancel(req, cs.done); err != nil {
   383  		cs.cancelStream()
   384  		cs.bufPipe.CloseWithError(err)
   385  	}
   386  }
   387  
   388  func (cs *clientStream) cancelStream() {
   389  	cc := cs.cc
   390  	cc.mu.Lock()
   391  	didReset := cs.didReset
   392  	cs.didReset = true
   393  	cc.mu.Unlock()
   394  
   395  	if didReset {
   396  		cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
   397  		cc.forgetStreamID(cs.ID)
   398  	}
   399  }
   400  
   401  // checkResetOrDone reports any error sent in a RST_STREAM frame by the
   402  // server, or errStreamClosed if the stream is complete.
   403  func (cs *clientStream) checkResetOrDone() error {
   404  	select {
   405  	case <-cs.peerReset:
   406  		return cs.resetErr
   407  	case <-cs.done:
   408  		return errStreamClosed
   409  	default:
   410  		return nil
   411  	}
   412  }
   413  
   414  func (cs *clientStream) getStartedWrite() bool {
   415  	cc := cs.cc
   416  	cc.mu.Lock()
   417  	defer cc.mu.Unlock()
   418  	return cs.startedWrite
   419  }
   420  
   421  func (cs *clientStream) abortRequestBodyWrite(err error) {
   422  	if err == nil {
   423  		panic("nil error")
   424  	}
   425  	cc := cs.cc
   426  	cc.mu.Lock()
   427  	cs.stopReqBody = err
   428  	cc.cond.Broadcast()
   429  	cc.mu.Unlock()
   430  }
   431  
   432  type stickyErrWriter struct {
   433  	w   io.Writer
   434  	err *error
   435  }
   436  
   437  func (sew stickyErrWriter) Write(p []byte) (n int, err error) {
   438  	if *sew.err != nil {
   439  		return 0, *sew.err
   440  	}
   441  	n, err = sew.w.Write(p)
   442  	*sew.err = err
   443  	return
   444  }
   445  
   446  // noCachedConnError is the concrete type of ErrNoCachedConn, which
   447  // needs to be detected by net/http regardless of whether it's its
   448  // bundled version (in h2_bundle.go with a rewritten type name) or
   449  // from a user's x/net/http2. As such, as it has a unique method name
   450  // (IsHTTP2NoCachedConnError) that net/http sniffs for via func
   451  // isNoCachedConnError.
   452  type noCachedConnError struct{}
   453  
   454  func (noCachedConnError) IsHTTP2NoCachedConnError() {}
   455  func (noCachedConnError) Error() string             { return "http2: no cached connection was available" }
   456  
   457  // isNoCachedConnError reports whether err is of type noCachedConnError
   458  // or its equivalent renamed type in net/http2's h2_bundle.go. Both types
   459  // may coexist in the same running program.
   460  func isNoCachedConnError(err error) bool {
   461  	_, ok := err.(interface{ IsHTTP2NoCachedConnError() })
   462  	return ok
   463  }
   464  
   465  var ErrNoCachedConn error = noCachedConnError{}
   466  
   467  // RoundTripOpt are options for the Transport.RoundTripOpt method.
   468  type RoundTripOpt struct {
   469  	// OnlyCachedConn controls whether RoundTripOpt may
   470  	// create a new TCP connection. If set true and
   471  	// no cached connection is available, RoundTripOpt
   472  	// will return ErrNoCachedConn.
   473  	OnlyCachedConn bool
   474  }
   475  
   476  func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
   477  	return t.RoundTripOpt(req, RoundTripOpt{})
   478  }
   479  
   480  // authorityHostPort accepts a given authority (a host/IP, or host:port / ip:port)
   481  // and returns a host and port.
   482  func authorityHostPort(scheme string, authority string) (host, port string) {
   483  	host, port, err := net.SplitHostPort(authority)
   484  	if err != nil { // authority didn't have a port
   485  		port = "443"
   486  		if scheme == "http" {
   487  			port = "80"
   488  		}
   489  		host = authority
   490  	}
   491  	if a, err := idna.ToASCII(host); err == nil {
   492  		host = a
   493  	}
   494  	return
   495  }
   496  
   497  // authorityAddr returns a given authority (a host/IP, or host:port / ip:port)
   498  // and returns a host:port. The port 443 is added if needed.
   499  func authorityAddr(scheme string, authority string) (addr string) {
   500  	host, port := authorityHostPort(scheme, authority)
   501  	// IPv6 address literal, without a port:
   502  	if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
   503  		return host + ":" + port
   504  	}
   505  	return net.JoinHostPort(host, port)
   506  }
   507  
   508  // RoundTripOpt is like RoundTrip, but takes options.
   509  func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) {
   510  	if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) {
   511  		return nil, errors.New("http2: unsupported scheme")
   512  	}
   513  
   514  	addr := authorityAddr(req.URL.Scheme, req.URL.Host)
   515  	for retry := 0; ; retry++ {
   516  		cc, err := t.connPool().GetClientConn(req, addr)
   517  		if err != nil {
   518  			t.vlogf("http2: Transport failed to get client conn for %s: %v", addr, err)
   519  			return nil, err
   520  		}
   521  		reused := !atomic.CompareAndSwapUint32(&cc.reused, 0, 1)
   522  		traceGotConn(req, cc, reused)
   523  		res, gotErrAfterReqBodyWrite, err := cc.roundTrip(req)
   524  		if err != nil && retry <= 6 {
   525  			if req, err = shouldRetryRequest(req, err, gotErrAfterReqBodyWrite); err == nil {
   526  				// After the first retry, do exponential backoff with 10% jitter.
   527  				if retry == 0 {
   528  					continue
   529  				}
   530  				backoff := float64(uint(1) << (uint(retry) - 1))
   531  				backoff += backoff * (0.1 * mathrand.Float64())
   532  				select {
   533  				case <-time.After(time.Second * time.Duration(backoff)):
   534  					continue
   535  				case <-req.Context().Done():
   536  					return nil, req.Context().Err()
   537  				}
   538  			}
   539  		}
   540  		if err != nil {
   541  			t.vlogf("RoundTrip failure: %v", err)
   542  			return nil, err
   543  		}
   544  		return res, nil
   545  	}
   546  }
   547  
   548  // CloseIdleConnections closes any connections which were previously
   549  // connected from previous requests but are now sitting idle.
   550  // It does not interrupt any connections currently in use.
   551  func (t *Transport) CloseIdleConnections() {
   552  	if cp, ok := t.connPool().(clientConnPoolIdleCloser); ok {
   553  		cp.closeIdleConnections()
   554  	}
   555  }
   556  
   557  var (
   558  	errClientConnClosed               = errors.New("http2: client conn is closed")
   559  	errClientConnUnusable             = errors.New("http2: client conn not usable")
   560  	errClientConnGotGoAway            = errors.New("http2: Transport received Server's graceful shutdown GOAWAY")
   561  	errSettingsIncludeIllegalSettings = errors.New("http2: Settings contains either SettingInitialWindowSize or SettingHeaderTableSize, which should be specified in transport instead")
   562  )
   563  
   564  // shouldRetryRequest is called by RoundTrip when a request fails to get
   565  // response headers. It is always called with a non-nil error.
   566  // It returns either a request to retry (either the same request, or a
   567  // modified clone), or an error if the request can't be replayed.
   568  func shouldRetryRequest(req *http.Request, err error, afterBodyWrite bool) (*http.Request, error) {
   569  	if !canRetryError(err) {
   570  		return nil, err
   571  	}
   572  	// If the Body is nil (or http.NoBody), it's safe to reuse
   573  	// this request and its Body.
   574  	if req.Body == nil || req.Body == http.NoBody {
   575  		return req, nil
   576  	}
   577  
   578  	// If the request body can be reset back to its original
   579  	// state via the optional req.GetBody, do that.
   580  	if req.GetBody != nil {
   581  		// TODO: consider a req.Body.Close here? or audit that all caller paths do?
   582  		body, err := req.GetBody()
   583  		if err != nil {
   584  			return nil, err
   585  		}
   586  		newReq := *req
   587  		newReq.Body = body
   588  		return &newReq, nil
   589  	}
   590  
   591  	// The Request.Body can't reset back to the beginning, but we
   592  	// don't seem to have started to read from it yet, so reuse
   593  	// the request directly. The "afterBodyWrite" means the
   594  	// bodyWrite process has started, which becomes true before
   595  	// the first Read.
   596  	if !afterBodyWrite {
   597  		return req, nil
   598  	}
   599  
   600  	return nil, fmt.Errorf("http2: Transport: cannot retry err [%v] after Request.Body was written; define Request.GetBody to avoid this error", err)
   601  }
   602  
   603  func canRetryError(err error) bool {
   604  	if err == errClientConnUnusable || err == errClientConnGotGoAway {
   605  		return true
   606  	}
   607  	if se, ok := err.(StreamError); ok {
   608  		return se.Code == ErrCodeRefusedStream
   609  	}
   610  	return false
   611  }
   612  
   613  func (t *Transport) dialClientConn(addr string, singleUse bool) (*ClientConn, error) {
   614  	host, _, err := net.SplitHostPort(addr)
   615  	if err != nil {
   616  		return nil, err
   617  	}
   618  	tconn, err := t.dialTLS()("tcp", addr, t.newTLSConfig(host))
   619  	if err != nil {
   620  		return nil, err
   621  	}
   622  	return t.newClientConn(tconn, addr, singleUse)
   623  }
   624  
   625  func (t *Transport) newTLSConfig(host string) *tls.Config {
   626  	cfg := new(tls.Config)
   627  	if t.TLSClientConfig != nil {
   628  		*cfg = *t.TLSClientConfig.Clone()
   629  	}
   630  	if !strSliceContains(cfg.NextProtos, NextProtoTLS) {
   631  		cfg.NextProtos = append([]string{NextProtoTLS}, cfg.NextProtos...)
   632  	}
   633  	if cfg.ServerName == "" {
   634  		cfg.ServerName = host
   635  	}
   636  	return cfg
   637  }
   638  
   639  func (t *Transport) dialTLS() func(string, string, *tls.Config) (net.Conn, error) {
   640  	if t.DialTLS != nil {
   641  		return t.DialTLS
   642  	}
   643  	return t.dialTLSDefault
   644  }
   645  
   646  func (t *Transport) dialTLSDefault(network, addr string, cfg *tls.Config) (net.Conn, error) {
   647  	cn, err := tls.Dial(network, addr, cfg)
   648  	if err != nil {
   649  		return nil, err
   650  	}
   651  	if err := cn.Handshake(); err != nil {
   652  		return nil, err
   653  	}
   654  	if !cfg.InsecureSkipVerify {
   655  		if err := cn.VerifyHostname(cfg.ServerName); err != nil {
   656  			return nil, err
   657  		}
   658  	}
   659  	state := cn.ConnectionState()
   660  	if p := state.NegotiatedProtocol; p != NextProtoTLS {
   661  		return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, NextProtoTLS)
   662  	}
   663  	if !state.NegotiatedProtocolIsMutual {
   664  		return nil, errors.New("http2: could not negotiate protocol mutually")
   665  	}
   666  	return cn, nil
   667  }
   668  
   669  // disableKeepAlives reports whether connections should be closed as
   670  // soon as possible after handling the first request.
   671  func (t *Transport) disableKeepAlives() bool {
   672  	return t.t1 != nil && t.t1.DisableKeepAlives
   673  }
   674  
   675  func (t *Transport) expectContinueTimeout() time.Duration {
   676  	if t.t1 == nil {
   677  		return 0
   678  	}
   679  	return t.t1.ExpectContinueTimeout
   680  }
   681  
   682  func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) {
   683  	return t.newClientConn(c, "", t.disableKeepAlives())
   684  }
   685  
   686  func (t *Transport) newClientConn(c net.Conn, addr string, singleUse bool) (*ClientConn, error) {
   687  	cc := &ClientConn{
   688  		t:                     t,
   689  		tconn:                 c,
   690  		dialedAddr:            addr,
   691  		readerDone:            make(chan struct{}),
   692  		nextStreamID:          1,
   693  		maxFrameSize:          16 << 10,           // spec default
   694  		initialWindowSize:     65535,              // spec default
   695  		maxConcurrentStreams:  1000,               // "infinite", per spec. 1000 seems good enough.
   696  		peerMaxHeaderListSize: 0xffffffffffffffff, // "infinite", per spec. Use 2^64-1 instead.
   697  		streams:               make(map[uint32]*clientStream),
   698  		singleUse:             singleUse,
   699  		wantSettingsAck:       true,
   700  		pings:                 make(map[[8]byte]chan struct{}),
   701  	}
   702  	if d := t.idleConnTimeout(); d != 0 {
   703  		cc.idleTimeout = d
   704  		cc.idleTimer = time.AfterFunc(d, cc.onIdleTimeout)
   705  	}
   706  	if VerboseLogs {
   707  		t.vlogf("http2: Transport creating client conn %p to %v", cc, c.RemoteAddr())
   708  	}
   709  
   710  	cc.cond = sync.NewCond(&cc.mu)
   711  	cc.flow.add(int32(initialWindowSize))
   712  
   713  	// TODO: adjust this writer size to account for frame size +
   714  	// MTU + crypto/tls record padding.
   715  	cc.bw = bufio.NewWriter(stickyErrWriter{c, &cc.werr})
   716  	cc.br = bufio.NewReader(c)
   717  	cc.fr = NewFramer(cc.bw, cc.br)
   718  	if t.HeaderTableSize != 0 {
   719  		cc.fr.ReadMetaHeaders = hpack.NewDecoder(t.HeaderTableSize, nil)
   720  	} else {
   721  		cc.fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil)
   722  	}
   723  	cc.fr.MaxHeaderListSize = t.maxHeaderListSize()
   724  
   725  	// TODO: SetMaxDynamicTableSize, SetMaxDynamicTableSizeLimit on
   726  	// henc in response to SETTINGS frames?
   727  	cc.henc = hpack.NewEncoder(&cc.hbuf)
   728  
   729  	if t.AllowHTTP {
   730  		cc.nextStreamID = 3
   731  	}
   732  
   733  	if cs, ok := c.(connectionStater); ok {
   734  		state := cs.ConnectionState()
   735  		cc.tlsState = &state
   736  	}
   737  
   738  	initialSettings := []Setting{}
   739  
   740  	var pushEnabled uint32
   741  	if t.PushHandler != nil {
   742  		pushEnabled = 1
   743  	}
   744  	initialSettings = append(initialSettings, Setting{ID: SettingEnablePush, Val: pushEnabled})
   745  
   746  	setMaxHeader := false
   747  	if t.Settings != nil {
   748  		for _, setting := range t.Settings {
   749  			if setting.ID == SettingMaxHeaderListSize {
   750  				setMaxHeader = true
   751  			}
   752  			if setting.ID == SettingHeaderTableSize || setting.ID == SettingInitialWindowSize {
   753  				return nil, errSettingsIncludeIllegalSettings
   754  			}
   755  			initialSettings = append(initialSettings, setting)
   756  		}
   757  	}
   758  	if t.InitialWindowSize != 0 {
   759  		initialSettings = append(initialSettings, Setting{ID: SettingInitialWindowSize, Val: t.InitialWindowSize})
   760  	} else {
   761  		initialSettings = append(initialSettings, Setting{ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow})
   762  	}
   763  	if t.HeaderTableSize != 0 {
   764  		initialSettings = append(initialSettings, Setting{ID: SettingHeaderTableSize, Val: t.HeaderTableSize})
   765  	} else {
   766  		initialSettings = append(initialSettings, Setting{ID: SettingHeaderTableSize, Val: initialHeaderTableSize})
   767  	}
   768  	if max := t.maxHeaderListSize(); max != 0 && !setMaxHeader {
   769  		initialSettings = append(initialSettings, Setting{ID: SettingMaxHeaderListSize, Val: max})
   770  	}
   771  
   772  	cc.bw.Write(clientPreface)
   773  	cc.fr.WriteSettings(initialSettings...)
   774  	cc.fr.WriteWindowUpdate(0, transportDefaultConnFlow)
   775  	cc.inflow.add(transportDefaultConnFlow + initialWindowSize)
   776  	cc.bw.Flush()
   777  	if cc.werr != nil {
   778  		cc.Close()
   779  		return nil, cc.werr
   780  	}
   781  
   782  	go cc.readLoop()
   783  	return cc, nil
   784  }
   785  
   786  func (cc *ClientConn) healthCheck() {
   787  	pingTimeout := cc.t.pingTimeout()
   788  	// We don't need to periodically ping in the health check, because the readLoop of ClientConn will
   789  	// trigger the healthCheck again if there is no frame received.
   790  	ctx, cancel := context.WithTimeout(context.Background(), pingTimeout)
   791  	defer cancel()
   792  	err := cc.Ping(ctx)
   793  	if err != nil {
   794  		cc.closeForLostPing()
   795  		cc.t.connPool().MarkDead(cc)
   796  		return
   797  	}
   798  }
   799  
   800  func (cc *ClientConn) setGoAway(f *GoAwayFrame) {
   801  	cc.mu.Lock()
   802  	defer cc.mu.Unlock()
   803  
   804  	old := cc.goAway
   805  	cc.goAway = f
   806  
   807  	// Merge the previous and current GoAway error frames.
   808  	if cc.goAwayDebug == "" {
   809  		cc.goAwayDebug = string(f.DebugData())
   810  	}
   811  	if old != nil && old.ErrCode != ErrCodeNo {
   812  		cc.goAway.ErrCode = old.ErrCode
   813  	}
   814  	last := f.LastStreamID
   815  	for streamID, cs := range cc.streams {
   816  		if streamID > last {
   817  			select {
   818  			case cs.resc <- resAndError{err: errClientConnGotGoAway}:
   819  			default:
   820  			}
   821  		}
   822  	}
   823  }
   824  
   825  // CanTakeNewRequest reports whether the connection can take a new request,
   826  // meaning it has not been closed or received or sent a GOAWAY.
   827  func (cc *ClientConn) CanTakeNewRequest() bool {
   828  	cc.mu.Lock()
   829  	defer cc.mu.Unlock()
   830  	return cc.canTakeNewRequestLocked()
   831  }
   832  
   833  // clientConnIdleState describes the suitability of a client
   834  // connection to initiate a new RoundTrip request.
   835  type clientConnIdleState struct {
   836  	canTakeNewRequest bool
   837  	freshConn         bool // whether it's unused by any previous request
   838  }
   839  
   840  func (cc *ClientConn) idleState() clientConnIdleState {
   841  	cc.mu.Lock()
   842  	defer cc.mu.Unlock()
   843  	return cc.idleStateLocked()
   844  }
   845  
   846  func (cc *ClientConn) idleStateLocked() (st clientConnIdleState) {
   847  	if cc.singleUse && cc.nextStreamID > 1 {
   848  		return
   849  	}
   850  	var maxConcurrentOkay bool
   851  	if cc.t.StrictMaxConcurrentStreams {
   852  		// We'll tell the caller we can take a new request to
   853  		// prevent the caller from dialing a new TCP
   854  		// connection, but then we'll block later before
   855  		// writing it.
   856  		maxConcurrentOkay = true
   857  	} else {
   858  		maxConcurrentOkay = int64(len(cc.streams)+1) < int64(cc.maxConcurrentStreams)
   859  	}
   860  
   861  	st.canTakeNewRequest = cc.goAway == nil && !cc.closed && !cc.closing && maxConcurrentOkay &&
   862  		int64(cc.nextStreamID)+2*int64(cc.pendingRequests) < math.MaxInt32 &&
   863  		!cc.tooIdleLocked()
   864  	st.freshConn = cc.nextStreamID == 1 && st.canTakeNewRequest
   865  	return
   866  }
   867  
   868  func (cc *ClientConn) canTakeNewRequestLocked() bool {
   869  	st := cc.idleStateLocked()
   870  	return st.canTakeNewRequest
   871  }
   872  
   873  // tooIdleLocked reports whether this connection has been been sitting idle
   874  // for too much wall time.
   875  func (cc *ClientConn) tooIdleLocked() bool {
   876  	// The Round(0) strips the monontonic clock reading so the
   877  	// times are compared based on their wall time. We don't want
   878  	// to reuse a connection that's been sitting idle during
   879  	// VM/laptop suspend if monotonic time was also frozen.
   880  	return cc.idleTimeout != 0 && !cc.lastIdle.IsZero() && time.Since(cc.lastIdle.Round(0)) > cc.idleTimeout
   881  }
   882  
   883  // onIdleTimeout is called from a time.AfterFunc goroutine. It will
   884  // only be called when we're idle, but because we're coming from a new
   885  // goroutine, there could be a new request coming in at the same time,
   886  // so this simply calls the synchronized closeIfIdle to shut down this
   887  // connection. The timer could just call closeIfIdle, but this is more
   888  // clear.
   889  func (cc *ClientConn) onIdleTimeout() {
   890  	cc.closeIfIdle()
   891  }
   892  
   893  func (cc *ClientConn) closeIfIdle() {
   894  	cc.mu.Lock()
   895  	if len(cc.streams) > 0 {
   896  		cc.mu.Unlock()
   897  		return
   898  	}
   899  	cc.closed = true
   900  	nextID := cc.nextStreamID
   901  	// TODO: do clients send GOAWAY too? maybe? Just Close:
   902  	cc.mu.Unlock()
   903  
   904  	if VerboseLogs {
   905  		cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, nextID-2)
   906  	}
   907  	cc.tconn.Close()
   908  }
   909  
   910  var shutdownEnterWaitStateHook = func() {}
   911  
   912  // Shutdown gracefully close the client connection, waiting for running streams to complete.
   913  func (cc *ClientConn) Shutdown(ctx context.Context) error {
   914  	if err := cc.sendGoAway(); err != nil {
   915  		return err
   916  	}
   917  	// Wait for all in-flight streams to complete or connection to close
   918  	done := make(chan error, 1)
   919  	cancelled := false // guarded by cc.mu
   920  	go func() {
   921  		cc.mu.Lock()
   922  		defer cc.mu.Unlock()
   923  		for {
   924  			if len(cc.streams) == 0 || cc.closed {
   925  				cc.closed = true
   926  				done <- cc.tconn.Close()
   927  				break
   928  			}
   929  			if cancelled {
   930  				break
   931  			}
   932  			cc.cond.Wait()
   933  		}
   934  	}()
   935  	shutdownEnterWaitStateHook()
   936  	select {
   937  	case err := <-done:
   938  		return err
   939  	case <-ctx.Done():
   940  		cc.mu.Lock()
   941  		// Free the goroutine above
   942  		cancelled = true
   943  		cc.cond.Broadcast()
   944  		cc.mu.Unlock()
   945  		return ctx.Err()
   946  	}
   947  }
   948  
   949  func (cc *ClientConn) sendGoAway() error {
   950  	cc.mu.Lock()
   951  	defer cc.mu.Unlock()
   952  	cc.wmu.Lock()
   953  	defer cc.wmu.Unlock()
   954  	if cc.closing {
   955  		// GOAWAY sent already
   956  		return nil
   957  	}
   958  	// Send a graceful shutdown frame to server
   959  	maxStreamID := cc.nextStreamID
   960  	if err := cc.fr.WriteGoAway(maxStreamID, ErrCodeNo, nil); err != nil {
   961  		return err
   962  	}
   963  	if err := cc.bw.Flush(); err != nil {
   964  		return err
   965  	}
   966  	// Prevent new requests
   967  	cc.closing = true
   968  	return nil
   969  }
   970  
   971  // closes the client connection immediately. In-flight requests are interrupted.
   972  // err is sent to streams.
   973  func (cc *ClientConn) closeForError(err error) error {
   974  	cc.mu.Lock()
   975  	defer cc.cond.Broadcast()
   976  	defer cc.mu.Unlock()
   977  	for id, cs := range cc.streams {
   978  		select {
   979  		case cs.resc <- resAndError{err: err}:
   980  		default:
   981  		}
   982  		cs.bufPipe.CloseWithError(err)
   983  		delete(cc.streams, id)
   984  	}
   985  	cc.closed = true
   986  	return cc.tconn.Close()
   987  }
   988  
   989  // Close closes the client connection immediately.
   990  //
   991  // In-flight requests are interrupted. For a graceful shutdown, use Shutdown instead.
   992  func (cc *ClientConn) Close() error {
   993  	err := errors.New("http2: client connection force closed via ClientConn.Close")
   994  	return cc.closeForError(err)
   995  }
   996  
   997  // closes the client connection immediately. In-flight requests are interrupted.
   998  func (cc *ClientConn) closeForLostPing() error {
   999  	err := errors.New("http2: client connection lost")
  1000  	return cc.closeForError(err)
  1001  }
  1002  
  1003  const maxAllocFrameSize = 512 << 10
  1004  
  1005  // frameBuffer returns a scratch buffer suitable for writing DATA frames.
  1006  // They're capped at the min of the peer's max frame size or 512KB
  1007  // (kinda arbitrarily), but definitely capped so we don't allocate 4GB
  1008  // bufers.
  1009  func (cc *ClientConn) frameScratchBuffer() []byte {
  1010  	cc.mu.Lock()
  1011  	size := cc.maxFrameSize
  1012  	if size > maxAllocFrameSize {
  1013  		size = maxAllocFrameSize
  1014  	}
  1015  	for i, buf := range cc.freeBuf {
  1016  		if len(buf) >= int(size) {
  1017  			cc.freeBuf[i] = nil
  1018  			cc.mu.Unlock()
  1019  			return buf[:size]
  1020  		}
  1021  	}
  1022  	cc.mu.Unlock()
  1023  	return make([]byte, size)
  1024  }
  1025  
  1026  func (cc *ClientConn) putFrameScratchBuffer(buf []byte) {
  1027  	cc.mu.Lock()
  1028  	defer cc.mu.Unlock()
  1029  	const maxBufs = 4 // arbitrary; 4 concurrent requests per conn? investigate.
  1030  	if len(cc.freeBuf) < maxBufs {
  1031  		cc.freeBuf = append(cc.freeBuf, buf)
  1032  		return
  1033  	}
  1034  	for i, old := range cc.freeBuf {
  1035  		if old == nil {
  1036  			cc.freeBuf[i] = buf
  1037  			return
  1038  		}
  1039  	}
  1040  	// forget about it.
  1041  }
  1042  
  1043  // errRequestCanceled is a copy of net/http's errRequestCanceled because it's not
  1044  // exported. At least they'll be DeepEqual for h1-vs-h2 comparisons tests.
  1045  var errRequestCanceled = errors.New("net/http: request canceled")
  1046  
  1047  func commaSeparatedTrailers(req *http.Request) (string, error) {
  1048  	keys := make([]string, 0, len(req.Trailer))
  1049  	for k := range req.Trailer {
  1050  		k = http.CanonicalHeaderKey(k)
  1051  		switch k {
  1052  		case "Transfer-Encoding", "Trailer", "Content-Length":
  1053  			return "", fmt.Errorf("invalid Trailer key %q", k)
  1054  		}
  1055  		keys = append(keys, k)
  1056  	}
  1057  	if len(keys) > 0 {
  1058  		sort.Strings(keys)
  1059  		return strings.Join(keys, ","), nil
  1060  	}
  1061  	return "", nil
  1062  }
  1063  
  1064  func (cc *ClientConn) responseHeaderTimeout() time.Duration {
  1065  	if cc.t.t1 != nil {
  1066  		return cc.t.t1.ResponseHeaderTimeout
  1067  	}
  1068  	// No way to do this (yet?) with just an http2.Transport. Probably
  1069  	// no need. Request.Cancel this is the new way. We only need to support
  1070  	// this for compatibility with the old http.Transport fields when
  1071  	// we're doing transparent http2.
  1072  	return 0
  1073  }
  1074  
  1075  // checkConnHeaders checks whether req has any invalid connection-level headers.
  1076  // per RFC 7540 section 8.1.2.2: Connection-Specific Header Fields.
  1077  // Certain headers are special-cased as okay but not transmitted later.
  1078  func checkConnHeaders(req *http.Request) error {
  1079  	if v := req.Header.Get("Upgrade"); v != "" {
  1080  		return fmt.Errorf("http2: invalid Upgrade request header: %q", req.Header["Upgrade"])
  1081  	}
  1082  	if vv := req.Header["Transfer-Encoding"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "chunked") {
  1083  		return fmt.Errorf("http2: invalid Transfer-Encoding request header: %q", vv)
  1084  	}
  1085  	if vv := req.Header["Connection"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && !strings.EqualFold(vv[0], "close") && !strings.EqualFold(vv[0], "keep-alive")) {
  1086  		return fmt.Errorf("http2: invalid Connection request header: %q", vv)
  1087  	}
  1088  	return nil
  1089  }
  1090  
  1091  // actualContentLength returns a sanitized version of
  1092  // req.ContentLength, where 0 actually means zero (not unknown) and -1
  1093  // means unknown.
  1094  func actualContentLength(req *http.Request) int64 {
  1095  	if req.Body == nil || req.Body == http.NoBody {
  1096  		return 0
  1097  	}
  1098  	if req.ContentLength != 0 {
  1099  		return req.ContentLength
  1100  	}
  1101  	return -1
  1102  }
  1103  
  1104  func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) {
  1105  	resp, _, err := cc.roundTrip(req)
  1106  	return resp, err
  1107  }
  1108  
  1109  func (cc *ClientConn) roundTrip(req *http.Request) (res *http.Response, gotErrAfterReqBodyWrite bool, err error) {
  1110  	if err := checkConnHeaders(req); err != nil {
  1111  		return nil, false, err
  1112  	}
  1113  	if cc.idleTimer != nil {
  1114  		cc.idleTimer.Stop()
  1115  	}
  1116  
  1117  	trailers, err := commaSeparatedTrailers(req)
  1118  	if err != nil {
  1119  		return nil, false, err
  1120  	}
  1121  	hasTrailers := trailers != ""
  1122  
  1123  	cc.mu.Lock()
  1124  	if err := cc.awaitOpenSlotForRequest(req); err != nil {
  1125  		cc.mu.Unlock()
  1126  		return nil, false, err
  1127  	}
  1128  
  1129  	body := req.Body
  1130  	contentLen := actualContentLength(req)
  1131  	hasBody := contentLen != 0
  1132  	requestedGzip := cc.requestGzip(req)
  1133  
  1134  	// we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,} (DATA is
  1135  	// sent by writeRequestBody below, along with any Trailers,
  1136  	// again in form HEADERS{1}, CONTINUATION{0,})
  1137  	hdrs, err := cc.encodeHeaders(req, requestedGzip, trailers, contentLen)
  1138  	if err != nil {
  1139  		cc.mu.Unlock()
  1140  		return nil, false, err
  1141  	}
  1142  
  1143  	cs := cc.newStream()
  1144  	cs.req = req
  1145  	cs.trace = httptrace.ContextClientTrace(req.Context())
  1146  	cs.requestedGzip = requestedGzip
  1147  	bodyWriter := cc.t.getBodyWriterState(cs, body)
  1148  	cs.on100 = bodyWriter.on100
  1149  
  1150  	defer func() {
  1151  		cc.wmu.Lock()
  1152  		werr := cc.werr
  1153  		cc.wmu.Unlock()
  1154  		if werr != nil {
  1155  			cc.Close()
  1156  		}
  1157  	}()
  1158  
  1159  	cc.wmu.Lock()
  1160  	endStream := !hasBody && !hasTrailers
  1161  	werr := cc.writeHeaders(cs.ID, endStream, int(cc.maxFrameSize), hdrs)
  1162  	cc.wmu.Unlock()
  1163  	traceWroteHeaders(cs.trace)
  1164  	cc.mu.Unlock()
  1165  
  1166  	if werr != nil {
  1167  		if hasBody {
  1168  			req.Body.Close() // per RoundTripper contract
  1169  			bodyWriter.cancel()
  1170  		}
  1171  		cc.forgetStreamID(cs.ID)
  1172  		// Don't bother sending a RST_STREAM (our write already failed;
  1173  		// no need to keep writing)
  1174  		traceWroteRequest(cs.trace, werr)
  1175  		return nil, false, werr
  1176  	}
  1177  
  1178  	var respHeaderTimer <-chan time.Time
  1179  	if hasBody {
  1180  		bodyWriter.scheduleBodyWrite()
  1181  	} else {
  1182  		traceWroteRequest(cs.trace, nil)
  1183  		if d := cc.responseHeaderTimeout(); d != 0 {
  1184  			timer := time.NewTimer(d)
  1185  			defer timer.Stop()
  1186  			respHeaderTimer = timer.C
  1187  		}
  1188  	}
  1189  
  1190  	readLoopResCh := cs.resc
  1191  	bodyWritten := false
  1192  	ctx := req.Context()
  1193  
  1194  	handleReadLoopResponse := func(re resAndError) (*http.Response, bool, error) {
  1195  		res := re.res
  1196  		if re.err != nil || res.StatusCode > 299 {
  1197  			// On error or status code 3xx, 4xx, 5xx, etc abort any
  1198  			// ongoing write, assuming that the server doesn't care
  1199  			// about our request body. If the server replied with 1xx or
  1200  			// 2xx, however, then assume the server DOES potentially
  1201  			// want our body (e.g. full-duplex streaming:
  1202  			// golang.org/issue/13444). If it turns out the server
  1203  			// doesn't, they'll RST_STREAM us soon enough. This is a
  1204  			// heuristic to avoid adding knobs to Transport. Hopefully
  1205  			// we can keep it.
  1206  			bodyWriter.cancel()
  1207  			cs.abortRequestBodyWrite(errStopReqBodyWrite)
  1208  			if hasBody && !bodyWritten {
  1209  				<-bodyWriter.resc
  1210  			}
  1211  		}
  1212  		if re.err != nil {
  1213  			cc.forgetStreamID(cs.ID)
  1214  			return nil, cs.getStartedWrite(), re.err
  1215  		}
  1216  		res.Request = req
  1217  		res.TLS = cc.tlsState
  1218  		return res, false, nil
  1219  	}
  1220  
  1221  	for {
  1222  		select {
  1223  		case re := <-readLoopResCh:
  1224  			return handleReadLoopResponse(re)
  1225  		case <-respHeaderTimer:
  1226  			if !hasBody || bodyWritten {
  1227  				cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  1228  			} else {
  1229  				bodyWriter.cancel()
  1230  				cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
  1231  				<-bodyWriter.resc
  1232  			}
  1233  			cc.forgetStreamID(cs.ID)
  1234  			return nil, cs.getStartedWrite(), errTimeout
  1235  		case <-ctx.Done():
  1236  			if !hasBody || bodyWritten {
  1237  				cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  1238  			} else {
  1239  				bodyWriter.cancel()
  1240  				cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
  1241  				<-bodyWriter.resc
  1242  			}
  1243  			cc.forgetStreamID(cs.ID)
  1244  			return nil, cs.getStartedWrite(), ctx.Err()
  1245  		case <-req.Cancel:
  1246  			if !hasBody || bodyWritten {
  1247  				cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  1248  			} else {
  1249  				bodyWriter.cancel()
  1250  				cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
  1251  				<-bodyWriter.resc
  1252  			}
  1253  			cc.forgetStreamID(cs.ID)
  1254  			return nil, cs.getStartedWrite(), errRequestCanceled
  1255  		case <-cs.peerReset:
  1256  			// processResetStream already removed the
  1257  			// stream from the streams map; no need for
  1258  			// forgetStreamID.
  1259  			return nil, cs.getStartedWrite(), cs.resetErr
  1260  		case err := <-bodyWriter.resc:
  1261  			bodyWritten = true
  1262  			// Prefer the read loop's response, if available. Issue 16102.
  1263  			select {
  1264  			case re := <-readLoopResCh:
  1265  				return handleReadLoopResponse(re)
  1266  			default:
  1267  			}
  1268  			if err != nil {
  1269  				cc.forgetStreamID(cs.ID)
  1270  				return nil, cs.getStartedWrite(), err
  1271  			}
  1272  			if d := cc.responseHeaderTimeout(); d != 0 {
  1273  				timer := time.NewTimer(d)
  1274  				defer timer.Stop()
  1275  				respHeaderTimer = timer.C
  1276  			}
  1277  		}
  1278  	}
  1279  }
  1280  
  1281  // awaitOpenSlotForRequest waits until len(streams) < maxConcurrentStreams.
  1282  // Must hold cc.mu.
  1283  func (cc *ClientConn) awaitOpenSlotForRequest(req *http.Request) error {
  1284  	var waitingForConn chan struct{}
  1285  	var waitingForConnErr error // guarded by cc.mu
  1286  	for {
  1287  		cc.lastActive = time.Now()
  1288  		if cc.closed || !cc.canTakeNewRequestLocked() {
  1289  			if waitingForConn != nil {
  1290  				close(waitingForConn)
  1291  			}
  1292  			return errClientConnUnusable
  1293  		}
  1294  		cc.lastIdle = time.Time{}
  1295  		if int64(len(cc.streams))+1 <= int64(cc.maxConcurrentStreams) {
  1296  			if waitingForConn != nil {
  1297  				close(waitingForConn)
  1298  			}
  1299  			return nil
  1300  		}
  1301  		// Unfortunately, we cannot wait on a condition variable and channel at
  1302  		// the same time, so instead, we spin up a goroutine to check if the
  1303  		// request is canceled while we wait for a slot to open in the connection.
  1304  		if waitingForConn == nil {
  1305  			waitingForConn = make(chan struct{})
  1306  			go func() {
  1307  				if err := awaitRequestCancel(req, waitingForConn); err != nil {
  1308  					cc.mu.Lock()
  1309  					waitingForConnErr = err
  1310  					cc.cond.Broadcast()
  1311  					cc.mu.Unlock()
  1312  				}
  1313  			}()
  1314  		}
  1315  		cc.pendingRequests++
  1316  		cc.cond.Wait()
  1317  		cc.pendingRequests--
  1318  		if waitingForConnErr != nil {
  1319  			return waitingForConnErr
  1320  		}
  1321  	}
  1322  }
  1323  
  1324  // requires cc.wmu be held
  1325  func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, maxFrameSize int, hdrs []byte) error {
  1326  	first := true // first frame written (HEADERS is first, then CONTINUATION)
  1327  	for len(hdrs) > 0 && cc.werr == nil {
  1328  		chunk := hdrs
  1329  		if len(chunk) > maxFrameSize {
  1330  			chunk = chunk[:maxFrameSize]
  1331  		}
  1332  		hdrs = hdrs[len(chunk):]
  1333  		endHeaders := len(hdrs) == 0
  1334  		if first {
  1335  			cc.fr.WriteHeaders(HeadersFrameParam{
  1336  				StreamID:      streamID,
  1337  				BlockFragment: chunk,
  1338  				EndStream:     endStream,
  1339  				EndHeaders:    endHeaders,
  1340  			})
  1341  			first = false
  1342  		} else {
  1343  			cc.fr.WriteContinuation(streamID, endHeaders, chunk)
  1344  		}
  1345  	}
  1346  	// TODO(bradfitz): this Flush could potentially block (as
  1347  	// could the WriteHeaders call(s) above), which means they
  1348  	// wouldn't respond to Request.Cancel being readable. That's
  1349  	// rare, but this should probably be in a goroutine.
  1350  	cc.bw.Flush()
  1351  	return cc.werr
  1352  }
  1353  
  1354  func (cc *ClientConn) requestGzip(req *http.Request) bool {
  1355  	// TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere?
  1356  	if !cc.t.disableCompression() &&
  1357  		req.Header.Get("Accept-Encoding") == "" &&
  1358  		req.Header.Get("Range") == "" &&
  1359  		req.Method != "HEAD" {
  1360  		// Request gzip only, not deflate. Deflate is ambiguous and
  1361  		// not as universally supported anyway.
  1362  		// See: https://zlib.net/zlib_faq.html#faq39
  1363  		//
  1364  		// Note that we don't request this for HEAD requests,
  1365  		// due to a bug in nginx:
  1366  		//   http://trac.nginx.org/nginx/ticket/358
  1367  		//   https://golang.org/issue/5522
  1368  		//
  1369  		// We don't request gzip if the request is for a range, since
  1370  		// auto-decoding a portion of a gzipped document will just fail
  1371  		// anyway. See https://golang.org/issue/8923
  1372  		return true
  1373  	}
  1374  	return false
  1375  }
  1376  
  1377  // internal error values; they don't escape to callers
  1378  var (
  1379  	// abort request body write; don't send cancel
  1380  	errStopReqBodyWrite = errors.New("http2: aborting request body write")
  1381  
  1382  	// abort request body write, but send stream reset of cancel.
  1383  	errStopReqBodyWriteAndCancel = errors.New("http2: canceling request")
  1384  
  1385  	errReqBodyTooLong = errors.New("http2: request body larger than specified content length")
  1386  )
  1387  
  1388  func (cs *clientStream) writeRequestBody(body io.Reader, bodyCloser io.Closer) (err error) {
  1389  	cc := cs.cc
  1390  	sentEnd := false // whether we sent the final DATA frame w/ END_STREAM
  1391  	buf := cc.frameScratchBuffer()
  1392  	defer cc.putFrameScratchBuffer(buf)
  1393  
  1394  	defer func() {
  1395  		traceWroteRequest(cs.trace, err)
  1396  		// TODO: write h12Compare test showing whether
  1397  		// Request.Body is closed by the Transport,
  1398  		// and in multiple cases: server replies <=299 and >299
  1399  		// while still writing request body
  1400  		cerr := bodyCloser.Close()
  1401  		if err == nil {
  1402  			err = cerr
  1403  		}
  1404  	}()
  1405  
  1406  	req := cs.req
  1407  	hasTrailers := req.Trailer != nil
  1408  	remainLen := actualContentLength(req)
  1409  	hasContentLen := remainLen != -1
  1410  
  1411  	var sawEOF bool
  1412  	for !sawEOF {
  1413  		n, err := body.Read(buf[:len(buf)-1])
  1414  		if hasContentLen {
  1415  			remainLen -= int64(n)
  1416  			if remainLen == 0 && err == nil {
  1417  				// The request body's Content-Length was predeclared and
  1418  				// we just finished reading it all, but the underlying io.Reader
  1419  				// returned the final chunk with a nil error (which is one of
  1420  				// the two valid things a Reader can do at EOF). Because we'd prefer
  1421  				// to send the END_STREAM bit early, double-check that we're actually
  1422  				// at EOF. Subsequent reads should return (0, EOF) at this point.
  1423  				// If either value is different, we return an error in one of two ways below.
  1424  				var n1 int
  1425  				n1, err = body.Read(buf[n:])
  1426  				remainLen -= int64(n1)
  1427  			}
  1428  			if remainLen < 0 {
  1429  				err = errReqBodyTooLong
  1430  				cc.writeStreamReset(cs.ID, ErrCodeCancel, err)
  1431  				return err
  1432  			}
  1433  		}
  1434  		if err == io.EOF {
  1435  			sawEOF = true
  1436  			err = nil
  1437  		} else if err != nil {
  1438  			cc.writeStreamReset(cs.ID, ErrCodeCancel, err)
  1439  			return err
  1440  		}
  1441  
  1442  		remain := buf[:n]
  1443  		for len(remain) > 0 && err == nil {
  1444  			var allowed int32
  1445  			allowed, err = cs.awaitFlowControl(len(remain))
  1446  			switch {
  1447  			case err == errStopReqBodyWrite:
  1448  				return err
  1449  			case err == errStopReqBodyWriteAndCancel:
  1450  				cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  1451  				return err
  1452  			case err != nil:
  1453  				return err
  1454  			}
  1455  			cc.wmu.Lock()
  1456  			data := remain[:allowed]
  1457  			remain = remain[allowed:]
  1458  			sentEnd = sawEOF && len(remain) == 0 && !hasTrailers
  1459  			err = cc.fr.WriteData(cs.ID, sentEnd, data)
  1460  			if err == nil {
  1461  				// TODO(bradfitz): this flush is for latency, not bandwidth.
  1462  				// Most requests won't need this. Make this opt-in or
  1463  				// opt-out?  Use some heuristic on the body type? Nagel-like
  1464  				// timers?  Based on 'n'? Only last chunk of this for loop,
  1465  				// unless flow control tokens are low? For now, always.
  1466  				// If we change this, see comment below.
  1467  				err = cc.bw.Flush()
  1468  			}
  1469  			cc.wmu.Unlock()
  1470  		}
  1471  		if err != nil {
  1472  			return err
  1473  		}
  1474  	}
  1475  
  1476  	if sentEnd {
  1477  		// Already sent END_STREAM (which implies we have no
  1478  		// trailers) and flushed, because currently all
  1479  		// WriteData frames above get a flush. So we're done.
  1480  		return nil
  1481  	}
  1482  
  1483  	var trls []byte
  1484  	if hasTrailers {
  1485  		cc.mu.Lock()
  1486  		trls, err = cc.encodeTrailers(req)
  1487  		cc.mu.Unlock()
  1488  		if err != nil {
  1489  			cc.writeStreamReset(cs.ID, ErrCodeInternal, err)
  1490  			cc.forgetStreamID(cs.ID)
  1491  			return err
  1492  		}
  1493  	}
  1494  
  1495  	cc.mu.Lock()
  1496  	maxFrameSize := int(cc.maxFrameSize)
  1497  	cc.mu.Unlock()
  1498  
  1499  	cc.wmu.Lock()
  1500  	defer cc.wmu.Unlock()
  1501  
  1502  	// Two ways to send END_STREAM: either with trailers, or
  1503  	// with an empty DATA frame.
  1504  	if len(trls) > 0 {
  1505  		err = cc.writeHeaders(cs.ID, true, maxFrameSize, trls)
  1506  	} else {
  1507  		err = cc.fr.WriteData(cs.ID, true, nil)
  1508  	}
  1509  	if ferr := cc.bw.Flush(); ferr != nil && err == nil {
  1510  		err = ferr
  1511  	}
  1512  	return err
  1513  }
  1514  
  1515  // awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
  1516  // control tokens from the server.
  1517  // It returns either the non-zero number of tokens taken or an error
  1518  // if the stream is dead.
  1519  func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
  1520  	cc := cs.cc
  1521  	cc.mu.Lock()
  1522  	defer cc.mu.Unlock()
  1523  	for {
  1524  		if cc.closed {
  1525  			return 0, errClientConnClosed
  1526  		}
  1527  		if cs.stopReqBody != nil {
  1528  			return 0, cs.stopReqBody
  1529  		}
  1530  		if err := cs.checkResetOrDone(); err != nil {
  1531  			return 0, err
  1532  		}
  1533  		if a := cs.flow.available(); a > 0 {
  1534  			take := a
  1535  			if int(take) > maxBytes {
  1536  
  1537  				take = int32(maxBytes) // can't truncate int; take is int32
  1538  			}
  1539  			if take > int32(cc.maxFrameSize) {
  1540  				take = int32(cc.maxFrameSize)
  1541  			}
  1542  			cs.flow.take(take)
  1543  			return take, nil
  1544  		}
  1545  		cc.cond.Wait()
  1546  	}
  1547  }
  1548  
  1549  // requires cc.mu be held.
  1550  func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) {
  1551  	cc.hbuf.Reset()
  1552  
  1553  	host := req.Host
  1554  	if host == "" {
  1555  		host = req.URL.Host
  1556  	}
  1557  	host, err := httpguts.PunycodeHostPort(host)
  1558  	if err != nil {
  1559  		return nil, err
  1560  	}
  1561  
  1562  	var path string
  1563  	if req.Method != "CONNECT" {
  1564  		path = req.URL.RequestURI()
  1565  		if !validPseudoPath(path) {
  1566  			orig := path
  1567  			path = strings.TrimPrefix(path, req.URL.Scheme+"://"+host)
  1568  			if !validPseudoPath(path) {
  1569  				if req.URL.Opaque != "" {
  1570  					return nil, fmt.Errorf("invalid request :path %q from URL.Opaque = %q", orig, req.URL.Opaque)
  1571  				} else {
  1572  					return nil, fmt.Errorf("invalid request :path %q", orig)
  1573  				}
  1574  			}
  1575  		}
  1576  	}
  1577  
  1578  	// Check for any invalid headers and return an error before we
  1579  	// potentially pollute our hpack state. (We want to be able to
  1580  	// continue to reuse the hpack encoder for future requests)
  1581  	for k, vv := range req.Header {
  1582  		if !httpguts.ValidHeaderFieldName(k) {
  1583  			// If the header is magic key, the headers would have been ordered
  1584  			// by this step. It is ok to delete and not raise an error
  1585  			if k == http.HeaderOrderKey || k == http.PHeaderOrderKey {
  1586  				continue
  1587  			}
  1588  
  1589  			return nil, fmt.Errorf("invalid HTTP header name %q", k)
  1590  		}
  1591  		for _, v := range vv {
  1592  			if !httpguts.ValidHeaderFieldValue(v) {
  1593  				return nil, fmt.Errorf("invalid HTTP header value %q for header %q", v, k)
  1594  			}
  1595  		}
  1596  	}
  1597  
  1598  	enumerateHeaders := func(f func(name, value string)) {
  1599  		// 8.1.2.3 Request Pseudo-Header Fields
  1600  		// The :path pseudo-header field includes the path and query parts of the
  1601  		// target URI (the path-absolute production and optionally a '?' character
  1602  		// followed by the query production (see Sections 3.3 and 3.4 of
  1603  		// [RFC3986]).
  1604  
  1605  		pHeaderOrder, ok := req.Header[http.PHeaderOrderKey]
  1606  		m := req.Method
  1607  		if m == "" {
  1608  			m = http.MethodGet
  1609  		}
  1610  		if ok {
  1611  			// follow based on pseudo header order
  1612  			for _, p := range pHeaderOrder {
  1613  				switch p {
  1614  				case ":authority":
  1615  					f(":authority", host)
  1616  				case ":method":
  1617  					f(":method", req.Method)
  1618  				case ":path":
  1619  					if req.Method != "CONNECT" {
  1620  						f(":path", path)
  1621  					}
  1622  				case ":scheme":
  1623  					if req.Method != "CONNECT" {
  1624  						f(":scheme", req.URL.Scheme)
  1625  					}
  1626  
  1627  				// (zMrKrabz): Currently skips over unrecognized pheader fields,
  1628  				// should throw error or something but works for now.
  1629  				default:
  1630  					continue
  1631  				}
  1632  			}
  1633  		} else {
  1634  			f(":authority", host)
  1635  			f(":method", m)
  1636  			if req.Method != "CONNECT" {
  1637  				f(":path", path)
  1638  				f(":scheme", req.URL.Scheme)
  1639  			}
  1640  		}
  1641  		if trailers != "" {
  1642  			f("trailer", trailers)
  1643  		}
  1644  
  1645  		// Should clone, because this function is called twice; to read and to write.
  1646  		// If headers are added to the req, then headers would be added twice.
  1647  		hdrs := req.Header.Clone()
  1648  		if _, ok := req.Header["content-length"]; !ok && shouldSendReqContentLength(req.Method, contentLength) {
  1649  			hdrs["content-length"] = []string{strconv.FormatInt(contentLength, 10)}
  1650  		}
  1651  
  1652  		// Does not include accept-encoding header if its defined in req.Header
  1653  		if _, ok := hdrs["accept-encoding"]; !ok && addGzipHeader {
  1654  			hdrs["accept-encoding"] = []string{"gzip, deflate, br"}
  1655  		}
  1656  
  1657  		// Formats and writes headers with f function
  1658  		var didUA bool
  1659  		var kvs []http.HeaderKeyValues
  1660  
  1661  		if headerOrder, ok := hdrs[http.HeaderOrderKey]; ok {
  1662  			order := make(map[string]int)
  1663  			for i, v := range headerOrder {
  1664  				order[v] = i
  1665  			}
  1666  			kvs, _ = hdrs.SortedKeyValuesBy(order, make(map[string]bool))
  1667  		} else {
  1668  			kvs, _ = hdrs.SortedKeyValues(make(map[string]bool))
  1669  		}
  1670  
  1671  		for _, kv := range kvs {
  1672  			if strings.EqualFold(kv.Key, "host") {
  1673  				// Host is :authority, already sent.
  1674  				continue
  1675  			} else if strings.EqualFold(kv.Key, "connection") || strings.EqualFold(kv.Key, "proxy-connection") ||
  1676  				strings.EqualFold(kv.Key, "transfer-encoding") || strings.EqualFold(kv.Key, "upgrade") ||
  1677  				strings.EqualFold(kv.Key, "keep-alive") {
  1678  				// Per 8.1.2.2 Connection-Specific Header
  1679  				// Fields, don't send connection-specific
  1680  				// fields. We have already checked if any
  1681  				// are error-worthy so just ignore the rest.
  1682  				continue
  1683  			} else if strings.EqualFold(kv.Key, "cookie") {
  1684  				// Per 8.1.2.5 To allow for better compression efficiency, the
  1685  				// Cookie header field MAY be split into separate header fields,
  1686  				// each with one or more cookie-pairs.
  1687  				for _, v := range kv.Values {
  1688  					for {
  1689  						p := strings.IndexByte(v, ';')
  1690  						if p < 0 {
  1691  							break
  1692  						}
  1693  						f("cookie", v[:p])
  1694  						p++
  1695  						// strip space after semicolon if any.
  1696  						for p+1 <= len(v) && v[p] == ' ' {
  1697  							p++
  1698  						}
  1699  						v = v[p:]
  1700  					}
  1701  					if len(v) > 0 {
  1702  						f("cookie", v)
  1703  					}
  1704  				}
  1705  				continue
  1706  			} else if strings.EqualFold(kv.Key, "user-agent") {
  1707  				// Match Go's http1 behavior: at most one
  1708  				// User-Agent. If set to nil or empty string,
  1709  				// then omit it. Otherwise if not mentioned,
  1710  				// include the default (below).
  1711  				didUA = true
  1712  				if len(kv.Values) > 1 {
  1713  					kv.Values = kv.Values[:1]
  1714  				}
  1715  
  1716  				if kv.Values[0] == "" {
  1717  					continue
  1718  				}
  1719  			}
  1720  
  1721  			for _, v := range kv.Values {
  1722  				f(kv.Key, v)
  1723  			}
  1724  		}
  1725  
  1726  		if !didUA {
  1727  			f("user-agent", defaultUserAgent)
  1728  		}
  1729  	}
  1730  
  1731  	// Do a first pass over the headers counting bytes to ensure
  1732  	// we don't exceed cc.peerMaxHeaderListSize. This is done as a
  1733  	// separate pass before encoding the headers to prevent
  1734  	// modifying the hpack state.
  1735  	hlSize := uint64(0)
  1736  	enumerateHeaders(func(name, value string) {
  1737  		hf := hpack.HeaderField{Name: name, Value: value}
  1738  		hlSize += uint64(hf.Size())
  1739  	})
  1740  
  1741  	if hlSize > cc.peerMaxHeaderListSize {
  1742  		return nil, errRequestHeaderListSize
  1743  	}
  1744  
  1745  	trace := httptrace.ContextClientTrace(req.Context())
  1746  	traceHeaders := traceHasWroteHeaderField(trace)
  1747  
  1748  	// Header list size is ok. Write the headers.
  1749  	enumerateHeaders(func(name, value string) {
  1750  		// skips over writing magic key headers
  1751  		if name == http.PHeaderOrderKey || name == http.HeaderOrderKey {
  1752  			return
  1753  		}
  1754  
  1755  		name = strings.ToLower(name)
  1756  		cc.writeHeader(name, value)
  1757  		if traceHeaders {
  1758  			traceWroteHeaderField(trace, name, value)
  1759  		}
  1760  	})
  1761  
  1762  	return cc.hbuf.Bytes(), nil
  1763  }
  1764  
  1765  // shouldSendReqContentLength reports whether the http2.Transport should send
  1766  // a "content-length" request header. This logic is basically a copy of the net/http
  1767  // transferWriter.shouldSendContentLength.
  1768  // The contentLength is the corrected contentLength (so 0 means actually 0, not unknown).
  1769  // -1 means unknown.
  1770  func shouldSendReqContentLength(method string, contentLength int64) bool {
  1771  	if contentLength > 0 {
  1772  		return true
  1773  	}
  1774  	if contentLength < 0 {
  1775  		return false
  1776  	}
  1777  	// For zero bodies, whether we send a content-length depends on the method.
  1778  	// It also kinda doesn't matter for http2 either way, with END_STREAM.
  1779  	switch method {
  1780  	case "POST", "PUT", "PATCH":
  1781  		return true
  1782  	default:
  1783  		return false
  1784  	}
  1785  }
  1786  
  1787  // requires cc.mu be held.
  1788  func (cc *ClientConn) encodeTrailers(req *http.Request) ([]byte, error) {
  1789  	cc.hbuf.Reset()
  1790  
  1791  	hlSize := uint64(0)
  1792  	for k, vv := range req.Trailer {
  1793  		for _, v := range vv {
  1794  			hf := hpack.HeaderField{Name: k, Value: v}
  1795  			hlSize += uint64(hf.Size())
  1796  		}
  1797  	}
  1798  	if hlSize > cc.peerMaxHeaderListSize {
  1799  		return nil, errRequestHeaderListSize
  1800  	}
  1801  
  1802  	for k, vv := range req.Trailer {
  1803  		// Transfer-Encoding, etc.. have already been filtered at the
  1804  		// start of RoundTrip
  1805  		lowKey := strings.ToLower(k)
  1806  		for _, v := range vv {
  1807  			cc.writeHeader(lowKey, v)
  1808  		}
  1809  	}
  1810  	return cc.hbuf.Bytes(), nil
  1811  }
  1812  
  1813  func (cc *ClientConn) writeHeader(name, value string) {
  1814  	if VerboseLogs {
  1815  		log.Printf("http2: Transport encoding header %q = %q", name, value)
  1816  	}
  1817  	cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
  1818  }
  1819  
  1820  type resAndError struct {
  1821  	_   incomparable
  1822  	res *http.Response
  1823  	err error
  1824  }
  1825  
  1826  // requires cc.mu be held.
  1827  func (cc *ClientConn) newStreamWithID(streamID uint32, incNext bool) *clientStream {
  1828  	cs := &clientStream{
  1829  		cc:        cc,
  1830  		ID:        streamID,
  1831  		resc:      make(chan resAndError, 1),
  1832  		peerReset: make(chan struct{}),
  1833  		done:      make(chan struct{}),
  1834  	}
  1835  	cs.flow.add(int32(cc.initialWindowSize))
  1836  	cs.flow.setConnFlow(&cc.flow)
  1837  	cs.inflow.add(transportDefaultStreamFlow)
  1838  	cs.inflow.setConnFlow(&cc.inflow)
  1839  	cc.streams[cs.ID] = cs
  1840  
  1841  	if incNext {
  1842  		cc.nextStreamID += 2
  1843  	}
  1844  	return cs
  1845  }
  1846  
  1847  func (cc *ClientConn) newStream() *clientStream {
  1848  	return cc.newStreamWithID(cc.nextStreamID, true)
  1849  }
  1850  
  1851  func (cc *ClientConn) forgetStreamID(id uint32) {
  1852  	cc.streamByID(id, true)
  1853  }
  1854  
  1855  func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream {
  1856  	cc.mu.Lock()
  1857  	defer cc.mu.Unlock()
  1858  	cs := cc.streams[id]
  1859  	if andRemove && cs != nil && !cc.closed {
  1860  		cc.lastActive = time.Now()
  1861  		delete(cc.streams, id)
  1862  		if len(cc.streams) == 0 && cc.idleTimer != nil {
  1863  			cc.idleTimer.Reset(cc.idleTimeout)
  1864  			cc.lastIdle = time.Now()
  1865  		}
  1866  		close(cs.done)
  1867  		// Wake up checkResetOrDone via clientStream.awaitFlowControl and
  1868  		// wake up RoundTrip if there is a pending request.
  1869  		cc.cond.Broadcast()
  1870  	}
  1871  	return cs
  1872  }
  1873  
  1874  // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.
  1875  type clientConnReadLoop struct {
  1876  	_             incomparable
  1877  	cc            *ClientConn
  1878  	closeWhenIdle bool
  1879  }
  1880  
  1881  // readLoop runs in its own goroutine and reads and dispatches frames.
  1882  func (cc *ClientConn) readLoop() {
  1883  	rl := &clientConnReadLoop{cc: cc}
  1884  	defer rl.cleanup()
  1885  	cc.readerErr = rl.run()
  1886  	if ce, ok := cc.readerErr.(ConnectionError); ok {
  1887  		cc.wmu.Lock()
  1888  		cc.fr.WriteGoAway(0, ErrCode(ce), nil)
  1889  		cc.wmu.Unlock()
  1890  	}
  1891  }
  1892  
  1893  // GoAwayError is returned by the Transport when the server closes the
  1894  // TCP connection after sending a GOAWAY frame.
  1895  type GoAwayError struct {
  1896  	LastStreamID uint32
  1897  	ErrCode      ErrCode
  1898  	DebugData    string
  1899  }
  1900  
  1901  func (e GoAwayError) Error() string {
  1902  	return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q",
  1903  		e.LastStreamID, e.ErrCode, e.DebugData)
  1904  }
  1905  
  1906  func isEOFOrNetReadError(err error) bool {
  1907  	if err == io.EOF {
  1908  		return true
  1909  	}
  1910  	ne, ok := err.(*net.OpError)
  1911  	return ok && ne.Op == "read"
  1912  }
  1913  
  1914  func (rl *clientConnReadLoop) cleanup() {
  1915  	cc := rl.cc
  1916  	defer cc.tconn.Close()
  1917  	defer cc.t.connPool().MarkDead(cc)
  1918  	defer close(cc.readerDone)
  1919  
  1920  	if cc.idleTimer != nil {
  1921  		cc.idleTimer.Stop()
  1922  	}
  1923  
  1924  	// Close any response bodies if the server closes prematurely.
  1925  	// TODO: also do this if we've written the headers but not
  1926  	// gotten a response yet.
  1927  	err := cc.readerErr
  1928  	cc.mu.Lock()
  1929  	if cc.goAway != nil && isEOFOrNetReadError(err) {
  1930  		err = GoAwayError{
  1931  			LastStreamID: cc.goAway.LastStreamID,
  1932  			ErrCode:      cc.goAway.ErrCode,
  1933  			DebugData:    cc.goAwayDebug,
  1934  		}
  1935  	} else if err == io.EOF {
  1936  		err = io.ErrUnexpectedEOF
  1937  	}
  1938  	for _, cs := range cc.streams {
  1939  		cs.bufPipe.CloseWithError(err) // no-op if already closed
  1940  		select {
  1941  		case cs.resc <- resAndError{err: err}:
  1942  		default:
  1943  		}
  1944  		close(cs.done)
  1945  	}
  1946  	cc.closed = true
  1947  	cc.cond.Broadcast()
  1948  	cc.mu.Unlock()
  1949  }
  1950  
  1951  func (rl *clientConnReadLoop) run() error {
  1952  	cc := rl.cc
  1953  	rl.closeWhenIdle = cc.t.disableKeepAlives() || cc.singleUse
  1954  	gotReply := false // ever saw a HEADERS reply
  1955  	gotSettings := false
  1956  	readIdleTimeout := cc.t.ReadIdleTimeout
  1957  	var t *time.Timer
  1958  	if readIdleTimeout != 0 {
  1959  		t = time.AfterFunc(readIdleTimeout, cc.healthCheck)
  1960  		defer t.Stop()
  1961  	}
  1962  	for {
  1963  		f, err := cc.fr.ReadFrame()
  1964  		if t != nil {
  1965  			t.Reset(readIdleTimeout)
  1966  		}
  1967  		if err != nil {
  1968  			cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err)
  1969  		}
  1970  		if se, ok := err.(StreamError); ok {
  1971  			if cs := cc.streamByID(se.StreamID, false); cs != nil {
  1972  				cs.cc.writeStreamReset(cs.ID, se.Code, err)
  1973  				cs.cc.forgetStreamID(cs.ID)
  1974  				if se.Cause == nil {
  1975  					se.Cause = cc.fr.errDetail
  1976  				}
  1977  				rl.endStreamError(cs, se)
  1978  			}
  1979  			continue
  1980  		} else if err != nil {
  1981  			return err
  1982  		}
  1983  		if VerboseLogs {
  1984  			cc.vlogf("http2: Transport received %s", summarizeFrame(f))
  1985  		}
  1986  		if !gotSettings {
  1987  			if _, ok := f.(*SettingsFrame); !ok {
  1988  				cc.logf("protocol error: received %T before a SETTINGS frame", f)
  1989  				return ConnectionError(ErrCodeProtocol)
  1990  			}
  1991  			gotSettings = true
  1992  		}
  1993  		maybeIdle := false // whether frame might transition us to idle
  1994  
  1995  		switch f := f.(type) {
  1996  		case *MetaHeadersFrame:
  1997  			err = rl.processHeaders(f)
  1998  			maybeIdle = true
  1999  			gotReply = true
  2000  		case *DataFrame:
  2001  			err = rl.processData(f)
  2002  			maybeIdle = true
  2003  		case *GoAwayFrame:
  2004  			err = rl.processGoAway(f)
  2005  			maybeIdle = true
  2006  		case *RSTStreamFrame:
  2007  			err = rl.processResetStream(f)
  2008  			maybeIdle = true
  2009  		case *SettingsFrame:
  2010  			err = rl.processSettings(f)
  2011  		case *MetaPushPromiseFrame:
  2012  			cc.vlogf("http2: handling push promise frame")
  2013  			err = rl.processPushPromise(f)
  2014  		case *WindowUpdateFrame:
  2015  			err = rl.processWindowUpdate(f)
  2016  		case *PingFrame:
  2017  			err = rl.processPing(f)
  2018  		default:
  2019  			cc.logf("Transport: unhandled response frame type %T", f)
  2020  		}
  2021  		if err != nil {
  2022  			if VerboseLogs {
  2023  				cc.vlogf("http2: Transport conn %p received error from processing frame %v: %v", cc, summarizeFrame(f), err)
  2024  			}
  2025  			return err
  2026  		}
  2027  		if rl.closeWhenIdle && gotReply && maybeIdle {
  2028  			cc.closeIfIdle()
  2029  		}
  2030  	}
  2031  }
  2032  
  2033  func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error {
  2034  	cc := rl.cc
  2035  	cs := cc.streamByID(f.StreamID, false)
  2036  	if cs == nil {
  2037  		// We'd get here if we canceled a request while the
  2038  		// server had its response still in flight. So if this
  2039  		// was just something we canceled, ignore it.
  2040  		return nil
  2041  	}
  2042  	if f.StreamEnded() {
  2043  		cs.gotEndStream = true
  2044  		// Issue 20521: If the stream has ended, streamByID() causes
  2045  		// clientStream.done to be closed, which causes the request's bodyWriter
  2046  		// to be closed with an errStreamClosed, which may be received by
  2047  		// clientConn.RoundTrip before the result of processing these headers.
  2048  		// Deferring stream closure allows the header processing to occur first.
  2049  		// clientConn.RoundTrip may still receive the bodyWriter error first, but
  2050  		// the fix for issue 16102 prioritises any response.
  2051  		//
  2052  		// Issue 22413: If there is no request body, we should close the
  2053  		// stream before writing to cs.resc so that the stream is closed
  2054  		// immediately once RoundTrip returns.
  2055  		if cs.req.Body != nil {
  2056  			defer cc.forgetStreamID(f.StreamID)
  2057  		} else {
  2058  			cc.forgetStreamID(f.StreamID)
  2059  		}
  2060  	}
  2061  	if !cs.firstByte {
  2062  		if cs.trace != nil {
  2063  			// TODO(bradfitz): move first response byte earlier,
  2064  			// when we first read the 9 byte header, not waiting
  2065  			// until all the HEADERS+CONTINUATION frames have been
  2066  			// merged. This works for now.
  2067  			traceFirstResponseByte(cs.trace)
  2068  		}
  2069  		cs.firstByte = true
  2070  	}
  2071  	if !cs.pastHeaders {
  2072  		cs.pastHeaders = true
  2073  	} else {
  2074  		return rl.processTrailers(cs, f)
  2075  	}
  2076  
  2077  	res, err := rl.handleResponse(cs, f)
  2078  	if err != nil {
  2079  		if _, ok := err.(ConnectionError); ok {
  2080  			return err
  2081  		}
  2082  		// Any other error type is a stream error.
  2083  		cs.cc.writeStreamReset(f.StreamID, ErrCodeProtocol, err)
  2084  		cc.forgetStreamID(cs.ID)
  2085  		cs.resc <- resAndError{err: err}
  2086  		return nil // return nil from process* funcs to keep conn alive
  2087  	}
  2088  	if res == nil {
  2089  		// (nil, nil) special case. See handleResponse docs.
  2090  		return nil
  2091  	}
  2092  	cs.resTrailer = &res.Trailer
  2093  	cs.resc <- resAndError{res: res}
  2094  	return nil
  2095  }
  2096  
  2097  // may return error types nil, or ConnectionError. Any other error value
  2098  // is a StreamError of type ErrCodeProtocol. The returned error in that case
  2099  // is the detail.
  2100  //
  2101  // As a special case, handleResponse may return (nil, nil) to skip the
  2102  // frame (currently only used for 1xx responses).
  2103  func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFrame) (*http.Response, error) {
  2104  	if f.Truncated {
  2105  		return nil, errResponseHeaderListSize
  2106  	}
  2107  
  2108  	status := f.PseudoValue("status")
  2109  	if status == "" {
  2110  		return nil, errors.New("malformed response from server: missing status pseudo header")
  2111  	}
  2112  	statusCode, err := strconv.Atoi(status)
  2113  	if err != nil {
  2114  		return nil, errors.New("malformed response from server: malformed non-numeric status pseudo header")
  2115  	}
  2116  
  2117  	regularFields := f.RegularFields()
  2118  	strs := make([]string, len(regularFields))
  2119  	header := make(http.Header, len(regularFields))
  2120  	res := &http.Response{
  2121  		Proto:      "HTTP/2.0",
  2122  		ProtoMajor: 2,
  2123  		Header:     header,
  2124  		StatusCode: statusCode,
  2125  		Status:     status + " " + http.StatusText(statusCode),
  2126  	}
  2127  	for _, hf := range regularFields {
  2128  		key := http.CanonicalHeaderKey(hf.Name)
  2129  		if key == "Trailer" {
  2130  			t := res.Trailer
  2131  			if t == nil {
  2132  				t = make(http.Header)
  2133  				res.Trailer = t
  2134  			}
  2135  			foreachHeaderElement(hf.Value, func(v string) {
  2136  				t[http.CanonicalHeaderKey(v)] = nil
  2137  			})
  2138  		} else {
  2139  			vv := header[key]
  2140  			if vv == nil && len(strs) > 0 {
  2141  				// More than likely this will be a single-element key.
  2142  				// Most headers aren't multi-valued.
  2143  				// Set the capacity on strs[0] to 1, so any future append
  2144  				// won't extend the slice into the other strings.
  2145  				vv, strs = strs[:1:1], strs[1:]
  2146  				vv[0] = hf.Value
  2147  				header[key] = vv
  2148  			} else {
  2149  				header[key] = append(vv, hf.Value)
  2150  			}
  2151  		}
  2152  	}
  2153  
  2154  	if statusCode >= 100 && statusCode <= 199 {
  2155  		cs.num1xx++
  2156  		const max1xxResponses = 5 // arbitrary bound on number of informational responses, same as net/http
  2157  		if cs.num1xx > max1xxResponses {
  2158  			return nil, errors.New("http2: too many 1xx informational responses")
  2159  		}
  2160  		if fn := cs.get1xxTraceFunc(); fn != nil {
  2161  			if err := fn(statusCode, textproto.MIMEHeader(header)); err != nil {
  2162  				return nil, err
  2163  			}
  2164  		}
  2165  		if statusCode == 100 {
  2166  			traceGot100Continue(cs.trace)
  2167  			if cs.on100 != nil {
  2168  				cs.on100() // forces any write delay timer to fire
  2169  			}
  2170  		}
  2171  		cs.pastHeaders = false // do it all again
  2172  		return nil, nil
  2173  	}
  2174  
  2175  	streamEnded := f.StreamEnded()
  2176  	isHead := cs.req.Method == "HEAD"
  2177  	if !streamEnded || isHead {
  2178  		res.ContentLength = -1
  2179  		if clens := res.Header["Content-Length"]; len(clens) == 1 {
  2180  			if cl, err := strconv.ParseUint(clens[0], 10, 63); err == nil {
  2181  				res.ContentLength = int64(cl)
  2182  			} else {
  2183  				// TODO: care? unlike http/1, it won't mess up our framing, so it's
  2184  				// more safe smuggling-wise to ignore.
  2185  			}
  2186  		} else if len(clens) > 1 {
  2187  			// TODO: care? unlike http/1, it won't mess up our framing, so it's
  2188  			// more safe smuggling-wise to ignore.
  2189  		}
  2190  	}
  2191  
  2192  	if streamEnded || isHead {
  2193  		res.Body = noBody
  2194  		return res, nil
  2195  	}
  2196  
  2197  	cs.bufPipe = pipe{b: &dataBuffer{expected: res.ContentLength}}
  2198  	cs.bytesRemain = res.ContentLength
  2199  	res.Body = transportResponseBody{cs}
  2200  	go cs.awaitRequestCancel(cs.req)
  2201  
  2202  	res.Body = http.DecompressBody(res)
  2203  	return res, nil
  2204  }
  2205  
  2206  func (rl *clientConnReadLoop) processTrailers(cs *clientStream, f *MetaHeadersFrame) error {
  2207  	if cs.pastTrailers {
  2208  		// Too many HEADERS frames for this stream.
  2209  		return ConnectionError(ErrCodeProtocol)
  2210  	}
  2211  	cs.pastTrailers = true
  2212  	if !f.StreamEnded() {
  2213  		// We expect that any headers for trailers also
  2214  		// has END_STREAM.
  2215  		return ConnectionError(ErrCodeProtocol)
  2216  	}
  2217  	if len(f.PseudoFields()) > 0 {
  2218  		// No pseudo header fields are defined for trailers.
  2219  		// TODO: ConnectionError might be overly harsh? Check.
  2220  		return ConnectionError(ErrCodeProtocol)
  2221  	}
  2222  
  2223  	trailer := make(http.Header)
  2224  	for _, hf := range f.RegularFields() {
  2225  		key := http.CanonicalHeaderKey(hf.Name)
  2226  		trailer[key] = append(trailer[key], hf.Value)
  2227  	}
  2228  	cs.trailer = trailer
  2229  
  2230  	rl.endStream(cs)
  2231  	return nil
  2232  }
  2233  
  2234  // transportResponseBody is the concrete type of Transport.RoundTrip's
  2235  // Response.Body. It is an io.ReadCloser. On Read, it reads from cs.body.
  2236  // On Close it sends RST_STREAM if EOF wasn't already seen.
  2237  type transportResponseBody struct {
  2238  	cs *clientStream
  2239  }
  2240  
  2241  func (b transportResponseBody) Read(p []byte) (n int, err error) {
  2242  	cs := b.cs
  2243  	cc := cs.cc
  2244  
  2245  	if cs.readErr != nil {
  2246  		return 0, cs.readErr
  2247  	}
  2248  	n, err = b.cs.bufPipe.Read(p)
  2249  	if cs.bytesRemain != -1 {
  2250  		if int64(n) > cs.bytesRemain {
  2251  			n = int(cs.bytesRemain)
  2252  			if err == nil {
  2253  				err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
  2254  				cc.writeStreamReset(cs.ID, ErrCodeProtocol, err)
  2255  			}
  2256  			cs.readErr = err
  2257  			return int(cs.bytesRemain), err
  2258  		}
  2259  		cs.bytesRemain -= int64(n)
  2260  		if err == io.EOF && cs.bytesRemain > 0 {
  2261  			err = io.ErrUnexpectedEOF
  2262  			cs.readErr = err
  2263  			return n, err
  2264  		}
  2265  	}
  2266  	if n == 0 {
  2267  		// No flow control tokens to send back.
  2268  		return
  2269  	}
  2270  
  2271  	cc.mu.Lock()
  2272  	defer cc.mu.Unlock()
  2273  
  2274  	var connAdd, streamAdd int32
  2275  	// Check the conn-level first, before the stream-level.
  2276  	if v := cc.inflow.available(); v < transportDefaultConnFlow/2 {
  2277  		connAdd = transportDefaultConnFlow - v
  2278  		cc.inflow.add(connAdd)
  2279  	}
  2280  	if err == nil { // No need to refresh if the stream is over or failed.
  2281  		// Consider any buffered body data (read from the conn but not
  2282  		// consumed by the client) when computing flow control for this
  2283  		// stream.
  2284  		v := int(cs.inflow.available()) + cs.bufPipe.Len()
  2285  		if v < transportDefaultStreamFlow-transportDefaultStreamMinRefresh {
  2286  			streamAdd = int32(transportDefaultStreamFlow - v)
  2287  			cs.inflow.add(streamAdd)
  2288  		}
  2289  	}
  2290  	if connAdd != 0 || streamAdd != 0 {
  2291  		cc.wmu.Lock()
  2292  		defer cc.wmu.Unlock()
  2293  		if connAdd != 0 {
  2294  			cc.fr.WriteWindowUpdate(0, mustUint31(connAdd))
  2295  		}
  2296  		if streamAdd != 0 {
  2297  			cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd))
  2298  		}
  2299  		cc.bw.Flush()
  2300  	}
  2301  	return
  2302  }
  2303  
  2304  var errClosedResponseBody = errors.New("http2: response body closed")
  2305  
  2306  func (b transportResponseBody) Close() error {
  2307  	cs := b.cs
  2308  	cc := cs.cc
  2309  
  2310  	serverSentStreamEnd := cs.bufPipe.Err() == io.EOF
  2311  	unread := cs.bufPipe.Len()
  2312  
  2313  	if unread > 0 || !serverSentStreamEnd {
  2314  		cc.mu.Lock()
  2315  		cc.wmu.Lock()
  2316  		if !serverSentStreamEnd {
  2317  			cc.fr.WriteRSTStream(cs.ID, ErrCodeCancel)
  2318  			cs.didReset = true
  2319  		}
  2320  		// Return connection-level flow control.
  2321  		if unread > 0 {
  2322  			cc.inflow.add(int32(unread))
  2323  			cc.fr.WriteWindowUpdate(0, uint32(unread))
  2324  		}
  2325  		cc.bw.Flush()
  2326  		cc.wmu.Unlock()
  2327  		cc.mu.Unlock()
  2328  	}
  2329  
  2330  	cs.bufPipe.BreakWithError(errClosedResponseBody)
  2331  	cc.forgetStreamID(cs.ID)
  2332  	return nil
  2333  }
  2334  
  2335  func (rl *clientConnReadLoop) processData(f *DataFrame) error {
  2336  	cc := rl.cc
  2337  	cs := cc.streamByID(f.StreamID, f.StreamEnded())
  2338  	data := f.Data()
  2339  	if cs == nil {
  2340  		cc.mu.Lock()
  2341  		neverSent := cc.nextStreamID
  2342  		cc.mu.Unlock()
  2343  		serverInitiated := f.StreamID%2 == 0
  2344  		if f.StreamID >= neverSent && !serverInitiated {
  2345  			// We never asked for this.
  2346  			cc.logf("http2: Transport received unsolicited DATA frame; closing connection")
  2347  			return ConnectionError(ErrCodeProtocol)
  2348  		}
  2349  
  2350  		// We probably did ask for this, but canceled. Just ignore it.
  2351  		// TODO: be stricter here? only silently ignore things which
  2352  		// we canceled, but not things which were closed normally
  2353  		// by the peer? Tough without accumulating too much state.
  2354  
  2355  		// But at least return their flow control:
  2356  		if f.Length > 0 {
  2357  			cc.mu.Lock()
  2358  			cc.inflow.add(int32(f.Length))
  2359  			cc.mu.Unlock()
  2360  
  2361  			cc.wmu.Lock()
  2362  			cc.fr.WriteWindowUpdate(0, uint32(f.Length))
  2363  			cc.bw.Flush()
  2364  			cc.wmu.Unlock()
  2365  		}
  2366  		return nil
  2367  	}
  2368  	if f.StreamEnded() {
  2369  		cs.gotEndStream = true
  2370  	}
  2371  	if !cs.firstByte {
  2372  		cc.logf("protocol error: received DATA before a HEADERS frame")
  2373  		rl.endStreamError(cs, StreamError{
  2374  			StreamID: f.StreamID,
  2375  			Code:     ErrCodeProtocol,
  2376  		})
  2377  		return nil
  2378  	}
  2379  	if f.Length > 0 {
  2380  		if cs.req.Method == "HEAD" && len(data) > 0 {
  2381  			cc.logf("protocol error: received DATA on a HEAD request")
  2382  			rl.endStreamError(cs, StreamError{
  2383  				StreamID: f.StreamID,
  2384  				Code:     ErrCodeProtocol,
  2385  			})
  2386  			return nil
  2387  		}
  2388  		// Check connection-level flow control.
  2389  		cc.mu.Lock()
  2390  		if cs.inflow.available() >= int32(f.Length) {
  2391  			cs.inflow.take(int32(f.Length))
  2392  		} else {
  2393  			cc.mu.Unlock()
  2394  			return ConnectionError(ErrCodeFlowControl)
  2395  		}
  2396  		// Return any padded flow control now, since we won't
  2397  		// refund it later on body reads.
  2398  		var refund int
  2399  		if pad := int(f.Length) - len(data); pad > 0 {
  2400  			refund += pad
  2401  		}
  2402  		// Return len(data) now if the stream is already closed,
  2403  		// since data will never be read.
  2404  		didReset := cs.didReset
  2405  		if didReset {
  2406  			refund += len(data)
  2407  		}
  2408  		if refund > 0 {
  2409  			cc.inflow.add(int32(refund))
  2410  			cc.wmu.Lock()
  2411  			cc.fr.WriteWindowUpdate(0, uint32(refund))
  2412  			if !didReset {
  2413  				cs.inflow.add(int32(refund))
  2414  				cc.fr.WriteWindowUpdate(cs.ID, uint32(refund))
  2415  			}
  2416  			cc.bw.Flush()
  2417  			cc.wmu.Unlock()
  2418  		}
  2419  		cc.mu.Unlock()
  2420  
  2421  		if len(data) > 0 && !didReset {
  2422  			if _, err := cs.bufPipe.Write(data); err != nil {
  2423  				rl.endStreamError(cs, err)
  2424  				return err
  2425  			}
  2426  		}
  2427  	}
  2428  
  2429  	if f.StreamEnded() {
  2430  		rl.endStream(cs)
  2431  	}
  2432  	return nil
  2433  }
  2434  
  2435  func (rl *clientConnReadLoop) endStream(cs *clientStream) {
  2436  	// TODO: check that any declared content-length matches, like
  2437  	// server.go's (*stream).endStream method.
  2438  	rl.endStreamError(cs, nil)
  2439  }
  2440  
  2441  func (rl *clientConnReadLoop) endStreamError(cs *clientStream, err error) {
  2442  	var code func()
  2443  	if err == nil {
  2444  		err = io.EOF
  2445  		code = cs.copyTrailers
  2446  	}
  2447  	if isConnectionCloseRequest(cs.req) {
  2448  		rl.closeWhenIdle = true
  2449  	}
  2450  	cs.bufPipe.closeWithErrorAndCode(err, code)
  2451  
  2452  	select {
  2453  	case cs.resc <- resAndError{err: err}:
  2454  	default:
  2455  	}
  2456  }
  2457  
  2458  func (cs *clientStream) copyTrailers() {
  2459  	for k, vv := range cs.trailer {
  2460  		t := cs.resTrailer
  2461  		if *t == nil {
  2462  			*t = make(http.Header)
  2463  		}
  2464  		(*t)[k] = vv
  2465  	}
  2466  }
  2467  
  2468  func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error {
  2469  	cc := rl.cc
  2470  	cc.t.connPool().MarkDead(cc)
  2471  	if f.ErrCode != 0 {
  2472  		// TODO: deal with GOAWAY more. particularly the error code
  2473  		cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
  2474  	}
  2475  	cc.setGoAway(f)
  2476  	return nil
  2477  }
  2478  
  2479  func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error {
  2480  	cc := rl.cc
  2481  	cc.mu.Lock()
  2482  	defer cc.mu.Unlock()
  2483  
  2484  	if f.IsAck() {
  2485  		if cc.wantSettingsAck {
  2486  			cc.wantSettingsAck = false
  2487  			return nil
  2488  		}
  2489  		return ConnectionError(ErrCodeProtocol)
  2490  	}
  2491  
  2492  	err := f.ForeachSetting(func(s Setting) error {
  2493  		switch s.ID {
  2494  		case SettingMaxFrameSize:
  2495  			cc.maxFrameSize = s.Val
  2496  		case SettingMaxConcurrentStreams:
  2497  			cc.maxConcurrentStreams = s.Val
  2498  		case SettingMaxHeaderListSize:
  2499  			cc.peerMaxHeaderListSize = uint64(s.Val)
  2500  		case SettingInitialWindowSize:
  2501  			// Values above the maximum flow-control
  2502  			// window size of 2^31-1 MUST be treated as a
  2503  			// connection error (Section 5.4.1) of type
  2504  			// FLOW_CONTROL_ERROR.
  2505  			if s.Val > math.MaxInt32 {
  2506  				return ConnectionError(ErrCodeFlowControl)
  2507  			}
  2508  
  2509  			// Adjust flow control of currently-open
  2510  			// frames by the difference of the old initial
  2511  			// window size and this one.
  2512  			delta := int32(s.Val) - int32(cc.initialWindowSize)
  2513  			for _, cs := range cc.streams {
  2514  				cs.flow.add(delta)
  2515  			}
  2516  			cc.cond.Broadcast()
  2517  
  2518  			cc.initialWindowSize = s.Val
  2519  		default:
  2520  			// TODO(bradfitz): handle more settings? SETTINGS_HEADER_TABLE_SIZE probably.
  2521  			cc.vlogf("Unhandled Setting: %v", s)
  2522  		}
  2523  		return nil
  2524  	})
  2525  	if err != nil {
  2526  		return err
  2527  	}
  2528  
  2529  	cc.wmu.Lock()
  2530  	defer cc.wmu.Unlock()
  2531  
  2532  	cc.fr.WriteSettingsAck()
  2533  	cc.bw.Flush()
  2534  	return cc.werr
  2535  }
  2536  
  2537  func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error {
  2538  	cc := rl.cc
  2539  	cs := cc.streamByID(f.StreamID, false)
  2540  	if f.StreamID != 0 && cs == nil {
  2541  		return nil
  2542  	}
  2543  
  2544  	cc.mu.Lock()
  2545  	defer cc.mu.Unlock()
  2546  
  2547  	fl := &cc.flow
  2548  	if cs != nil {
  2549  		fl = &cs.flow
  2550  	}
  2551  	if !fl.add(int32(f.Increment)) {
  2552  		return ConnectionError(ErrCodeFlowControl)
  2553  	}
  2554  	cc.cond.Broadcast()
  2555  	return nil
  2556  }
  2557  
  2558  func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error {
  2559  	cs := rl.cc.streamByID(f.StreamID, true)
  2560  	if cs == nil {
  2561  		// TODO: return error if server tries to RST_STEAM an idle stream
  2562  		return nil
  2563  	}
  2564  	select {
  2565  	case <-cs.peerReset:
  2566  		// Already reset.
  2567  		// This is the only goroutine
  2568  		// which closes this, so there
  2569  		// isn't a race.
  2570  	default:
  2571  		err := streamError(cs.ID, f.ErrCode)
  2572  		cs.resetErr = err
  2573  		close(cs.peerReset)
  2574  		cs.bufPipe.CloseWithError(err)
  2575  		cs.cc.cond.Broadcast() // wake up checkResetOrDone via clientStream.awaitFlowControl
  2576  	}
  2577  	return nil
  2578  }
  2579  
  2580  // Ping sends a PING frame to the server and waits for the ack.
  2581  func (cc *ClientConn) Ping(ctx context.Context) error {
  2582  	c := make(chan struct{})
  2583  	// Generate a random payload
  2584  	var p [8]byte
  2585  	for {
  2586  		if _, err := rand.Read(p[:]); err != nil {
  2587  			return err
  2588  		}
  2589  		cc.mu.Lock()
  2590  		// check for dup before insert
  2591  		if _, found := cc.pings[p]; !found {
  2592  			cc.pings[p] = c
  2593  			cc.mu.Unlock()
  2594  			break
  2595  		}
  2596  		cc.mu.Unlock()
  2597  	}
  2598  	cc.wmu.Lock()
  2599  	if err := cc.fr.WritePing(false, p); err != nil {
  2600  		cc.wmu.Unlock()
  2601  		return err
  2602  	}
  2603  	if err := cc.bw.Flush(); err != nil {
  2604  		cc.wmu.Unlock()
  2605  		return err
  2606  	}
  2607  	cc.wmu.Unlock()
  2608  	select {
  2609  	case <-c:
  2610  		return nil
  2611  	case <-ctx.Done():
  2612  		return ctx.Err()
  2613  	case <-cc.readerDone:
  2614  		// connection closed
  2615  		return cc.readerErr
  2616  	}
  2617  }
  2618  
  2619  func (rl *clientConnReadLoop) processPing(f *PingFrame) error {
  2620  	if f.IsAck() {
  2621  		cc := rl.cc
  2622  		cc.mu.Lock()
  2623  		defer cc.mu.Unlock()
  2624  		// If ack, notify listener if any
  2625  		if c, ok := cc.pings[f.Data]; ok {
  2626  			close(c)
  2627  			delete(cc.pings, f.Data)
  2628  		}
  2629  		return nil
  2630  	}
  2631  	cc := rl.cc
  2632  	cc.wmu.Lock()
  2633  	defer cc.wmu.Unlock()
  2634  	if err := cc.fr.WritePing(true, f.Data); err != nil {
  2635  		return err
  2636  	}
  2637  	return cc.bw.Flush()
  2638  }
  2639  
  2640  func (rl *clientConnReadLoop) processPushPromise(f *MetaPushPromiseFrame) error {
  2641  	if rl.cc.t.PushHandler == nil { // should not be receiving PUSH_PROMISE if ENABLE_PUSH is disabled
  2642  		return ConnectionError(ErrCodeProtocol)
  2643  	}
  2644  	if f.StreamID%2 != 1 { // Reject recursive push
  2645  		return ConnectionError(ErrCodeProtocol)
  2646  	}
  2647  	if f.PromiseID%2 != 0 { // Reject invalid server-initiated stream id
  2648  		return ConnectionError(ErrCodeProtocol)
  2649  	}
  2650  	stream := rl.cc.streamByID(f.StreamID, false)
  2651  	// "A receiver MUST treat the receipt of a PUSH_PROMISE on a stream that is neither
  2652  	// "open" nor "half-closed (local)" as a connection error of type PROTOCOL_ERROR"
  2653  	// See: https://tools.ietf.org/html/rfc7540#section-6.6
  2654  	if stream == nil || stream.resetErr != nil || stream.gotEndStream {
  2655  		return ConnectionError(ErrCodeProtocol)
  2656  	}
  2657  
  2658  	rl.cc.mu.Lock()
  2659  	if f.PromiseID <= rl.cc.highestPromiseID {
  2660  		rl.cc.mu.Unlock()
  2661  		return ConnectionError(ErrCodeProtocol)
  2662  	}
  2663  	rl.cc.highestPromiseID = f.PromiseID
  2664  	pushedStream := rl.cc.newStreamWithID(f.PromiseID, false)
  2665  	rl.cc.mu.Unlock()
  2666  
  2667  	pushedReq, err := pushedRequestToHTTPRequest(f)
  2668  	if err != nil {
  2669  		return StreamError{f.StreamID, ErrCodeProtocol, err}
  2670  	}
  2671  	pushedReq.RemoteAddr = rl.cc.dialedAddr
  2672  
  2673  	// Reject non-authoritative pushes
  2674  	skipVerify := rl.cc.t.TLSClientConfig != nil && rl.cc.t.TLSClientConfig.InsecureSkipVerify
  2675  	if !skipVerify {
  2676  		if stream.req.URL.Scheme != pushedReq.URL.Scheme {
  2677  			err := fmt.Errorf("push's scheme %q not equal to original request's scheme %q",
  2678  				pushedReq.URL.Scheme, stream.req.URL.Scheme)
  2679  			return StreamError{f.StreamID, ErrCodeProtocol, err}
  2680  		}
  2681  		pushHost, pushPort := authorityHostPort(pushedReq.URL.Scheme, pushedReq.URL.Host)
  2682  		origHost, origPort := authorityHostPort(stream.req.URL.Scheme, stream.req.URL.Host)
  2683  		if origPort != pushPort {
  2684  			err := fmt.Errorf("push's port %q not equal to original request's port %q", pushPort, origPort)
  2685  			return StreamError{f.StreamID, ErrCodeProtocol, err}
  2686  		}
  2687  
  2688  		var authoritative bool
  2689  		if rl.cc.tlsState != nil {
  2690  			authoritative = len(rl.cc.tlsState.VerifiedChains) > 0 &&
  2691  				rl.cc.tlsState.PeerCertificates[0].VerifyHostname(pushedReq.URL.Hostname()) == nil
  2692  		} else {
  2693  			// Non-TLS connection
  2694  			authoritative = pushHost == origHost
  2695  		}
  2696  		if !authoritative {
  2697  			err := fmt.Errorf("server not authoritative for push with host %q", pushedReq.URL.Hostname())
  2698  			return StreamError{f.StreamID, ErrCodeProtocol, err}
  2699  		}
  2700  	}
  2701  
  2702  	pushedReq.TLS = rl.cc.tlsState
  2703  	pushedStream.req = pushedReq
  2704  	pr := &PushedRequest{
  2705  		Promise:               pushedReq,
  2706  		OriginalRequestURL:    stream.req.URL,
  2707  		OriginalRequestHeader: cloneHeader(stream.req.Header),
  2708  		pushedStream:          pushedStream,
  2709  	}
  2710  	go handlePushEarlyReturnCancel(rl.cc.t.PushHandler, pr)
  2711  	return nil
  2712  }
  2713  
  2714  func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) {
  2715  	// TODO: map err to more interesting error codes, once the
  2716  	// HTTP community comes up with some. But currently for
  2717  	// RST_STREAM there's no equivalent to GOAWAY frame's debug
  2718  	// data, and the error codes are all pretty vague ("cancel").
  2719  	cc.wmu.Lock()
  2720  	fmt.Printf("reset err %v StreamID: %v\n", code, streamID)
  2721  	cc.fr.WriteRSTStream(streamID, code)
  2722  	cc.bw.Flush()
  2723  	cc.wmu.Unlock()
  2724  }
  2725  
  2726  var (
  2727  	errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
  2728  	errRequestHeaderListSize  = errors.New("http2: request header list larger than peer's advertised limit")
  2729  )
  2730  
  2731  func (cc *ClientConn) logf(format string, args ...interface{}) {
  2732  	cc.t.logf(format, args...)
  2733  }
  2734  
  2735  func (cc *ClientConn) vlogf(format string, args ...interface{}) {
  2736  	cc.t.vlogf(format, args...)
  2737  }
  2738  
  2739  func (t *Transport) vlogf(format string, args ...interface{}) {
  2740  	if VerboseLogs {
  2741  		t.logf(format, args...)
  2742  	}
  2743  }
  2744  
  2745  func (t *Transport) logf(format string, args ...interface{}) {
  2746  	log.Printf(format, args...)
  2747  }
  2748  
  2749  var noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
  2750  
  2751  func strSliceContains(ss []string, s string) bool {
  2752  	for _, v := range ss {
  2753  		if v == s {
  2754  			return true
  2755  		}
  2756  	}
  2757  	return false
  2758  }
  2759  
  2760  type erringRoundTripper struct{ err error }
  2761  
  2762  func (rt erringRoundTripper) RoundTripErr() error                             { return rt.err }
  2763  func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err }
  2764  
  2765  type errorReader struct{ err error }
  2766  
  2767  func (r errorReader) Read(p []byte) (int, error) { return 0, r.err }
  2768  
  2769  // bodyWriterState encapsulates various state around the Transport's writing
  2770  // of the request body, particularly regarding doing delayed writes of the body
  2771  // when the request contains "Expect: 100-continue".
  2772  type bodyWriterState struct {
  2773  	cs     *clientStream
  2774  	timer  *time.Timer   // if non-nil, we're doing a delayed write
  2775  	fnonce *sync.Once    // to call fn with
  2776  	fn     func()        // the code to run in the goroutine, writing the body
  2777  	resc   chan error    // result of fn's execution
  2778  	delay  time.Duration // how long we should delay a delayed write for
  2779  }
  2780  
  2781  func (t *Transport) getBodyWriterState(cs *clientStream, body io.Reader) (s bodyWriterState) {
  2782  	s.cs = cs
  2783  	if body == nil {
  2784  		return
  2785  	}
  2786  	resc := make(chan error, 1)
  2787  	s.resc = resc
  2788  	s.fn = func() {
  2789  		cs.cc.mu.Lock()
  2790  		cs.startedWrite = true
  2791  		cs.cc.mu.Unlock()
  2792  		resc <- cs.writeRequestBody(body, cs.req.Body)
  2793  	}
  2794  	s.delay = t.expectContinueTimeout()
  2795  	if s.delay == 0 ||
  2796  		!httpguts.HeaderValuesContainsToken(
  2797  			cs.req.Header["Expect"],
  2798  			"100-continue") {
  2799  		return
  2800  	}
  2801  	s.fnonce = new(sync.Once)
  2802  
  2803  	// Arm the timer with a very large duration, which we'll
  2804  	// intentionally lower later. It has to be large now because
  2805  	// we need a handle to it before writing the headers, but the
  2806  	// s.delay value is defined to not start until after the
  2807  	// request headers were written.
  2808  	const hugeDuration = 365 * 24 * time.Hour
  2809  	s.timer = time.AfterFunc(hugeDuration, func() {
  2810  		s.fnonce.Do(s.fn)
  2811  	})
  2812  	return
  2813  }
  2814  
  2815  func (s bodyWriterState) cancel() {
  2816  	if s.timer != nil {
  2817  		if s.timer.Stop() {
  2818  			s.resc <- nil
  2819  		}
  2820  	}
  2821  }
  2822  
  2823  func (s bodyWriterState) on100() {
  2824  	if s.timer == nil {
  2825  		// If we didn't do a delayed write, ignore the server's
  2826  		// bogus 100 continue response.
  2827  		return
  2828  	}
  2829  	s.timer.Stop()
  2830  	go func() { s.fnonce.Do(s.fn) }()
  2831  }
  2832  
  2833  // scheduleBodyWrite starts writing the body, either immediately (in
  2834  // the common case) or after the delay timeout. It should not be
  2835  // called until after the headers have been written.
  2836  func (s bodyWriterState) scheduleBodyWrite() {
  2837  	if s.timer == nil {
  2838  		// We're not doing a delayed write (see
  2839  		// getBodyWriterState), so just start the writing
  2840  		// goroutine immediately.
  2841  		go s.fn()
  2842  		return
  2843  	}
  2844  	traceWait100Continue(s.cs.trace)
  2845  	if s.timer.Stop() {
  2846  		s.timer.Reset(s.delay)
  2847  	}
  2848  }
  2849  
  2850  // isConnectionCloseRequest reports whether req should use its own
  2851  // connection for a single request and then close the connection.
  2852  func isConnectionCloseRequest(req *http.Request) bool {
  2853  	return req.Close || httpguts.HeaderValuesContainsToken(req.Header["Connection"], "close")
  2854  }
  2855  
  2856  // registerHTTPSProtocol calls Transport.RegisterProtocol but
  2857  // converting panics into errors.
  2858  func registerHTTPSProtocol(t *http.Transport, rt noDialH2RoundTripper) (err error) {
  2859  	defer func() {
  2860  		if e := recover(); e != nil {
  2861  			err = fmt.Errorf("%v", e)
  2862  		}
  2863  	}()
  2864  	t.RegisterProtocol("https", rt)
  2865  	return nil
  2866  }
  2867  
  2868  // noDialH2RoundTripper is a RoundTripper which only tries to complete the request
  2869  // if there's already has a cached connection to the host.
  2870  // (The field is exported so it can be accessed via reflect from net/http; tested
  2871  // by TestNoDialH2RoundTripperType)
  2872  type noDialH2RoundTripper struct{ *Transport }
  2873  
  2874  func (rt noDialH2RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
  2875  	res, err := rt.Transport.RoundTrip(req)
  2876  	if isNoCachedConnError(err) {
  2877  		return nil, http.ErrSkipAltProtocol
  2878  	}
  2879  	return res, err
  2880  }
  2881  
  2882  func (t *Transport) idleConnTimeout() time.Duration {
  2883  	if t.t1 != nil {
  2884  		return t.t1.IdleConnTimeout
  2885  	}
  2886  	return 0
  2887  }
  2888  
  2889  func traceGetConn(req *http.Request, hostPort string) {
  2890  	trace := httptrace.ContextClientTrace(req.Context())
  2891  	if trace == nil || trace.GetConn == nil {
  2892  		return
  2893  	}
  2894  	trace.GetConn(hostPort)
  2895  }
  2896  
  2897  func traceGotConn(req *http.Request, cc *ClientConn, reused bool) {
  2898  	trace := httptrace.ContextClientTrace(req.Context())
  2899  	if trace == nil || trace.GotConn == nil {
  2900  		return
  2901  	}
  2902  	ci := httptrace.GotConnInfo{Conn: cc.tconn}
  2903  	ci.Reused = reused
  2904  	cc.mu.Lock()
  2905  	ci.WasIdle = len(cc.streams) == 0 && reused
  2906  	if ci.WasIdle && !cc.lastActive.IsZero() {
  2907  		ci.IdleTime = time.Now().Sub(cc.lastActive)
  2908  	}
  2909  	cc.mu.Unlock()
  2910  
  2911  	trace.GotConn(ci)
  2912  }
  2913  
  2914  func traceWroteHeaders(trace *httptrace.ClientTrace) {
  2915  	if trace != nil && trace.WroteHeaders != nil {
  2916  		trace.WroteHeaders()
  2917  	}
  2918  }
  2919  
  2920  func traceGot100Continue(trace *httptrace.ClientTrace) {
  2921  	if trace != nil && trace.Got100Continue != nil {
  2922  		trace.Got100Continue()
  2923  	}
  2924  }
  2925  
  2926  func traceWait100Continue(trace *httptrace.ClientTrace) {
  2927  	if trace != nil && trace.Wait100Continue != nil {
  2928  		trace.Wait100Continue()
  2929  	}
  2930  }
  2931  
  2932  func traceWroteRequest(trace *httptrace.ClientTrace, err error) {
  2933  	if trace != nil && trace.WroteRequest != nil {
  2934  		trace.WroteRequest(httptrace.WroteRequestInfo{Err: err})
  2935  	}
  2936  }
  2937  
  2938  func traceFirstResponseByte(trace *httptrace.ClientTrace) {
  2939  	if trace != nil && trace.GotFirstResponseByte != nil {
  2940  		trace.GotFirstResponseByte()
  2941  	}
  2942  }