• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
7package http2
8
9import (
10	"bufio"
11	"bytes"
12	"compress/gzip"
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/http"
24	"sort"
25	"strconv"
26	"strings"
27	"sync"
28	"time"
29
30	"golang.org/x/net/http/httpguts"
31	"golang.org/x/net/http2/hpack"
32	"golang.org/x/net/idna"
33)
34
35const (
36	// transportDefaultConnFlow is how many connection-level flow control
37	// tokens we give the server at start-up, past the default 64k.
38	transportDefaultConnFlow = 1 << 30
39
40	// transportDefaultStreamFlow is how many stream-level flow
41	// control tokens we announce to the peer, and how many bytes
42	// we buffer per stream.
43	transportDefaultStreamFlow = 4 << 20
44
45	// transportDefaultStreamMinRefresh is the minimum number of bytes we'll send
46	// a stream-level WINDOW_UPDATE for at a time.
47	transportDefaultStreamMinRefresh = 4 << 10
48
49	defaultUserAgent = "Go-http-client/2.0"
50)
51
52// Transport is an HTTP/2 Transport.
53//
54// A Transport internally caches connections to servers. It is safe
55// for concurrent use by multiple goroutines.
56type Transport struct {
57	// DialTLS specifies an optional dial function for creating
58	// TLS connections for requests.
59	//
60	// If DialTLS is nil, tls.Dial is used.
61	//
62	// If the returned net.Conn has a ConnectionState method like tls.Conn,
63	// it will be used to set http.Response.TLS.
64	DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error)
65
66	// TLSClientConfig specifies the TLS configuration to use with
67	// tls.Client. If nil, the default configuration is used.
68	TLSClientConfig *tls.Config
69
70	// ConnPool optionally specifies an alternate connection pool to use.
71	// If nil, the default is used.
72	ConnPool ClientConnPool
73
74	// DisableCompression, if true, prevents the Transport from
75	// requesting compression with an "Accept-Encoding: gzip"
76	// request header when the Request contains no existing
77	// Accept-Encoding value. If the Transport requests gzip on
78	// its own and gets a gzipped response, it's transparently
79	// decoded in the Response.Body. However, if the user
80	// explicitly requested gzip it is not automatically
81	// uncompressed.
82	DisableCompression bool
83
84	// AllowHTTP, if true, permits HTTP/2 requests using the insecure,
85	// plain-text "http" scheme. Note that this does not enable h2c support.
86	AllowHTTP bool
87
88	// MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
89	// send in the initial settings frame. It is how many bytes
90	// of response headers are allowed. Unlike the http2 spec, zero here
91	// means to use a default limit (currently 10MB). If you actually
92	// want to advertise an ulimited value to the peer, Transport
93	// interprets the highest possible value here (0xffffffff or 1<<32-1)
94	// to mean no limit.
95	MaxHeaderListSize uint32
96
97	// t1, if non-nil, is the standard library Transport using
98	// this transport. Its settings are used (but not its
99	// RoundTrip method, etc).
100	t1 *http.Transport
101
102	connPoolOnce  sync.Once
103	connPoolOrDef ClientConnPool // non-nil version of ConnPool
104}
105
106func (t *Transport) maxHeaderListSize() uint32 {
107	if t.MaxHeaderListSize == 0 {
108		return 10 << 20
109	}
110	if t.MaxHeaderListSize == 0xffffffff {
111		return 0
112	}
113	return t.MaxHeaderListSize
114}
115
116func (t *Transport) disableCompression() bool {
117	return t.DisableCompression || (t.t1 != nil && t.t1.DisableCompression)
118}
119
120var errTransportVersion = errors.New("http2: ConfigureTransport is only supported starting at Go 1.6")
121
122// ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2.
123// It requires Go 1.6 or later and returns an error if the net/http package is too old
124// or if t1 has already been HTTP/2-enabled.
125func ConfigureTransport(t1 *http.Transport) error {
126	_, err := configureTransport(t1) // in configure_transport.go (go1.6) or not_go16.go
127	return err
128}
129
130func (t *Transport) connPool() ClientConnPool {
131	t.connPoolOnce.Do(t.initConnPool)
132	return t.connPoolOrDef
133}
134
135func (t *Transport) initConnPool() {
136	if t.ConnPool != nil {
137		t.connPoolOrDef = t.ConnPool
138	} else {
139		t.connPoolOrDef = &clientConnPool{t: t}
140	}
141}
142
143// ClientConn is the state of a single HTTP/2 client connection to an
144// HTTP/2 server.
145type ClientConn struct {
146	t         *Transport
147	tconn     net.Conn             // usually *tls.Conn, except specialized impls
148	tlsState  *tls.ConnectionState // nil only for specialized impls
149	singleUse bool                 // whether being used for a single http.Request
150
151	// readLoop goroutine fields:
152	readerDone chan struct{} // closed on error
153	readerErr  error         // set before readerDone is closed
154
155	idleTimeout time.Duration // or 0 for never
156	idleTimer   *time.Timer
157
158	mu              sync.Mutex // guards following
159	cond            *sync.Cond // hold mu; broadcast on flow/closed changes
160	flow            flow       // our conn-level flow control quota (cs.flow is per stream)
161	inflow          flow       // peer's conn-level flow control
162	closed          bool
163	wantSettingsAck bool                     // we sent a SETTINGS frame and haven't heard back
164	goAway          *GoAwayFrame             // if non-nil, the GoAwayFrame we received
165	goAwayDebug     string                   // goAway frame's debug data, retained as a string
166	streams         map[uint32]*clientStream // client-initiated
167	nextStreamID    uint32
168	pendingRequests int                       // requests blocked and waiting to be sent because len(streams) == maxConcurrentStreams
169	pings           map[[8]byte]chan struct{} // in flight ping data to notification channel
170	bw              *bufio.Writer
171	br              *bufio.Reader
172	fr              *Framer
173	lastActive      time.Time
174	// Settings from peer: (also guarded by mu)
175	maxFrameSize          uint32
176	maxConcurrentStreams  uint32
177	peerMaxHeaderListSize uint64
178	initialWindowSize     uint32
179
180	hbuf    bytes.Buffer // HPACK encoder writes into this
181	henc    *hpack.Encoder
182	freeBuf [][]byte
183
184	wmu  sync.Mutex // held while writing; acquire AFTER mu if holding both
185	werr error      // first write error that has occurred
186}
187
188// clientStream is the state for a single HTTP/2 stream. One of these
189// is created for each Transport.RoundTrip call.
190type clientStream struct {
191	cc            *ClientConn
192	req           *http.Request
193	trace         *clientTrace // or nil
194	ID            uint32
195	resc          chan resAndError
196	bufPipe       pipe // buffered pipe with the flow-controlled response payload
197	startedWrite  bool // started request body write; guarded by cc.mu
198	requestedGzip bool
199	on100         func() // optional code to run if get a 100 continue response
200
201	flow        flow  // guarded by cc.mu
202	inflow      flow  // guarded by cc.mu
203	bytesRemain int64 // -1 means unknown; owned by transportResponseBody.Read
204	readErr     error // sticky read error; owned by transportResponseBody.Read
205	stopReqBody error // if non-nil, stop writing req body; guarded by cc.mu
206	didReset    bool  // whether we sent a RST_STREAM to the server; guarded by cc.mu
207
208	peerReset chan struct{} // closed on peer reset
209	resetErr  error         // populated before peerReset is closed
210
211	done chan struct{} // closed when stream remove from cc.streams map; close calls guarded by cc.mu
212
213	// owned by clientConnReadLoop:
214	firstByte    bool // got the first response byte
215	pastHeaders  bool // got first MetaHeadersFrame (actual headers)
216	pastTrailers bool // got optional second MetaHeadersFrame (trailers)
217
218	trailer    http.Header  // accumulated trailers
219	resTrailer *http.Header // client's Response.Trailer
220}
221
222// awaitRequestCancel waits for the user to cancel a request or for the done
223// channel to be signaled. A non-nil error is returned only if the request was
224// canceled.
225func awaitRequestCancel(req *http.Request, done <-chan struct{}) error {
226	ctx := reqContext(req)
227	if req.Cancel == nil && ctx.Done() == nil {
228		return nil
229	}
230	select {
231	case <-req.Cancel:
232		return errRequestCanceled
233	case <-ctx.Done():
234		return ctx.Err()
235	case <-done:
236		return nil
237	}
238}
239
240// awaitRequestCancel waits for the user to cancel a request, its context to
241// expire, or for the request to be done (any way it might be removed from the
242// cc.streams map: peer reset, successful completion, TCP connection breakage,
243// etc). If the request is canceled, then cs will be canceled and closed.
244func (cs *clientStream) awaitRequestCancel(req *http.Request) {
245	if err := awaitRequestCancel(req, cs.done); err != nil {
246		cs.cancelStream()
247		cs.bufPipe.CloseWithError(err)
248	}
249}
250
251func (cs *clientStream) cancelStream() {
252	cc := cs.cc
253	cc.mu.Lock()
254	didReset := cs.didReset
255	cs.didReset = true
256	cc.mu.Unlock()
257
258	if !didReset {
259		cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
260		cc.forgetStreamID(cs.ID)
261	}
262}
263
264// checkResetOrDone reports any error sent in a RST_STREAM frame by the
265// server, or errStreamClosed if the stream is complete.
266func (cs *clientStream) checkResetOrDone() error {
267	select {
268	case <-cs.peerReset:
269		return cs.resetErr
270	case <-cs.done:
271		return errStreamClosed
272	default:
273		return nil
274	}
275}
276
277func (cs *clientStream) getStartedWrite() bool {
278	cc := cs.cc
279	cc.mu.Lock()
280	defer cc.mu.Unlock()
281	return cs.startedWrite
282}
283
284func (cs *clientStream) abortRequestBodyWrite(err error) {
285	if err == nil {
286		panic("nil error")
287	}
288	cc := cs.cc
289	cc.mu.Lock()
290	cs.stopReqBody = err
291	cc.cond.Broadcast()
292	cc.mu.Unlock()
293}
294
295type stickyErrWriter struct {
296	w   io.Writer
297	err *error
298}
299
300func (sew stickyErrWriter) Write(p []byte) (n int, err error) {
301	if *sew.err != nil {
302		return 0, *sew.err
303	}
304	n, err = sew.w.Write(p)
305	*sew.err = err
306	return
307}
308
309// noCachedConnError is the concrete type of ErrNoCachedConn, which
310// needs to be detected by net/http regardless of whether it's its
311// bundled version (in h2_bundle.go with a rewritten type name) or
312// from a user's x/net/http2. As such, as it has a unique method name
313// (IsHTTP2NoCachedConnError) that net/http sniffs for via func
314// isNoCachedConnError.
315type noCachedConnError struct{}
316
317func (noCachedConnError) IsHTTP2NoCachedConnError() {}
318func (noCachedConnError) Error() string             { return "http2: no cached connection was available" }
319
320// isNoCachedConnError reports whether err is of type noCachedConnError
321// or its equivalent renamed type in net/http2's h2_bundle.go. Both types
322// may coexist in the same running program.
323func isNoCachedConnError(err error) bool {
324	_, ok := err.(interface{ IsHTTP2NoCachedConnError() })
325	return ok
326}
327
328var ErrNoCachedConn error = noCachedConnError{}
329
330// RoundTripOpt are options for the Transport.RoundTripOpt method.
331type RoundTripOpt struct {
332	// OnlyCachedConn controls whether RoundTripOpt may
333	// create a new TCP connection. If set true and
334	// no cached connection is available, RoundTripOpt
335	// will return ErrNoCachedConn.
336	OnlyCachedConn bool
337}
338
339func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
340	return t.RoundTripOpt(req, RoundTripOpt{})
341}
342
343// authorityAddr returns a given authority (a host/IP, or host:port / ip:port)
344// and returns a host:port. The port 443 is added if needed.
345func authorityAddr(scheme string, authority string) (addr string) {
346	host, port, err := net.SplitHostPort(authority)
347	if err != nil { // authority didn't have a port
348		port = "443"
349		if scheme == "http" {
350			port = "80"
351		}
352		host = authority
353	}
354	if a, err := idna.ToASCII(host); err == nil {
355		host = a
356	}
357	// IPv6 address literal, without a port:
358	if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
359		return host + ":" + port
360	}
361	return net.JoinHostPort(host, port)
362}
363
364// RoundTripOpt is like RoundTrip, but takes options.
365func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) {
366	if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) {
367		return nil, errors.New("http2: unsupported scheme")
368	}
369
370	addr := authorityAddr(req.URL.Scheme, req.URL.Host)
371	for retry := 0; ; retry++ {
372		cc, err := t.connPool().GetClientConn(req, addr)
373		if err != nil {
374			t.vlogf("http2: Transport failed to get client conn for %s: %v", addr, err)
375			return nil, err
376		}
377		traceGotConn(req, cc)
378		res, gotErrAfterReqBodyWrite, err := cc.roundTrip(req)
379		if err != nil && retry <= 6 {
380			if req, err = shouldRetryRequest(req, err, gotErrAfterReqBodyWrite); err == nil {
381				// After the first retry, do exponential backoff with 10% jitter.
382				if retry == 0 {
383					continue
384				}
385				backoff := float64(uint(1) << (uint(retry) - 1))
386				backoff += backoff * (0.1 * mathrand.Float64())
387				select {
388				case <-time.After(time.Second * time.Duration(backoff)):
389					continue
390				case <-reqContext(req).Done():
391					return nil, reqContext(req).Err()
392				}
393			}
394		}
395		if err != nil {
396			t.vlogf("RoundTrip failure: %v", err)
397			return nil, err
398		}
399		return res, nil
400	}
401}
402
403// CloseIdleConnections closes any connections which were previously
404// connected from previous requests but are now sitting idle.
405// It does not interrupt any connections currently in use.
406func (t *Transport) CloseIdleConnections() {
407	if cp, ok := t.connPool().(clientConnPoolIdleCloser); ok {
408		cp.closeIdleConnections()
409	}
410}
411
412var (
413	errClientConnClosed    = errors.New("http2: client conn is closed")
414	errClientConnUnusable  = errors.New("http2: client conn not usable")
415	errClientConnGotGoAway = errors.New("http2: Transport received Server's graceful shutdown GOAWAY")
416)
417
418// shouldRetryRequest is called by RoundTrip when a request fails to get
419// response headers. It is always called with a non-nil error.
420// It returns either a request to retry (either the same request, or a
421// modified clone), or an error if the request can't be replayed.
422func shouldRetryRequest(req *http.Request, err error, afterBodyWrite bool) (*http.Request, error) {
423	if !canRetryError(err) {
424		return nil, err
425	}
426	if !afterBodyWrite {
427		return req, nil
428	}
429	// If the Body is nil (or http.NoBody), it's safe to reuse
430	// this request and its Body.
431	if req.Body == nil || reqBodyIsNoBody(req.Body) {
432		return req, nil
433	}
434	// Otherwise we depend on the Request having its GetBody
435	// func defined.
436	getBody := reqGetBody(req) // Go 1.8: getBody = req.GetBody
437	if getBody == nil {
438		return nil, fmt.Errorf("http2: Transport: cannot retry err [%v] after Request.Body was written; define Request.GetBody to avoid this error", err)
439	}
440	body, err := getBody()
441	if err != nil {
442		return nil, err
443	}
444	newReq := *req
445	newReq.Body = body
446	return &newReq, nil
447}
448
449func canRetryError(err error) bool {
450	if err == errClientConnUnusable || err == errClientConnGotGoAway {
451		return true
452	}
453	if se, ok := err.(StreamError); ok {
454		return se.Code == ErrCodeRefusedStream
455	}
456	return false
457}
458
459func (t *Transport) dialClientConn(addr string, singleUse bool) (*ClientConn, error) {
460	host, _, err := net.SplitHostPort(addr)
461	if err != nil {
462		return nil, err
463	}
464	tconn, err := t.dialTLS()("tcp", addr, t.newTLSConfig(host))
465	if err != nil {
466		return nil, err
467	}
468	return t.newClientConn(tconn, singleUse)
469}
470
471func (t *Transport) newTLSConfig(host string) *tls.Config {
472	cfg := new(tls.Config)
473	if t.TLSClientConfig != nil {
474		*cfg = *cloneTLSConfig(t.TLSClientConfig)
475	}
476	if !strSliceContains(cfg.NextProtos, NextProtoTLS) {
477		cfg.NextProtos = append([]string{NextProtoTLS}, cfg.NextProtos...)
478	}
479	if cfg.ServerName == "" {
480		cfg.ServerName = host
481	}
482	return cfg
483}
484
485func (t *Transport) dialTLS() func(string, string, *tls.Config) (net.Conn, error) {
486	if t.DialTLS != nil {
487		return t.DialTLS
488	}
489	return t.dialTLSDefault
490}
491
492func (t *Transport) dialTLSDefault(network, addr string, cfg *tls.Config) (net.Conn, error) {
493	cn, err := tls.Dial(network, addr, cfg)
494	if err != nil {
495		return nil, err
496	}
497	if err := cn.Handshake(); err != nil {
498		return nil, err
499	}
500	if !cfg.InsecureSkipVerify {
501		if err := cn.VerifyHostname(cfg.ServerName); err != nil {
502			return nil, err
503		}
504	}
505	state := cn.ConnectionState()
506	if p := state.NegotiatedProtocol; p != NextProtoTLS {
507		return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, NextProtoTLS)
508	}
509	if !state.NegotiatedProtocolIsMutual {
510		return nil, errors.New("http2: could not negotiate protocol mutually")
511	}
512	return cn, nil
513}
514
515// disableKeepAlives reports whether connections should be closed as
516// soon as possible after handling the first request.
517func (t *Transport) disableKeepAlives() bool {
518	return t.t1 != nil && t.t1.DisableKeepAlives
519}
520
521func (t *Transport) expectContinueTimeout() time.Duration {
522	if t.t1 == nil {
523		return 0
524	}
525	return transportExpectContinueTimeout(t.t1)
526}
527
528func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) {
529	return t.newClientConn(c, false)
530}
531
532func (t *Transport) newClientConn(c net.Conn, singleUse bool) (*ClientConn, error) {
533	cc := &ClientConn{
534		t:                     t,
535		tconn:                 c,
536		readerDone:            make(chan struct{}),
537		nextStreamID:          1,
538		maxFrameSize:          16 << 10,           // spec default
539		initialWindowSize:     65535,              // spec default
540		maxConcurrentStreams:  1000,               // "infinite", per spec. 1000 seems good enough.
541		peerMaxHeaderListSize: 0xffffffffffffffff, // "infinite", per spec. Use 2^64-1 instead.
542		streams:               make(map[uint32]*clientStream),
543		singleUse:             singleUse,
544		wantSettingsAck:       true,
545		pings:                 make(map[[8]byte]chan struct{}),
546	}
547	if d := t.idleConnTimeout(); d != 0 {
548		cc.idleTimeout = d
549		cc.idleTimer = time.AfterFunc(d, cc.onIdleTimeout)
550	}
551	if VerboseLogs {
552		t.vlogf("http2: Transport creating client conn %p to %v", cc, c.RemoteAddr())
553	}
554
555	cc.cond = sync.NewCond(&cc.mu)
556	cc.flow.add(int32(initialWindowSize))
557
558	// TODO: adjust this writer size to account for frame size +
559	// MTU + crypto/tls record padding.
560	cc.bw = bufio.NewWriter(stickyErrWriter{c, &cc.werr})
561	cc.br = bufio.NewReader(c)
562	cc.fr = NewFramer(cc.bw, cc.br)
563	cc.fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil)
564	cc.fr.MaxHeaderListSize = t.maxHeaderListSize()
565
566	// TODO: SetMaxDynamicTableSize, SetMaxDynamicTableSizeLimit on
567	// henc in response to SETTINGS frames?
568	cc.henc = hpack.NewEncoder(&cc.hbuf)
569
570	if t.AllowHTTP {
571		cc.nextStreamID = 3
572	}
573
574	if cs, ok := c.(connectionStater); ok {
575		state := cs.ConnectionState()
576		cc.tlsState = &state
577	}
578
579	initialSettings := []Setting{
580		{ID: SettingEnablePush, Val: 0},
581		{ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow},
582	}
583	if max := t.maxHeaderListSize(); max != 0 {
584		initialSettings = append(initialSettings, Setting{ID: SettingMaxHeaderListSize, Val: max})
585	}
586
587	cc.bw.Write(clientPreface)
588	cc.fr.WriteSettings(initialSettings...)
589	cc.fr.WriteWindowUpdate(0, transportDefaultConnFlow)
590	cc.inflow.add(transportDefaultConnFlow + initialWindowSize)
591	cc.bw.Flush()
592	if cc.werr != nil {
593		return nil, cc.werr
594	}
595
596	go cc.readLoop()
597	return cc, nil
598}
599
600func (cc *ClientConn) setGoAway(f *GoAwayFrame) {
601	cc.mu.Lock()
602	defer cc.mu.Unlock()
603
604	old := cc.goAway
605	cc.goAway = f
606
607	// Merge the previous and current GoAway error frames.
608	if cc.goAwayDebug == "" {
609		cc.goAwayDebug = string(f.DebugData())
610	}
611	if old != nil && old.ErrCode != ErrCodeNo {
612		cc.goAway.ErrCode = old.ErrCode
613	}
614	last := f.LastStreamID
615	for streamID, cs := range cc.streams {
616		if streamID > last {
617			select {
618			case cs.resc <- resAndError{err: errClientConnGotGoAway}:
619			default:
620			}
621		}
622	}
623}
624
625// CanTakeNewRequest reports whether the connection can take a new request,
626// meaning it has not been closed or received or sent a GOAWAY.
627func (cc *ClientConn) CanTakeNewRequest() bool {
628	cc.mu.Lock()
629	defer cc.mu.Unlock()
630	return cc.canTakeNewRequestLocked()
631}
632
633func (cc *ClientConn) canTakeNewRequestLocked() bool {
634	if cc.singleUse && cc.nextStreamID > 1 {
635		return false
636	}
637	return cc.goAway == nil && !cc.closed &&
638		int64(cc.nextStreamID)+int64(cc.pendingRequests) < math.MaxInt32
639}
640
641// onIdleTimeout is called from a time.AfterFunc goroutine. It will
642// only be called when we're idle, but because we're coming from a new
643// goroutine, there could be a new request coming in at the same time,
644// so this simply calls the synchronized closeIfIdle to shut down this
645// connection. The timer could just call closeIfIdle, but this is more
646// clear.
647func (cc *ClientConn) onIdleTimeout() {
648	cc.closeIfIdle()
649}
650
651func (cc *ClientConn) closeIfIdle() {
652	cc.mu.Lock()
653	if len(cc.streams) > 0 {
654		cc.mu.Unlock()
655		return
656	}
657	cc.closed = true
658	nextID := cc.nextStreamID
659	// TODO: do clients send GOAWAY too? maybe? Just Close:
660	cc.mu.Unlock()
661
662	if VerboseLogs {
663		cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, nextID-2)
664	}
665	cc.tconn.Close()
666}
667
668const maxAllocFrameSize = 512 << 10
669
670// frameBuffer returns a scratch buffer suitable for writing DATA frames.
671// They're capped at the min of the peer's max frame size or 512KB
672// (kinda arbitrarily), but definitely capped so we don't allocate 4GB
673// bufers.
674func (cc *ClientConn) frameScratchBuffer() []byte {
675	cc.mu.Lock()
676	size := cc.maxFrameSize
677	if size > maxAllocFrameSize {
678		size = maxAllocFrameSize
679	}
680	for i, buf := range cc.freeBuf {
681		if len(buf) >= int(size) {
682			cc.freeBuf[i] = nil
683			cc.mu.Unlock()
684			return buf[:size]
685		}
686	}
687	cc.mu.Unlock()
688	return make([]byte, size)
689}
690
691func (cc *ClientConn) putFrameScratchBuffer(buf []byte) {
692	cc.mu.Lock()
693	defer cc.mu.Unlock()
694	const maxBufs = 4 // arbitrary; 4 concurrent requests per conn? investigate.
695	if len(cc.freeBuf) < maxBufs {
696		cc.freeBuf = append(cc.freeBuf, buf)
697		return
698	}
699	for i, old := range cc.freeBuf {
700		if old == nil {
701			cc.freeBuf[i] = buf
702			return
703		}
704	}
705	// forget about it.
706}
707
708// errRequestCanceled is a copy of net/http's errRequestCanceled because it's not
709// exported. At least they'll be DeepEqual for h1-vs-h2 comparisons tests.
710var errRequestCanceled = errors.New("net/http: request canceled")
711
712func commaSeparatedTrailers(req *http.Request) (string, error) {
713	keys := make([]string, 0, len(req.Trailer))
714	for k := range req.Trailer {
715		k = http.CanonicalHeaderKey(k)
716		switch k {
717		case "Transfer-Encoding", "Trailer", "Content-Length":
718			return "", &badStringError{"invalid Trailer key", k}
719		}
720		keys = append(keys, k)
721	}
722	if len(keys) > 0 {
723		sort.Strings(keys)
724		return strings.Join(keys, ","), nil
725	}
726	return "", nil
727}
728
729func (cc *ClientConn) responseHeaderTimeout() time.Duration {
730	if cc.t.t1 != nil {
731		return cc.t.t1.ResponseHeaderTimeout
732	}
733	// No way to do this (yet?) with just an http2.Transport. Probably
734	// no need. Request.Cancel this is the new way. We only need to support
735	// this for compatibility with the old http.Transport fields when
736	// we're doing transparent http2.
737	return 0
738}
739
740// checkConnHeaders checks whether req has any invalid connection-level headers.
741// per RFC 7540 section 8.1.2.2: Connection-Specific Header Fields.
742// Certain headers are special-cased as okay but not transmitted later.
743func checkConnHeaders(req *http.Request) error {
744	if v := req.Header.Get("Upgrade"); v != "" {
745		return fmt.Errorf("http2: invalid Upgrade request header: %q", req.Header["Upgrade"])
746	}
747	if vv := req.Header["Transfer-Encoding"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "chunked") {
748		return fmt.Errorf("http2: invalid Transfer-Encoding request header: %q", vv)
749	}
750	if vv := req.Header["Connection"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "close" && vv[0] != "keep-alive") {
751		return fmt.Errorf("http2: invalid Connection request header: %q", vv)
752	}
753	return nil
754}
755
756// actualContentLength returns a sanitized version of
757// req.ContentLength, where 0 actually means zero (not unknown) and -1
758// means unknown.
759func actualContentLength(req *http.Request) int64 {
760	if req.Body == nil || reqBodyIsNoBody(req.Body) {
761		return 0
762	}
763	if req.ContentLength != 0 {
764		return req.ContentLength
765	}
766	return -1
767}
768
769func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) {
770	resp, _, err := cc.roundTrip(req)
771	return resp, err
772}
773
774func (cc *ClientConn) roundTrip(req *http.Request) (res *http.Response, gotErrAfterReqBodyWrite bool, err error) {
775	if err := checkConnHeaders(req); err != nil {
776		return nil, false, err
777	}
778	if cc.idleTimer != nil {
779		cc.idleTimer.Stop()
780	}
781
782	trailers, err := commaSeparatedTrailers(req)
783	if err != nil {
784		return nil, false, err
785	}
786	hasTrailers := trailers != ""
787
788	cc.mu.Lock()
789	if err := cc.awaitOpenSlotForRequest(req); err != nil {
790		cc.mu.Unlock()
791		return nil, false, err
792	}
793
794	body := req.Body
795	contentLen := actualContentLength(req)
796	hasBody := contentLen != 0
797
798	// TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere?
799	var requestedGzip bool
800	if !cc.t.disableCompression() &&
801		req.Header.Get("Accept-Encoding") == "" &&
802		req.Header.Get("Range") == "" &&
803		req.Method != "HEAD" {
804		// Request gzip only, not deflate. Deflate is ambiguous and
805		// not as universally supported anyway.
806		// See: http://www.gzip.org/zlib/zlib_faq.html#faq38
807		//
808		// Note that we don't request this for HEAD requests,
809		// due to a bug in nginx:
810		//   http://trac.nginx.org/nginx/ticket/358
811		//   https://golang.org/issue/5522
812		//
813		// We don't request gzip if the request is for a range, since
814		// auto-decoding a portion of a gzipped document will just fail
815		// anyway. See https://golang.org/issue/8923
816		requestedGzip = true
817	}
818
819	// we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,} (DATA is
820	// sent by writeRequestBody below, along with any Trailers,
821	// again in form HEADERS{1}, CONTINUATION{0,})
822	hdrs, err := cc.encodeHeaders(req, requestedGzip, trailers, contentLen)
823	if err != nil {
824		cc.mu.Unlock()
825		return nil, false, err
826	}
827
828	cs := cc.newStream()
829	cs.req = req
830	cs.trace = requestTrace(req)
831	cs.requestedGzip = requestedGzip
832	bodyWriter := cc.t.getBodyWriterState(cs, body)
833	cs.on100 = bodyWriter.on100
834
835	cc.wmu.Lock()
836	endStream := !hasBody && !hasTrailers
837	werr := cc.writeHeaders(cs.ID, endStream, int(cc.maxFrameSize), hdrs)
838	cc.wmu.Unlock()
839	traceWroteHeaders(cs.trace)
840	cc.mu.Unlock()
841
842	if werr != nil {
843		if hasBody {
844			req.Body.Close() // per RoundTripper contract
845			bodyWriter.cancel()
846		}
847		cc.forgetStreamID(cs.ID)
848		// Don't bother sending a RST_STREAM (our write already failed;
849		// no need to keep writing)
850		traceWroteRequest(cs.trace, werr)
851		return nil, false, werr
852	}
853
854	var respHeaderTimer <-chan time.Time
855	if hasBody {
856		bodyWriter.scheduleBodyWrite()
857	} else {
858		traceWroteRequest(cs.trace, nil)
859		if d := cc.responseHeaderTimeout(); d != 0 {
860			timer := time.NewTimer(d)
861			defer timer.Stop()
862			respHeaderTimer = timer.C
863		}
864	}
865
866	readLoopResCh := cs.resc
867	bodyWritten := false
868	ctx := reqContext(req)
869
870	handleReadLoopResponse := func(re resAndError) (*http.Response, bool, error) {
871		res := re.res
872		if re.err != nil || res.StatusCode > 299 {
873			// On error or status code 3xx, 4xx, 5xx, etc abort any
874			// ongoing write, assuming that the server doesn't care
875			// about our request body. If the server replied with 1xx or
876			// 2xx, however, then assume the server DOES potentially
877			// want our body (e.g. full-duplex streaming:
878			// golang.org/issue/13444). If it turns out the server
879			// doesn't, they'll RST_STREAM us soon enough. This is a
880			// heuristic to avoid adding knobs to Transport. Hopefully
881			// we can keep it.
882			bodyWriter.cancel()
883			cs.abortRequestBodyWrite(errStopReqBodyWrite)
884		}
885		if re.err != nil {
886			cc.forgetStreamID(cs.ID)
887			return nil, cs.getStartedWrite(), re.err
888		}
889		res.Request = req
890		res.TLS = cc.tlsState
891		return res, false, nil
892	}
893
894	for {
895		select {
896		case re := <-readLoopResCh:
897			return handleReadLoopResponse(re)
898		case <-respHeaderTimer:
899			if !hasBody || bodyWritten {
900				cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
901			} else {
902				bodyWriter.cancel()
903				cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
904			}
905			cc.forgetStreamID(cs.ID)
906			return nil, cs.getStartedWrite(), errTimeout
907		case <-ctx.Done():
908			if !hasBody || bodyWritten {
909				cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
910			} else {
911				bodyWriter.cancel()
912				cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
913			}
914			cc.forgetStreamID(cs.ID)
915			return nil, cs.getStartedWrite(), ctx.Err()
916		case <-req.Cancel:
917			if !hasBody || bodyWritten {
918				cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
919			} else {
920				bodyWriter.cancel()
921				cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
922			}
923			cc.forgetStreamID(cs.ID)
924			return nil, cs.getStartedWrite(), errRequestCanceled
925		case <-cs.peerReset:
926			// processResetStream already removed the
927			// stream from the streams map; no need for
928			// forgetStreamID.
929			return nil, cs.getStartedWrite(), cs.resetErr
930		case err := <-bodyWriter.resc:
931			// Prefer the read loop's response, if available. Issue 16102.
932			select {
933			case re := <-readLoopResCh:
934				return handleReadLoopResponse(re)
935			default:
936			}
937			if err != nil {
938				return nil, cs.getStartedWrite(), err
939			}
940			bodyWritten = true
941			if d := cc.responseHeaderTimeout(); d != 0 {
942				timer := time.NewTimer(d)
943				defer timer.Stop()
944				respHeaderTimer = timer.C
945			}
946		}
947	}
948}
949
950// awaitOpenSlotForRequest waits until len(streams) < maxConcurrentStreams.
951// Must hold cc.mu.
952func (cc *ClientConn) awaitOpenSlotForRequest(req *http.Request) error {
953	var waitingForConn chan struct{}
954	var waitingForConnErr error // guarded by cc.mu
955	for {
956		cc.lastActive = time.Now()
957		if cc.closed || !cc.canTakeNewRequestLocked() {
958			if waitingForConn != nil {
959				close(waitingForConn)
960			}
961			return errClientConnUnusable
962		}
963		if int64(len(cc.streams))+1 <= int64(cc.maxConcurrentStreams) {
964			if waitingForConn != nil {
965				close(waitingForConn)
966			}
967			return nil
968		}
969		// Unfortunately, we cannot wait on a condition variable and channel at
970		// the same time, so instead, we spin up a goroutine to check if the
971		// request is canceled while we wait for a slot to open in the connection.
972		if waitingForConn == nil {
973			waitingForConn = make(chan struct{})
974			go func() {
975				if err := awaitRequestCancel(req, waitingForConn); err != nil {
976					cc.mu.Lock()
977					waitingForConnErr = err
978					cc.cond.Broadcast()
979					cc.mu.Unlock()
980				}
981			}()
982		}
983		cc.pendingRequests++
984		cc.cond.Wait()
985		cc.pendingRequests--
986		if waitingForConnErr != nil {
987			return waitingForConnErr
988		}
989	}
990}
991
992// requires cc.wmu be held
993func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, maxFrameSize int, hdrs []byte) error {
994	first := true // first frame written (HEADERS is first, then CONTINUATION)
995	for len(hdrs) > 0 && cc.werr == nil {
996		chunk := hdrs
997		if len(chunk) > maxFrameSize {
998			chunk = chunk[:maxFrameSize]
999		}
1000		hdrs = hdrs[len(chunk):]
1001		endHeaders := len(hdrs) == 0
1002		if first {
1003			cc.fr.WriteHeaders(HeadersFrameParam{
1004				StreamID:      streamID,
1005				BlockFragment: chunk,
1006				EndStream:     endStream,
1007				EndHeaders:    endHeaders,
1008			})
1009			first = false
1010		} else {
1011			cc.fr.WriteContinuation(streamID, endHeaders, chunk)
1012		}
1013	}
1014	// TODO(bradfitz): this Flush could potentially block (as
1015	// could the WriteHeaders call(s) above), which means they
1016	// wouldn't respond to Request.Cancel being readable. That's
1017	// rare, but this should probably be in a goroutine.
1018	cc.bw.Flush()
1019	return cc.werr
1020}
1021
1022// internal error values; they don't escape to callers
1023var (
1024	// abort request body write; don't send cancel
1025	errStopReqBodyWrite = errors.New("http2: aborting request body write")
1026
1027	// abort request body write, but send stream reset of cancel.
1028	errStopReqBodyWriteAndCancel = errors.New("http2: canceling request")
1029)
1030
1031func (cs *clientStream) writeRequestBody(body io.Reader, bodyCloser io.Closer) (err error) {
1032	cc := cs.cc
1033	sentEnd := false // whether we sent the final DATA frame w/ END_STREAM
1034	buf := cc.frameScratchBuffer()
1035	defer cc.putFrameScratchBuffer(buf)
1036
1037	defer func() {
1038		traceWroteRequest(cs.trace, err)
1039		// TODO: write h12Compare test showing whether
1040		// Request.Body is closed by the Transport,
1041		// and in multiple cases: server replies <=299 and >299
1042		// while still writing request body
1043		cerr := bodyCloser.Close()
1044		if err == nil {
1045			err = cerr
1046		}
1047	}()
1048
1049	req := cs.req
1050	hasTrailers := req.Trailer != nil
1051
1052	var sawEOF bool
1053	for !sawEOF {
1054		n, err := body.Read(buf)
1055		if err == io.EOF {
1056			sawEOF = true
1057			err = nil
1058		} else if err != nil {
1059			return err
1060		}
1061
1062		remain := buf[:n]
1063		for len(remain) > 0 && err == nil {
1064			var allowed int32
1065			allowed, err = cs.awaitFlowControl(len(remain))
1066			switch {
1067			case err == errStopReqBodyWrite:
1068				return err
1069			case err == errStopReqBodyWriteAndCancel:
1070				cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
1071				return err
1072			case err != nil:
1073				return err
1074			}
1075			cc.wmu.Lock()
1076			data := remain[:allowed]
1077			remain = remain[allowed:]
1078			sentEnd = sawEOF && len(remain) == 0 && !hasTrailers
1079			err = cc.fr.WriteData(cs.ID, sentEnd, data)
1080			if err == nil {
1081				// TODO(bradfitz): this flush is for latency, not bandwidth.
1082				// Most requests won't need this. Make this opt-in or
1083				// opt-out?  Use some heuristic on the body type? Nagel-like
1084				// timers?  Based on 'n'? Only last chunk of this for loop,
1085				// unless flow control tokens are low? For now, always.
1086				// If we change this, see comment below.
1087				err = cc.bw.Flush()
1088			}
1089			cc.wmu.Unlock()
1090		}
1091		if err != nil {
1092			return err
1093		}
1094	}
1095
1096	if sentEnd {
1097		// Already sent END_STREAM (which implies we have no
1098		// trailers) and flushed, because currently all
1099		// WriteData frames above get a flush. So we're done.
1100		return nil
1101	}
1102
1103	var trls []byte
1104	if hasTrailers {
1105		cc.mu.Lock()
1106		trls, err = cc.encodeTrailers(req)
1107		cc.mu.Unlock()
1108		if err != nil {
1109			cc.writeStreamReset(cs.ID, ErrCodeInternal, err)
1110			cc.forgetStreamID(cs.ID)
1111			return err
1112		}
1113	}
1114
1115	cc.mu.Lock()
1116	maxFrameSize := int(cc.maxFrameSize)
1117	cc.mu.Unlock()
1118
1119	cc.wmu.Lock()
1120	defer cc.wmu.Unlock()
1121
1122	// Two ways to send END_STREAM: either with trailers, or
1123	// with an empty DATA frame.
1124	if len(trls) > 0 {
1125		err = cc.writeHeaders(cs.ID, true, maxFrameSize, trls)
1126	} else {
1127		err = cc.fr.WriteData(cs.ID, true, nil)
1128	}
1129	if ferr := cc.bw.Flush(); ferr != nil && err == nil {
1130		err = ferr
1131	}
1132	return err
1133}
1134
1135// awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
1136// control tokens from the server.
1137// It returns either the non-zero number of tokens taken or an error
1138// if the stream is dead.
1139func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
1140	cc := cs.cc
1141	cc.mu.Lock()
1142	defer cc.mu.Unlock()
1143	for {
1144		if cc.closed {
1145			return 0, errClientConnClosed
1146		}
1147		if cs.stopReqBody != nil {
1148			return 0, cs.stopReqBody
1149		}
1150		if err := cs.checkResetOrDone(); err != nil {
1151			return 0, err
1152		}
1153		if a := cs.flow.available(); a > 0 {
1154			take := a
1155			if int(take) > maxBytes {
1156
1157				take = int32(maxBytes) // can't truncate int; take is int32
1158			}
1159			if take > int32(cc.maxFrameSize) {
1160				take = int32(cc.maxFrameSize)
1161			}
1162			cs.flow.take(take)
1163			return take, nil
1164		}
1165		cc.cond.Wait()
1166	}
1167}
1168
1169type badStringError struct {
1170	what string
1171	str  string
1172}
1173
1174func (e *badStringError) Error() string { return fmt.Sprintf("%s %q", e.what, e.str) }
1175
1176// requires cc.mu be held.
1177func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) {
1178	cc.hbuf.Reset()
1179
1180	host := req.Host
1181	if host == "" {
1182		host = req.URL.Host
1183	}
1184	host, err := httpguts.PunycodeHostPort(host)
1185	if err != nil {
1186		return nil, err
1187	}
1188
1189	var path string
1190	if req.Method != "CONNECT" {
1191		path = req.URL.RequestURI()
1192		if !validPseudoPath(path) {
1193			orig := path
1194			path = strings.TrimPrefix(path, req.URL.Scheme+"://"+host)
1195			if !validPseudoPath(path) {
1196				if req.URL.Opaque != "" {
1197					return nil, fmt.Errorf("invalid request :path %q from URL.Opaque = %q", orig, req.URL.Opaque)
1198				} else {
1199					return nil, fmt.Errorf("invalid request :path %q", orig)
1200				}
1201			}
1202		}
1203	}
1204
1205	// Check for any invalid headers and return an error before we
1206	// potentially pollute our hpack state. (We want to be able to
1207	// continue to reuse the hpack encoder for future requests)
1208	for k, vv := range req.Header {
1209		if !httpguts.ValidHeaderFieldName(k) {
1210			return nil, fmt.Errorf("invalid HTTP header name %q", k)
1211		}
1212		for _, v := range vv {
1213			if !httpguts.ValidHeaderFieldValue(v) {
1214				return nil, fmt.Errorf("invalid HTTP header value %q for header %q", v, k)
1215			}
1216		}
1217	}
1218
1219	enumerateHeaders := func(f func(name, value string)) {
1220		// 8.1.2.3 Request Pseudo-Header Fields
1221		// The :path pseudo-header field includes the path and query parts of the
1222		// target URI (the path-absolute production and optionally a '?' character
1223		// followed by the query production (see Sections 3.3 and 3.4 of
1224		// [RFC3986]).
1225		f(":authority", host)
1226		f(":method", req.Method)
1227		if req.Method != "CONNECT" {
1228			f(":path", path)
1229			f(":scheme", req.URL.Scheme)
1230		}
1231		if trailers != "" {
1232			f("trailer", trailers)
1233		}
1234
1235		var didUA bool
1236		for k, vv := range req.Header {
1237			if strings.EqualFold(k, "host") || strings.EqualFold(k, "content-length") {
1238				// Host is :authority, already sent.
1239				// Content-Length is automatic, set below.
1240				continue
1241			} else if strings.EqualFold(k, "connection") || strings.EqualFold(k, "proxy-connection") ||
1242				strings.EqualFold(k, "transfer-encoding") || strings.EqualFold(k, "upgrade") ||
1243				strings.EqualFold(k, "keep-alive") {
1244				// Per 8.1.2.2 Connection-Specific Header
1245				// Fields, don't send connection-specific
1246				// fields. We have already checked if any
1247				// are error-worthy so just ignore the rest.
1248				continue
1249			} else if strings.EqualFold(k, "user-agent") {
1250				// Match Go's http1 behavior: at most one
1251				// User-Agent. If set to nil or empty string,
1252				// then omit it. Otherwise if not mentioned,
1253				// include the default (below).
1254				didUA = true
1255				if len(vv) < 1 {
1256					continue
1257				}
1258				vv = vv[:1]
1259				if vv[0] == "" {
1260					continue
1261				}
1262
1263			}
1264
1265			for _, v := range vv {
1266				f(k, v)
1267			}
1268		}
1269		if shouldSendReqContentLength(req.Method, contentLength) {
1270			f("content-length", strconv.FormatInt(contentLength, 10))
1271		}
1272		if addGzipHeader {
1273			f("accept-encoding", "gzip")
1274		}
1275		if !didUA {
1276			f("user-agent", defaultUserAgent)
1277		}
1278	}
1279
1280	// Do a first pass over the headers counting bytes to ensure
1281	// we don't exceed cc.peerMaxHeaderListSize. This is done as a
1282	// separate pass before encoding the headers to prevent
1283	// modifying the hpack state.
1284	hlSize := uint64(0)
1285	enumerateHeaders(func(name, value string) {
1286		hf := hpack.HeaderField{Name: name, Value: value}
1287		hlSize += uint64(hf.Size())
1288	})
1289
1290	if hlSize > cc.peerMaxHeaderListSize {
1291		return nil, errRequestHeaderListSize
1292	}
1293
1294	// Header list size is ok. Write the headers.
1295	enumerateHeaders(func(name, value string) {
1296		cc.writeHeader(strings.ToLower(name), value)
1297	})
1298
1299	return cc.hbuf.Bytes(), nil
1300}
1301
1302// shouldSendReqContentLength reports whether the http2.Transport should send
1303// a "content-length" request header. This logic is basically a copy of the net/http
1304// transferWriter.shouldSendContentLength.
1305// The contentLength is the corrected contentLength (so 0 means actually 0, not unknown).
1306// -1 means unknown.
1307func shouldSendReqContentLength(method string, contentLength int64) bool {
1308	if contentLength > 0 {
1309		return true
1310	}
1311	if contentLength < 0 {
1312		return false
1313	}
1314	// For zero bodies, whether we send a content-length depends on the method.
1315	// It also kinda doesn't matter for http2 either way, with END_STREAM.
1316	switch method {
1317	case "POST", "PUT", "PATCH":
1318		return true
1319	default:
1320		return false
1321	}
1322}
1323
1324// requires cc.mu be held.
1325func (cc *ClientConn) encodeTrailers(req *http.Request) ([]byte, error) {
1326	cc.hbuf.Reset()
1327
1328	hlSize := uint64(0)
1329	for k, vv := range req.Trailer {
1330		for _, v := range vv {
1331			hf := hpack.HeaderField{Name: k, Value: v}
1332			hlSize += uint64(hf.Size())
1333		}
1334	}
1335	if hlSize > cc.peerMaxHeaderListSize {
1336		return nil, errRequestHeaderListSize
1337	}
1338
1339	for k, vv := range req.Trailer {
1340		// Transfer-Encoding, etc.. have already been filtered at the
1341		// start of RoundTrip
1342		lowKey := strings.ToLower(k)
1343		for _, v := range vv {
1344			cc.writeHeader(lowKey, v)
1345		}
1346	}
1347	return cc.hbuf.Bytes(), nil
1348}
1349
1350func (cc *ClientConn) writeHeader(name, value string) {
1351	if VerboseLogs {
1352		log.Printf("http2: Transport encoding header %q = %q", name, value)
1353	}
1354	cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
1355}
1356
1357type resAndError struct {
1358	res *http.Response
1359	err error
1360}
1361
1362// requires cc.mu be held.
1363func (cc *ClientConn) newStream() *clientStream {
1364	cs := &clientStream{
1365		cc:        cc,
1366		ID:        cc.nextStreamID,
1367		resc:      make(chan resAndError, 1),
1368		peerReset: make(chan struct{}),
1369		done:      make(chan struct{}),
1370	}
1371	cs.flow.add(int32(cc.initialWindowSize))
1372	cs.flow.setConnFlow(&cc.flow)
1373	cs.inflow.add(transportDefaultStreamFlow)
1374	cs.inflow.setConnFlow(&cc.inflow)
1375	cc.nextStreamID += 2
1376	cc.streams[cs.ID] = cs
1377	return cs
1378}
1379
1380func (cc *ClientConn) forgetStreamID(id uint32) {
1381	cc.streamByID(id, true)
1382}
1383
1384func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream {
1385	cc.mu.Lock()
1386	defer cc.mu.Unlock()
1387	cs := cc.streams[id]
1388	if andRemove && cs != nil && !cc.closed {
1389		cc.lastActive = time.Now()
1390		delete(cc.streams, id)
1391		if len(cc.streams) == 0 && cc.idleTimer != nil {
1392			cc.idleTimer.Reset(cc.idleTimeout)
1393		}
1394		close(cs.done)
1395		// Wake up checkResetOrDone via clientStream.awaitFlowControl and
1396		// wake up RoundTrip if there is a pending request.
1397		cc.cond.Broadcast()
1398	}
1399	return cs
1400}
1401
1402// clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.
1403type clientConnReadLoop struct {
1404	cc            *ClientConn
1405	closeWhenIdle bool
1406}
1407
1408// readLoop runs in its own goroutine and reads and dispatches frames.
1409func (cc *ClientConn) readLoop() {
1410	rl := &clientConnReadLoop{cc: cc}
1411	defer rl.cleanup()
1412	cc.readerErr = rl.run()
1413	if ce, ok := cc.readerErr.(ConnectionError); ok {
1414		cc.wmu.Lock()
1415		cc.fr.WriteGoAway(0, ErrCode(ce), nil)
1416		cc.wmu.Unlock()
1417	}
1418}
1419
1420// GoAwayError is returned by the Transport when the server closes the
1421// TCP connection after sending a GOAWAY frame.
1422type GoAwayError struct {
1423	LastStreamID uint32
1424	ErrCode      ErrCode
1425	DebugData    string
1426}
1427
1428func (e GoAwayError) Error() string {
1429	return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q",
1430		e.LastStreamID, e.ErrCode, e.DebugData)
1431}
1432
1433func isEOFOrNetReadError(err error) bool {
1434	if err == io.EOF {
1435		return true
1436	}
1437	ne, ok := err.(*net.OpError)
1438	return ok && ne.Op == "read"
1439}
1440
1441func (rl *clientConnReadLoop) cleanup() {
1442	cc := rl.cc
1443	defer cc.tconn.Close()
1444	defer cc.t.connPool().MarkDead(cc)
1445	defer close(cc.readerDone)
1446
1447	if cc.idleTimer != nil {
1448		cc.idleTimer.Stop()
1449	}
1450
1451	// Close any response bodies if the server closes prematurely.
1452	// TODO: also do this if we've written the headers but not
1453	// gotten a response yet.
1454	err := cc.readerErr
1455	cc.mu.Lock()
1456	if cc.goAway != nil && isEOFOrNetReadError(err) {
1457		err = GoAwayError{
1458			LastStreamID: cc.goAway.LastStreamID,
1459			ErrCode:      cc.goAway.ErrCode,
1460			DebugData:    cc.goAwayDebug,
1461		}
1462	} else if err == io.EOF {
1463		err = io.ErrUnexpectedEOF
1464	}
1465	for _, cs := range cc.streams {
1466		cs.bufPipe.CloseWithError(err) // no-op if already closed
1467		select {
1468		case cs.resc <- resAndError{err: err}:
1469		default:
1470		}
1471		close(cs.done)
1472	}
1473	cc.closed = true
1474	cc.cond.Broadcast()
1475	cc.mu.Unlock()
1476}
1477
1478func (rl *clientConnReadLoop) run() error {
1479	cc := rl.cc
1480	rl.closeWhenIdle = cc.t.disableKeepAlives() || cc.singleUse
1481	gotReply := false // ever saw a HEADERS reply
1482	gotSettings := false
1483	for {
1484		f, err := cc.fr.ReadFrame()
1485		if err != nil {
1486			cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err)
1487		}
1488		if se, ok := err.(StreamError); ok {
1489			if cs := cc.streamByID(se.StreamID, false); cs != nil {
1490				cs.cc.writeStreamReset(cs.ID, se.Code, err)
1491				cs.cc.forgetStreamID(cs.ID)
1492				if se.Cause == nil {
1493					se.Cause = cc.fr.errDetail
1494				}
1495				rl.endStreamError(cs, se)
1496			}
1497			continue
1498		} else if err != nil {
1499			return err
1500		}
1501		if VerboseLogs {
1502			cc.vlogf("http2: Transport received %s", summarizeFrame(f))
1503		}
1504		if !gotSettings {
1505			if _, ok := f.(*SettingsFrame); !ok {
1506				cc.logf("protocol error: received %T before a SETTINGS frame", f)
1507				return ConnectionError(ErrCodeProtocol)
1508			}
1509			gotSettings = true
1510		}
1511		maybeIdle := false // whether frame might transition us to idle
1512
1513		switch f := f.(type) {
1514		case *MetaHeadersFrame:
1515			err = rl.processHeaders(f)
1516			maybeIdle = true
1517			gotReply = true
1518		case *DataFrame:
1519			err = rl.processData(f)
1520			maybeIdle = true
1521		case *GoAwayFrame:
1522			err = rl.processGoAway(f)
1523			maybeIdle = true
1524		case *RSTStreamFrame:
1525			err = rl.processResetStream(f)
1526			maybeIdle = true
1527		case *SettingsFrame:
1528			err = rl.processSettings(f)
1529		case *PushPromiseFrame:
1530			err = rl.processPushPromise(f)
1531		case *WindowUpdateFrame:
1532			err = rl.processWindowUpdate(f)
1533		case *PingFrame:
1534			err = rl.processPing(f)
1535		default:
1536			cc.logf("Transport: unhandled response frame type %T", f)
1537		}
1538		if err != nil {
1539			if VerboseLogs {
1540				cc.vlogf("http2: Transport conn %p received error from processing frame %v: %v", cc, summarizeFrame(f), err)
1541			}
1542			return err
1543		}
1544		if rl.closeWhenIdle && gotReply && maybeIdle {
1545			cc.closeIfIdle()
1546		}
1547	}
1548}
1549
1550func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error {
1551	cc := rl.cc
1552	cs := cc.streamByID(f.StreamID, false)
1553	if cs == nil {
1554		// We'd get here if we canceled a request while the
1555		// server had its response still in flight. So if this
1556		// was just something we canceled, ignore it.
1557		return nil
1558	}
1559	if f.StreamEnded() {
1560		// Issue 20521: If the stream has ended, streamByID() causes
1561		// clientStream.done to be closed, which causes the request's bodyWriter
1562		// to be closed with an errStreamClosed, which may be received by
1563		// clientConn.RoundTrip before the result of processing these headers.
1564		// Deferring stream closure allows the header processing to occur first.
1565		// clientConn.RoundTrip may still receive the bodyWriter error first, but
1566		// the fix for issue 16102 prioritises any response.
1567		//
1568		// Issue 22413: If there is no request body, we should close the
1569		// stream before writing to cs.resc so that the stream is closed
1570		// immediately once RoundTrip returns.
1571		if cs.req.Body != nil {
1572			defer cc.forgetStreamID(f.StreamID)
1573		} else {
1574			cc.forgetStreamID(f.StreamID)
1575		}
1576	}
1577	if !cs.firstByte {
1578		if cs.trace != nil {
1579			// TODO(bradfitz): move first response byte earlier,
1580			// when we first read the 9 byte header, not waiting
1581			// until all the HEADERS+CONTINUATION frames have been
1582			// merged. This works for now.
1583			traceFirstResponseByte(cs.trace)
1584		}
1585		cs.firstByte = true
1586	}
1587	if !cs.pastHeaders {
1588		cs.pastHeaders = true
1589	} else {
1590		return rl.processTrailers(cs, f)
1591	}
1592
1593	res, err := rl.handleResponse(cs, f)
1594	if err != nil {
1595		if _, ok := err.(ConnectionError); ok {
1596			return err
1597		}
1598		// Any other error type is a stream error.
1599		cs.cc.writeStreamReset(f.StreamID, ErrCodeProtocol, err)
1600		cc.forgetStreamID(cs.ID)
1601		cs.resc <- resAndError{err: err}
1602		return nil // return nil from process* funcs to keep conn alive
1603	}
1604	if res == nil {
1605		// (nil, nil) special case. See handleResponse docs.
1606		return nil
1607	}
1608	cs.resTrailer = &res.Trailer
1609	cs.resc <- resAndError{res: res}
1610	return nil
1611}
1612
1613// may return error types nil, or ConnectionError. Any other error value
1614// is a StreamError of type ErrCodeProtocol. The returned error in that case
1615// is the detail.
1616//
1617// As a special case, handleResponse may return (nil, nil) to skip the
1618// frame (currently only used for 100 expect continue). This special
1619// case is going away after Issue 13851 is fixed.
1620func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFrame) (*http.Response, error) {
1621	if f.Truncated {
1622		return nil, errResponseHeaderListSize
1623	}
1624
1625	status := f.PseudoValue("status")
1626	if status == "" {
1627		return nil, errors.New("malformed response from server: missing status pseudo header")
1628	}
1629	statusCode, err := strconv.Atoi(status)
1630	if err != nil {
1631		return nil, errors.New("malformed response from server: malformed non-numeric status pseudo header")
1632	}
1633
1634	if statusCode == 100 {
1635		traceGot100Continue(cs.trace)
1636		if cs.on100 != nil {
1637			cs.on100() // forces any write delay timer to fire
1638		}
1639		cs.pastHeaders = false // do it all again
1640		return nil, nil
1641	}
1642
1643	header := make(http.Header)
1644	res := &http.Response{
1645		Proto:      "HTTP/2.0",
1646		ProtoMajor: 2,
1647		Header:     header,
1648		StatusCode: statusCode,
1649		Status:     status + " " + http.StatusText(statusCode),
1650	}
1651	for _, hf := range f.RegularFields() {
1652		key := http.CanonicalHeaderKey(hf.Name)
1653		if key == "Trailer" {
1654			t := res.Trailer
1655			if t == nil {
1656				t = make(http.Header)
1657				res.Trailer = t
1658			}
1659			foreachHeaderElement(hf.Value, func(v string) {
1660				t[http.CanonicalHeaderKey(v)] = nil
1661			})
1662		} else {
1663			header[key] = append(header[key], hf.Value)
1664		}
1665	}
1666
1667	streamEnded := f.StreamEnded()
1668	isHead := cs.req.Method == "HEAD"
1669	if !streamEnded || isHead {
1670		res.ContentLength = -1
1671		if clens := res.Header["Content-Length"]; len(clens) == 1 {
1672			if clen64, err := strconv.ParseInt(clens[0], 10, 64); err == nil {
1673				res.ContentLength = clen64
1674			} else {
1675				// TODO: care? unlike http/1, it won't mess up our framing, so it's
1676				// more safe smuggling-wise to ignore.
1677			}
1678		} else if len(clens) > 1 {
1679			// TODO: care? unlike http/1, it won't mess up our framing, so it's
1680			// more safe smuggling-wise to ignore.
1681		}
1682	}
1683
1684	if streamEnded || isHead {
1685		res.Body = noBody
1686		return res, nil
1687	}
1688
1689	cs.bufPipe = pipe{b: &dataBuffer{expected: res.ContentLength}}
1690	cs.bytesRemain = res.ContentLength
1691	res.Body = transportResponseBody{cs}
1692	go cs.awaitRequestCancel(cs.req)
1693
1694	if cs.requestedGzip && res.Header.Get("Content-Encoding") == "gzip" {
1695		res.Header.Del("Content-Encoding")
1696		res.Header.Del("Content-Length")
1697		res.ContentLength = -1
1698		res.Body = &gzipReader{body: res.Body}
1699		setResponseUncompressed(res)
1700	}
1701	return res, nil
1702}
1703
1704func (rl *clientConnReadLoop) processTrailers(cs *clientStream, f *MetaHeadersFrame) error {
1705	if cs.pastTrailers {
1706		// Too many HEADERS frames for this stream.
1707		return ConnectionError(ErrCodeProtocol)
1708	}
1709	cs.pastTrailers = true
1710	if !f.StreamEnded() {
1711		// We expect that any headers for trailers also
1712		// has END_STREAM.
1713		return ConnectionError(ErrCodeProtocol)
1714	}
1715	if len(f.PseudoFields()) > 0 {
1716		// No pseudo header fields are defined for trailers.
1717		// TODO: ConnectionError might be overly harsh? Check.
1718		return ConnectionError(ErrCodeProtocol)
1719	}
1720
1721	trailer := make(http.Header)
1722	for _, hf := range f.RegularFields() {
1723		key := http.CanonicalHeaderKey(hf.Name)
1724		trailer[key] = append(trailer[key], hf.Value)
1725	}
1726	cs.trailer = trailer
1727
1728	rl.endStream(cs)
1729	return nil
1730}
1731
1732// transportResponseBody is the concrete type of Transport.RoundTrip's
1733// Response.Body. It is an io.ReadCloser. On Read, it reads from cs.body.
1734// On Close it sends RST_STREAM if EOF wasn't already seen.
1735type transportResponseBody struct {
1736	cs *clientStream
1737}
1738
1739func (b transportResponseBody) Read(p []byte) (n int, err error) {
1740	cs := b.cs
1741	cc := cs.cc
1742
1743	if cs.readErr != nil {
1744		return 0, cs.readErr
1745	}
1746	n, err = b.cs.bufPipe.Read(p)
1747	if cs.bytesRemain != -1 {
1748		if int64(n) > cs.bytesRemain {
1749			n = int(cs.bytesRemain)
1750			if err == nil {
1751				err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
1752				cc.writeStreamReset(cs.ID, ErrCodeProtocol, err)
1753			}
1754			cs.readErr = err
1755			return int(cs.bytesRemain), err
1756		}
1757		cs.bytesRemain -= int64(n)
1758		if err == io.EOF && cs.bytesRemain > 0 {
1759			err = io.ErrUnexpectedEOF
1760			cs.readErr = err
1761			return n, err
1762		}
1763	}
1764	if n == 0 {
1765		// No flow control tokens to send back.
1766		return
1767	}
1768
1769	cc.mu.Lock()
1770	defer cc.mu.Unlock()
1771
1772	var connAdd, streamAdd int32
1773	// Check the conn-level first, before the stream-level.
1774	if v := cc.inflow.available(); v < transportDefaultConnFlow/2 {
1775		connAdd = transportDefaultConnFlow - v
1776		cc.inflow.add(connAdd)
1777	}
1778	if err == nil { // No need to refresh if the stream is over or failed.
1779		// Consider any buffered body data (read from the conn but not
1780		// consumed by the client) when computing flow control for this
1781		// stream.
1782		v := int(cs.inflow.available()) + cs.bufPipe.Len()
1783		if v < transportDefaultStreamFlow-transportDefaultStreamMinRefresh {
1784			streamAdd = int32(transportDefaultStreamFlow - v)
1785			cs.inflow.add(streamAdd)
1786		}
1787	}
1788	if connAdd != 0 || streamAdd != 0 {
1789		cc.wmu.Lock()
1790		defer cc.wmu.Unlock()
1791		if connAdd != 0 {
1792			cc.fr.WriteWindowUpdate(0, mustUint31(connAdd))
1793		}
1794		if streamAdd != 0 {
1795			cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd))
1796		}
1797		cc.bw.Flush()
1798	}
1799	return
1800}
1801
1802var errClosedResponseBody = errors.New("http2: response body closed")
1803
1804func (b transportResponseBody) Close() error {
1805	cs := b.cs
1806	cc := cs.cc
1807
1808	serverSentStreamEnd := cs.bufPipe.Err() == io.EOF
1809	unread := cs.bufPipe.Len()
1810
1811	if unread > 0 || !serverSentStreamEnd {
1812		cc.mu.Lock()
1813		cc.wmu.Lock()
1814		if !serverSentStreamEnd {
1815			cc.fr.WriteRSTStream(cs.ID, ErrCodeCancel)
1816			cs.didReset = true
1817		}
1818		// Return connection-level flow control.
1819		if unread > 0 {
1820			cc.inflow.add(int32(unread))
1821			cc.fr.WriteWindowUpdate(0, uint32(unread))
1822		}
1823		cc.bw.Flush()
1824		cc.wmu.Unlock()
1825		cc.mu.Unlock()
1826	}
1827
1828	cs.bufPipe.BreakWithError(errClosedResponseBody)
1829	cc.forgetStreamID(cs.ID)
1830	return nil
1831}
1832
1833func (rl *clientConnReadLoop) processData(f *DataFrame) error {
1834	cc := rl.cc
1835	cs := cc.streamByID(f.StreamID, f.StreamEnded())
1836	data := f.Data()
1837	if cs == nil {
1838		cc.mu.Lock()
1839		neverSent := cc.nextStreamID
1840		cc.mu.Unlock()
1841		if f.StreamID >= neverSent {
1842			// We never asked for this.
1843			cc.logf("http2: Transport received unsolicited DATA frame; closing connection")
1844			return ConnectionError(ErrCodeProtocol)
1845		}
1846		// We probably did ask for this, but canceled. Just ignore it.
1847		// TODO: be stricter here? only silently ignore things which
1848		// we canceled, but not things which were closed normally
1849		// by the peer? Tough without accumulating too much state.
1850
1851		// But at least return their flow control:
1852		if f.Length > 0 {
1853			cc.mu.Lock()
1854			cc.inflow.add(int32(f.Length))
1855			cc.mu.Unlock()
1856
1857			cc.wmu.Lock()
1858			cc.fr.WriteWindowUpdate(0, uint32(f.Length))
1859			cc.bw.Flush()
1860			cc.wmu.Unlock()
1861		}
1862		return nil
1863	}
1864	if !cs.firstByte {
1865		cc.logf("protocol error: received DATA before a HEADERS frame")
1866		rl.endStreamError(cs, StreamError{
1867			StreamID: f.StreamID,
1868			Code:     ErrCodeProtocol,
1869		})
1870		return nil
1871	}
1872	if f.Length > 0 {
1873		if cs.req.Method == "HEAD" && len(data) > 0 {
1874			cc.logf("protocol error: received DATA on a HEAD request")
1875			rl.endStreamError(cs, StreamError{
1876				StreamID: f.StreamID,
1877				Code:     ErrCodeProtocol,
1878			})
1879			return nil
1880		}
1881		// Check connection-level flow control.
1882		cc.mu.Lock()
1883		if cs.inflow.available() >= int32(f.Length) {
1884			cs.inflow.take(int32(f.Length))
1885		} else {
1886			cc.mu.Unlock()
1887			return ConnectionError(ErrCodeFlowControl)
1888		}
1889		// Return any padded flow control now, since we won't
1890		// refund it later on body reads.
1891		var refund int
1892		if pad := int(f.Length) - len(data); pad > 0 {
1893			refund += pad
1894		}
1895		// Return len(data) now if the stream is already closed,
1896		// since data will never be read.
1897		didReset := cs.didReset
1898		if didReset {
1899			refund += len(data)
1900		}
1901		if refund > 0 {
1902			cc.inflow.add(int32(refund))
1903			cc.wmu.Lock()
1904			cc.fr.WriteWindowUpdate(0, uint32(refund))
1905			if !didReset {
1906				cs.inflow.add(int32(refund))
1907				cc.fr.WriteWindowUpdate(cs.ID, uint32(refund))
1908			}
1909			cc.bw.Flush()
1910			cc.wmu.Unlock()
1911		}
1912		cc.mu.Unlock()
1913
1914		if len(data) > 0 && !didReset {
1915			if _, err := cs.bufPipe.Write(data); err != nil {
1916				rl.endStreamError(cs, err)
1917				return err
1918			}
1919		}
1920	}
1921
1922	if f.StreamEnded() {
1923		rl.endStream(cs)
1924	}
1925	return nil
1926}
1927
1928var errInvalidTrailers = errors.New("http2: invalid trailers")
1929
1930func (rl *clientConnReadLoop) endStream(cs *clientStream) {
1931	// TODO: check that any declared content-length matches, like
1932	// server.go's (*stream).endStream method.
1933	rl.endStreamError(cs, nil)
1934}
1935
1936func (rl *clientConnReadLoop) endStreamError(cs *clientStream, err error) {
1937	var code func()
1938	if err == nil {
1939		err = io.EOF
1940		code = cs.copyTrailers
1941	}
1942	if isConnectionCloseRequest(cs.req) {
1943		rl.closeWhenIdle = true
1944	}
1945	cs.bufPipe.closeWithErrorAndCode(err, code)
1946
1947	select {
1948	case cs.resc <- resAndError{err: err}:
1949	default:
1950	}
1951}
1952
1953func (cs *clientStream) copyTrailers() {
1954	for k, vv := range cs.trailer {
1955		t := cs.resTrailer
1956		if *t == nil {
1957			*t = make(http.Header)
1958		}
1959		(*t)[k] = vv
1960	}
1961}
1962
1963func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error {
1964	cc := rl.cc
1965	cc.t.connPool().MarkDead(cc)
1966	if f.ErrCode != 0 {
1967		// TODO: deal with GOAWAY more. particularly the error code
1968		cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
1969	}
1970	cc.setGoAway(f)
1971	return nil
1972}
1973
1974func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error {
1975	cc := rl.cc
1976	cc.mu.Lock()
1977	defer cc.mu.Unlock()
1978
1979	if f.IsAck() {
1980		if cc.wantSettingsAck {
1981			cc.wantSettingsAck = false
1982			return nil
1983		}
1984		return ConnectionError(ErrCodeProtocol)
1985	}
1986
1987	err := f.ForeachSetting(func(s Setting) error {
1988		switch s.ID {
1989		case SettingMaxFrameSize:
1990			cc.maxFrameSize = s.Val
1991		case SettingMaxConcurrentStreams:
1992			cc.maxConcurrentStreams = s.Val
1993		case SettingMaxHeaderListSize:
1994			cc.peerMaxHeaderListSize = uint64(s.Val)
1995		case SettingInitialWindowSize:
1996			// Values above the maximum flow-control
1997			// window size of 2^31-1 MUST be treated as a
1998			// connection error (Section 5.4.1) of type
1999			// FLOW_CONTROL_ERROR.
2000			if s.Val > math.MaxInt32 {
2001				return ConnectionError(ErrCodeFlowControl)
2002			}
2003
2004			// Adjust flow control of currently-open
2005			// frames by the difference of the old initial
2006			// window size and this one.
2007			delta := int32(s.Val) - int32(cc.initialWindowSize)
2008			for _, cs := range cc.streams {
2009				cs.flow.add(delta)
2010			}
2011			cc.cond.Broadcast()
2012
2013			cc.initialWindowSize = s.Val
2014		default:
2015			// TODO(bradfitz): handle more settings? SETTINGS_HEADER_TABLE_SIZE probably.
2016			cc.vlogf("Unhandled Setting: %v", s)
2017		}
2018		return nil
2019	})
2020	if err != nil {
2021		return err
2022	}
2023
2024	cc.wmu.Lock()
2025	defer cc.wmu.Unlock()
2026
2027	cc.fr.WriteSettingsAck()
2028	cc.bw.Flush()
2029	return cc.werr
2030}
2031
2032func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error {
2033	cc := rl.cc
2034	cs := cc.streamByID(f.StreamID, false)
2035	if f.StreamID != 0 && cs == nil {
2036		return nil
2037	}
2038
2039	cc.mu.Lock()
2040	defer cc.mu.Unlock()
2041
2042	fl := &cc.flow
2043	if cs != nil {
2044		fl = &cs.flow
2045	}
2046	if !fl.add(int32(f.Increment)) {
2047		return ConnectionError(ErrCodeFlowControl)
2048	}
2049	cc.cond.Broadcast()
2050	return nil
2051}
2052
2053func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error {
2054	cs := rl.cc.streamByID(f.StreamID, true)
2055	if cs == nil {
2056		// TODO: return error if server tries to RST_STEAM an idle stream
2057		return nil
2058	}
2059	select {
2060	case <-cs.peerReset:
2061		// Already reset.
2062		// This is the only goroutine
2063		// which closes this, so there
2064		// isn't a race.
2065	default:
2066		err := streamError(cs.ID, f.ErrCode)
2067		cs.resetErr = err
2068		close(cs.peerReset)
2069		cs.bufPipe.CloseWithError(err)
2070		cs.cc.cond.Broadcast() // wake up checkResetOrDone via clientStream.awaitFlowControl
2071	}
2072	return nil
2073}
2074
2075// Ping sends a PING frame to the server and waits for the ack.
2076// Public implementation is in go17.go and not_go17.go
2077func (cc *ClientConn) ping(ctx contextContext) error {
2078	c := make(chan struct{})
2079	// Generate a random payload
2080	var p [8]byte
2081	for {
2082		if _, err := rand.Read(p[:]); err != nil {
2083			return err
2084		}
2085		cc.mu.Lock()
2086		// check for dup before insert
2087		if _, found := cc.pings[p]; !found {
2088			cc.pings[p] = c
2089			cc.mu.Unlock()
2090			break
2091		}
2092		cc.mu.Unlock()
2093	}
2094	cc.wmu.Lock()
2095	if err := cc.fr.WritePing(false, p); err != nil {
2096		cc.wmu.Unlock()
2097		return err
2098	}
2099	if err := cc.bw.Flush(); err != nil {
2100		cc.wmu.Unlock()
2101		return err
2102	}
2103	cc.wmu.Unlock()
2104	select {
2105	case <-c:
2106		return nil
2107	case <-ctx.Done():
2108		return ctx.Err()
2109	case <-cc.readerDone:
2110		// connection closed
2111		return cc.readerErr
2112	}
2113}
2114
2115func (rl *clientConnReadLoop) processPing(f *PingFrame) error {
2116	if f.IsAck() {
2117		cc := rl.cc
2118		cc.mu.Lock()
2119		defer cc.mu.Unlock()
2120		// If ack, notify listener if any
2121		if c, ok := cc.pings[f.Data]; ok {
2122			close(c)
2123			delete(cc.pings, f.Data)
2124		}
2125		return nil
2126	}
2127	cc := rl.cc
2128	cc.wmu.Lock()
2129	defer cc.wmu.Unlock()
2130	if err := cc.fr.WritePing(true, f.Data); err != nil {
2131		return err
2132	}
2133	return cc.bw.Flush()
2134}
2135
2136func (rl *clientConnReadLoop) processPushPromise(f *PushPromiseFrame) error {
2137	// We told the peer we don't want them.
2138	// Spec says:
2139	// "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH
2140	// setting of the peer endpoint is set to 0. An endpoint that
2141	// has set this setting and has received acknowledgement MUST
2142	// treat the receipt of a PUSH_PROMISE frame as a connection
2143	// error (Section 5.4.1) of type PROTOCOL_ERROR."
2144	return ConnectionError(ErrCodeProtocol)
2145}
2146
2147func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) {
2148	// TODO: map err to more interesting error codes, once the
2149	// HTTP community comes up with some. But currently for
2150	// RST_STREAM there's no equivalent to GOAWAY frame's debug
2151	// data, and the error codes are all pretty vague ("cancel").
2152	cc.wmu.Lock()
2153	cc.fr.WriteRSTStream(streamID, code)
2154	cc.bw.Flush()
2155	cc.wmu.Unlock()
2156}
2157
2158var (
2159	errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
2160	errRequestHeaderListSize  = errors.New("http2: request header list larger than peer's advertised limit")
2161	errPseudoTrailers         = errors.New("http2: invalid pseudo header in trailers")
2162)
2163
2164func (cc *ClientConn) logf(format string, args ...interface{}) {
2165	cc.t.logf(format, args...)
2166}
2167
2168func (cc *ClientConn) vlogf(format string, args ...interface{}) {
2169	cc.t.vlogf(format, args...)
2170}
2171
2172func (t *Transport) vlogf(format string, args ...interface{}) {
2173	if VerboseLogs {
2174		t.logf(format, args...)
2175	}
2176}
2177
2178func (t *Transport) logf(format string, args ...interface{}) {
2179	log.Printf(format, args...)
2180}
2181
2182var noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
2183
2184func strSliceContains(ss []string, s string) bool {
2185	for _, v := range ss {
2186		if v == s {
2187			return true
2188		}
2189	}
2190	return false
2191}
2192
2193type erringRoundTripper struct{ err error }
2194
2195func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err }
2196
2197// gzipReader wraps a response body so it can lazily
2198// call gzip.NewReader on the first call to Read
2199type gzipReader struct {
2200	body io.ReadCloser // underlying Response.Body
2201	zr   *gzip.Reader  // lazily-initialized gzip reader
2202	zerr error         // sticky error
2203}
2204
2205func (gz *gzipReader) Read(p []byte) (n int, err error) {
2206	if gz.zerr != nil {
2207		return 0, gz.zerr
2208	}
2209	if gz.zr == nil {
2210		gz.zr, err = gzip.NewReader(gz.body)
2211		if err != nil {
2212			gz.zerr = err
2213			return 0, err
2214		}
2215	}
2216	return gz.zr.Read(p)
2217}
2218
2219func (gz *gzipReader) Close() error {
2220	return gz.body.Close()
2221}
2222
2223type errorReader struct{ err error }
2224
2225func (r errorReader) Read(p []byte) (int, error) { return 0, r.err }
2226
2227// bodyWriterState encapsulates various state around the Transport's writing
2228// of the request body, particularly regarding doing delayed writes of the body
2229// when the request contains "Expect: 100-continue".
2230type bodyWriterState struct {
2231	cs     *clientStream
2232	timer  *time.Timer   // if non-nil, we're doing a delayed write
2233	fnonce *sync.Once    // to call fn with
2234	fn     func()        // the code to run in the goroutine, writing the body
2235	resc   chan error    // result of fn's execution
2236	delay  time.Duration // how long we should delay a delayed write for
2237}
2238
2239func (t *Transport) getBodyWriterState(cs *clientStream, body io.Reader) (s bodyWriterState) {
2240	s.cs = cs
2241	if body == nil {
2242		return
2243	}
2244	resc := make(chan error, 1)
2245	s.resc = resc
2246	s.fn = func() {
2247		cs.cc.mu.Lock()
2248		cs.startedWrite = true
2249		cs.cc.mu.Unlock()
2250		resc <- cs.writeRequestBody(body, cs.req.Body)
2251	}
2252	s.delay = t.expectContinueTimeout()
2253	if s.delay == 0 ||
2254		!httpguts.HeaderValuesContainsToken(
2255			cs.req.Header["Expect"],
2256			"100-continue") {
2257		return
2258	}
2259	s.fnonce = new(sync.Once)
2260
2261	// Arm the timer with a very large duration, which we'll
2262	// intentionally lower later. It has to be large now because
2263	// we need a handle to it before writing the headers, but the
2264	// s.delay value is defined to not start until after the
2265	// request headers were written.
2266	const hugeDuration = 365 * 24 * time.Hour
2267	s.timer = time.AfterFunc(hugeDuration, func() {
2268		s.fnonce.Do(s.fn)
2269	})
2270	return
2271}
2272
2273func (s bodyWriterState) cancel() {
2274	if s.timer != nil {
2275		s.timer.Stop()
2276	}
2277}
2278
2279func (s bodyWriterState) on100() {
2280	if s.timer == nil {
2281		// If we didn't do a delayed write, ignore the server's
2282		// bogus 100 continue response.
2283		return
2284	}
2285	s.timer.Stop()
2286	go func() { s.fnonce.Do(s.fn) }()
2287}
2288
2289// scheduleBodyWrite starts writing the body, either immediately (in
2290// the common case) or after the delay timeout. It should not be
2291// called until after the headers have been written.
2292func (s bodyWriterState) scheduleBodyWrite() {
2293	if s.timer == nil {
2294		// We're not doing a delayed write (see
2295		// getBodyWriterState), so just start the writing
2296		// goroutine immediately.
2297		go s.fn()
2298		return
2299	}
2300	traceWait100Continue(s.cs.trace)
2301	if s.timer.Stop() {
2302		s.timer.Reset(s.delay)
2303	}
2304}
2305
2306// isConnectionCloseRequest reports whether req should use its own
2307// connection for a single request and then close the connection.
2308func isConnectionCloseRequest(req *http.Request) bool {
2309	return req.Close || httpguts.HeaderValuesContainsToken(req.Header["Connection"], "close")
2310}
2311