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.
33 "golang.org/x/net/http/httpguts"
34 "golang.org/x/net/http2/hpack"
35 "golang.org/x/net/idna"
39 // transportDefaultConnFlow is how many connection-level flow control
40 // tokens we give the server at start-up, past the default 64k.
41 transportDefaultConnFlow = 1 << 30
43 // transportDefaultStreamFlow is how many stream-level flow
44 // control tokens we announce to the peer, and how many bytes
45 // we buffer per stream.
46 transportDefaultStreamFlow = 4 << 20
48 // transportDefaultStreamMinRefresh is the minimum number of bytes we'll send
49 // a stream-level WINDOW_UPDATE for at a time.
50 transportDefaultStreamMinRefresh = 4 << 10
52 defaultUserAgent = "Go-http-client/2.0"
55 // Transport is an HTTP/2 Transport.
57 // A Transport internally caches connections to servers. It is safe
58 // for concurrent use by multiple goroutines.
59 type Transport struct {
60 // DialTLS specifies an optional dial function for creating
61 // TLS connections for requests.
63 // If DialTLS is nil, tls.Dial is used.
65 // If the returned net.Conn has a ConnectionState method like tls.Conn,
66 // it will be used to set http.Response.TLS.
67 DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error)
69 // TLSClientConfig specifies the TLS configuration to use with
70 // tls.Client. If nil, the default configuration is used.
71 TLSClientConfig *tls.Config
73 // ConnPool optionally specifies an alternate connection pool to use.
74 // If nil, the default is used.
75 ConnPool ClientConnPool
77 // DisableCompression, if true, prevents the Transport from
78 // requesting compression with an "Accept-Encoding: gzip"
79 // request header when the Request contains no existing
80 // Accept-Encoding value. If the Transport requests gzip on
81 // its own and gets a gzipped response, it's transparently
82 // decoded in the Response.Body. However, if the user
83 // explicitly requested gzip it is not automatically
85 DisableCompression bool
87 // AllowHTTP, if true, permits HTTP/2 requests using the insecure,
88 // plain-text "http" scheme. Note that this does not enable h2c support.
91 // MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
92 // send in the initial settings frame. It is how many bytes
93 // of response headers are allowed. Unlike the http2 spec, zero here
94 // means to use a default limit (currently 10MB). If you actually
95 // want to advertise an ulimited value to the peer, Transport
96 // interprets the highest possible value here (0xffffffff or 1<<32-1)
98 MaxHeaderListSize uint32
100 // StrictMaxConcurrentStreams controls whether the server's
101 // SETTINGS_MAX_CONCURRENT_STREAMS should be respected
102 // globally. If false, new TCP connections are created to the
103 // server as needed to keep each under the per-connection
104 // SETTINGS_MAX_CONCURRENT_STREAMS limit. If true, the
105 // server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as
106 // a global limit and callers of RoundTrip block when needed,
107 // waiting for their turn.
108 StrictMaxConcurrentStreams bool
110 // t1, if non-nil, is the standard library Transport using
111 // this transport. Its settings are used (but not its
112 // RoundTrip method, etc).
115 connPoolOnce sync.Once
116 connPoolOrDef ClientConnPool // non-nil version of ConnPool
119 func (t *Transport) maxHeaderListSize() uint32 {
120 if t.MaxHeaderListSize == 0 {
123 if t.MaxHeaderListSize == 0xffffffff {
126 return t.MaxHeaderListSize
129 func (t *Transport) disableCompression() bool {
130 return t.DisableCompression || (t.t1 != nil && t.t1.DisableCompression)
133 // ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2.
134 // It returns an error if t1 has already been HTTP/2-enabled.
135 func ConfigureTransport(t1 *http.Transport) error {
136 _, err := configureTransport(t1)
140 func configureTransport(t1 *http.Transport) (*Transport, error) {
141 connPool := new(clientConnPool)
143 ConnPool: noDialClientConnPool{connPool},
147 if err := registerHTTPSProtocol(t1, noDialH2RoundTripper{t2}); err != nil {
150 if t1.TLSClientConfig == nil {
151 t1.TLSClientConfig = new(tls.Config)
153 if !strSliceContains(t1.TLSClientConfig.NextProtos, "h2") {
154 t1.TLSClientConfig.NextProtos = append([]string{"h2"}, t1.TLSClientConfig.NextProtos...)
156 if !strSliceContains(t1.TLSClientConfig.NextProtos, "http/1.1") {
157 t1.TLSClientConfig.NextProtos = append(t1.TLSClientConfig.NextProtos, "http/1.1")
159 upgradeFn := func(authority string, c *tls.Conn) http.RoundTripper {
160 addr := authorityAddr("https", authority)
161 if used, err := connPool.addConnIfNeeded(addr, t2, c); err != nil {
163 return erringRoundTripper{err}
165 // Turns out we don't need this c.
166 // For example, two goroutines made requests to the same host
167 // at the same time, both kicking off TCP dials. (since protocol
173 if m := t1.TLSNextProto; len(m) == 0 {
174 t1.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{
183 func (t *Transport) connPool() ClientConnPool {
184 t.connPoolOnce.Do(t.initConnPool)
185 return t.connPoolOrDef
188 func (t *Transport) initConnPool() {
189 if t.ConnPool != nil {
190 t.connPoolOrDef = t.ConnPool
192 t.connPoolOrDef = &clientConnPool{t: t}
196 // ClientConn is the state of a single HTTP/2 client connection to an
198 type ClientConn struct {
200 tconn net.Conn // usually *tls.Conn, except specialized impls
201 tlsState *tls.ConnectionState // nil only for specialized impls
202 singleUse bool // whether being used for a single http.Request
204 // readLoop goroutine fields:
205 readerDone chan struct{} // closed on error
206 readerErr error // set before readerDone is closed
208 idleTimeout time.Duration // or 0 for never
209 idleTimer *time.Timer
211 mu sync.Mutex // guards following
212 cond *sync.Cond // hold mu; broadcast on flow/closed changes
213 flow flow // our conn-level flow control quota (cs.flow is per stream)
214 inflow flow // peer's conn-level flow control
217 wantSettingsAck bool // we sent a SETTINGS frame and haven't heard back
218 goAway *GoAwayFrame // if non-nil, the GoAwayFrame we received
219 goAwayDebug string // goAway frame's debug data, retained as a string
220 streams map[uint32]*clientStream // client-initiated
222 pendingRequests int // requests blocked and waiting to be sent because len(streams) == maxConcurrentStreams
223 pings map[[8]byte]chan struct{} // in flight ping data to notification channel
228 // Settings from peer: (also guarded by mu)
230 maxConcurrentStreams uint32
231 peerMaxHeaderListSize uint64
232 initialWindowSize uint32
234 hbuf bytes.Buffer // HPACK encoder writes into this
238 wmu sync.Mutex // held while writing; acquire AFTER mu if holding both
239 werr error // first write error that has occurred
242 // clientStream is the state for a single HTTP/2 stream. One of these
243 // is created for each Transport.RoundTrip call.
244 type clientStream struct {
247 trace *httptrace.ClientTrace // or nil
249 resc chan resAndError
250 bufPipe pipe // buffered pipe with the flow-controlled response payload
251 startedWrite bool // started request body write; guarded by cc.mu
253 on100 func() // optional code to run if get a 100 continue response
255 flow flow // guarded by cc.mu
256 inflow flow // guarded by cc.mu
257 bytesRemain int64 // -1 means unknown; owned by transportResponseBody.Read
258 readErr error // sticky read error; owned by transportResponseBody.Read
259 stopReqBody error // if non-nil, stop writing req body; guarded by cc.mu
260 didReset bool // whether we sent a RST_STREAM to the server; guarded by cc.mu
262 peerReset chan struct{} // closed on peer reset
263 resetErr error // populated before peerReset is closed
265 done chan struct{} // closed when stream remove from cc.streams map; close calls guarded by cc.mu
267 // owned by clientConnReadLoop:
268 firstByte bool // got the first response byte
269 pastHeaders bool // got first MetaHeadersFrame (actual headers)
270 pastTrailers bool // got optional second MetaHeadersFrame (trailers)
271 num1xx uint8 // number of 1xx responses seen
273 trailer http.Header // accumulated trailers
274 resTrailer *http.Header // client's Response.Trailer
277 // awaitRequestCancel waits for the user to cancel a request or for the done
278 // channel to be signaled. A non-nil error is returned only if the request was
280 func awaitRequestCancel(req *http.Request, done <-chan struct{}) error {
282 if req.Cancel == nil && ctx.Done() == nil {
287 return errRequestCanceled
295 var got1xxFuncForTests func(int, textproto.MIMEHeader) error
297 // get1xxTraceFunc returns the value of request's httptrace.ClientTrace.Got1xxResponse func,
298 // if any. It returns nil if not set or if the Go version is too old.
299 func (cs *clientStream) get1xxTraceFunc() func(int, textproto.MIMEHeader) error {
300 if fn := got1xxFuncForTests; fn != nil {
303 return traceGot1xxResponseFunc(cs.trace)
306 // awaitRequestCancel waits for the user to cancel a request, its context to
307 // expire, or for the request to be done (any way it might be removed from the
308 // cc.streams map: peer reset, successful completion, TCP connection breakage,
309 // etc). If the request is canceled, then cs will be canceled and closed.
310 func (cs *clientStream) awaitRequestCancel(req *http.Request) {
311 if err := awaitRequestCancel(req, cs.done); err != nil {
313 cs.bufPipe.CloseWithError(err)
317 func (cs *clientStream) cancelStream() {
320 didReset := cs.didReset
325 cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
326 cc.forgetStreamID(cs.ID)
330 // checkResetOrDone reports any error sent in a RST_STREAM frame by the
331 // server, or errStreamClosed if the stream is complete.
332 func (cs *clientStream) checkResetOrDone() error {
337 return errStreamClosed
343 func (cs *clientStream) getStartedWrite() bool {
347 return cs.startedWrite
350 func (cs *clientStream) abortRequestBodyWrite(err error) {
361 type stickyErrWriter struct {
366 func (sew stickyErrWriter) Write(p []byte) (n int, err error) {
370 n, err = sew.w.Write(p)
375 // noCachedConnError is the concrete type of ErrNoCachedConn, which
376 // needs to be detected by net/http regardless of whether it's its
377 // bundled version (in h2_bundle.go with a rewritten type name) or
378 // from a user's x/net/http2. As such, as it has a unique method name
379 // (IsHTTP2NoCachedConnError) that net/http sniffs for via func
380 // isNoCachedConnError.
381 type noCachedConnError struct{}
383 func (noCachedConnError) IsHTTP2NoCachedConnError() {}
384 func (noCachedConnError) Error() string { return "http2: no cached connection was available" }
386 // isNoCachedConnError reports whether err is of type noCachedConnError
387 // or its equivalent renamed type in net/http2's h2_bundle.go. Both types
388 // may coexist in the same running program.
389 func isNoCachedConnError(err error) bool {
390 _, ok := err.(interface{ IsHTTP2NoCachedConnError() })
394 var ErrNoCachedConn error = noCachedConnError{}
396 // RoundTripOpt are options for the Transport.RoundTripOpt method.
397 type RoundTripOpt struct {
398 // OnlyCachedConn controls whether RoundTripOpt may
399 // create a new TCP connection. If set true and
400 // no cached connection is available, RoundTripOpt
401 // will return ErrNoCachedConn.
405 func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
406 return t.RoundTripOpt(req, RoundTripOpt{})
409 // authorityAddr returns a given authority (a host/IP, or host:port / ip:port)
410 // and returns a host:port. The port 443 is added if needed.
411 func authorityAddr(scheme string, authority string) (addr string) {
412 host, port, err := net.SplitHostPort(authority)
413 if err != nil { // authority didn't have a port
415 if scheme == "http" {
420 if a, err := idna.ToASCII(host); err == nil {
423 // IPv6 address literal, without a port:
424 if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
425 return host + ":" + port
427 return net.JoinHostPort(host, port)
430 // RoundTripOpt is like RoundTrip, but takes options.
431 func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) {
432 if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) {
433 return nil, errors.New("http2: unsupported scheme")
436 addr := authorityAddr(req.URL.Scheme, req.URL.Host)
437 for retry := 0; ; retry++ {
438 cc, err := t.connPool().GetClientConn(req, addr)
440 t.vlogf("http2: Transport failed to get client conn for %s: %v", addr, err)
443 traceGotConn(req, cc)
444 res, gotErrAfterReqBodyWrite, err := cc.roundTrip(req)
445 if err != nil && retry <= 6 {
446 if req, err = shouldRetryRequest(req, err, gotErrAfterReqBodyWrite); err == nil {
447 // After the first retry, do exponential backoff with 10% jitter.
451 backoff := float64(uint(1) << (uint(retry) - 1))
452 backoff += backoff * (0.1 * mathrand.Float64())
454 case <-time.After(time.Second * time.Duration(backoff)):
456 case <-req.Context().Done():
457 return nil, req.Context().Err()
462 t.vlogf("RoundTrip failure: %v", err)
469 // CloseIdleConnections closes any connections which were previously
470 // connected from previous requests but are now sitting idle.
471 // It does not interrupt any connections currently in use.
472 func (t *Transport) CloseIdleConnections() {
473 if cp, ok := t.connPool().(clientConnPoolIdleCloser); ok {
474 cp.closeIdleConnections()
479 errClientConnClosed = errors.New("http2: client conn is closed")
480 errClientConnUnusable = errors.New("http2: client conn not usable")
481 errClientConnGotGoAway = errors.New("http2: Transport received Server's graceful shutdown GOAWAY")
484 // shouldRetryRequest is called by RoundTrip when a request fails to get
485 // response headers. It is always called with a non-nil error.
486 // It returns either a request to retry (either the same request, or a
487 // modified clone), or an error if the request can't be replayed.
488 func shouldRetryRequest(req *http.Request, err error, afterBodyWrite bool) (*http.Request, error) {
489 if !canRetryError(err) {
492 // If the Body is nil (or http.NoBody), it's safe to reuse
493 // this request and its Body.
494 if req.Body == nil || req.Body == http.NoBody {
498 // If the request body can be reset back to its original
499 // state via the optional req.GetBody, do that.
500 if req.GetBody != nil {
501 // TODO: consider a req.Body.Close here? or audit that all caller paths do?
502 body, err := req.GetBody()
511 // The Request.Body can't reset back to the beginning, but we
512 // don't seem to have started to read from it yet, so reuse
513 // the request directly. The "afterBodyWrite" means the
514 // bodyWrite process has started, which becomes true before
520 return nil, fmt.Errorf("http2: Transport: cannot retry err [%v] after Request.Body was written; define Request.GetBody to avoid this error", err)
523 func canRetryError(err error) bool {
524 if err == errClientConnUnusable || err == errClientConnGotGoAway {
527 if se, ok := err.(StreamError); ok {
528 return se.Code == ErrCodeRefusedStream
533 func (t *Transport) dialClientConn(addr string, singleUse bool) (*ClientConn, error) {
534 host, _, err := net.SplitHostPort(addr)
538 tconn, err := t.dialTLS()("tcp", addr, t.newTLSConfig(host))
542 return t.newClientConn(tconn, singleUse)
545 func (t *Transport) newTLSConfig(host string) *tls.Config {
546 cfg := new(tls.Config)
547 if t.TLSClientConfig != nil {
548 *cfg = *t.TLSClientConfig.Clone()
550 if !strSliceContains(cfg.NextProtos, NextProtoTLS) {
551 cfg.NextProtos = append([]string{NextProtoTLS}, cfg.NextProtos...)
553 if cfg.ServerName == "" {
554 cfg.ServerName = host
559 func (t *Transport) dialTLS() func(string, string, *tls.Config) (net.Conn, error) {
560 if t.DialTLS != nil {
563 return t.dialTLSDefault
566 func (t *Transport) dialTLSDefault(network, addr string, cfg *tls.Config) (net.Conn, error) {
567 cn, err := tls.Dial(network, addr, cfg)
571 if err := cn.Handshake(); err != nil {
574 if !cfg.InsecureSkipVerify {
575 if err := cn.VerifyHostname(cfg.ServerName); err != nil {
579 state := cn.ConnectionState()
580 if p := state.NegotiatedProtocol; p != NextProtoTLS {
581 return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, NextProtoTLS)
583 if !state.NegotiatedProtocolIsMutual {
584 return nil, errors.New("http2: could not negotiate protocol mutually")
589 // disableKeepAlives reports whether connections should be closed as
590 // soon as possible after handling the first request.
591 func (t *Transport) disableKeepAlives() bool {
592 return t.t1 != nil && t.t1.DisableKeepAlives
595 func (t *Transport) expectContinueTimeout() time.Duration {
599 return t.t1.ExpectContinueTimeout
602 func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) {
603 return t.newClientConn(c, false)
606 func (t *Transport) newClientConn(c net.Conn, singleUse bool) (*ClientConn, error) {
610 readerDone: make(chan struct{}),
612 maxFrameSize: 16 << 10, // spec default
613 initialWindowSize: 65535, // spec default
614 maxConcurrentStreams: 1000, // "infinite", per spec. 1000 seems good enough.
615 peerMaxHeaderListSize: 0xffffffffffffffff, // "infinite", per spec. Use 2^64-1 instead.
616 streams: make(map[uint32]*clientStream),
617 singleUse: singleUse,
618 wantSettingsAck: true,
619 pings: make(map[[8]byte]chan struct{}),
621 if d := t.idleConnTimeout(); d != 0 {
623 cc.idleTimer = time.AfterFunc(d, cc.onIdleTimeout)
626 t.vlogf("http2: Transport creating client conn %p to %v", cc, c.RemoteAddr())
629 cc.cond = sync.NewCond(&cc.mu)
630 cc.flow.add(int32(initialWindowSize))
632 // TODO: adjust this writer size to account for frame size +
633 // MTU + crypto/tls record padding.
634 cc.bw = bufio.NewWriter(stickyErrWriter{c, &cc.werr})
635 cc.br = bufio.NewReader(c)
636 cc.fr = NewFramer(cc.bw, cc.br)
637 cc.fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil)
638 cc.fr.MaxHeaderListSize = t.maxHeaderListSize()
640 // TODO: SetMaxDynamicTableSize, SetMaxDynamicTableSizeLimit on
641 // henc in response to SETTINGS frames?
642 cc.henc = hpack.NewEncoder(&cc.hbuf)
648 if cs, ok := c.(connectionStater); ok {
649 state := cs.ConnectionState()
653 initialSettings := []Setting{
654 {ID: SettingEnablePush, Val: 0},
655 {ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow},
657 if max := t.maxHeaderListSize(); max != 0 {
658 initialSettings = append(initialSettings, Setting{ID: SettingMaxHeaderListSize, Val: max})
661 cc.bw.Write(clientPreface)
662 cc.fr.WriteSettings(initialSettings...)
663 cc.fr.WriteWindowUpdate(0, transportDefaultConnFlow)
664 cc.inflow.add(transportDefaultConnFlow + initialWindowSize)
674 func (cc *ClientConn) setGoAway(f *GoAwayFrame) {
681 // Merge the previous and current GoAway error frames.
682 if cc.goAwayDebug == "" {
683 cc.goAwayDebug = string(f.DebugData())
685 if old != nil && old.ErrCode != ErrCodeNo {
686 cc.goAway.ErrCode = old.ErrCode
688 last := f.LastStreamID
689 for streamID, cs := range cc.streams {
692 case cs.resc <- resAndError{err: errClientConnGotGoAway}:
699 // CanTakeNewRequest reports whether the connection can take a new request,
700 // meaning it has not been closed or received or sent a GOAWAY.
701 func (cc *ClientConn) CanTakeNewRequest() bool {
704 return cc.canTakeNewRequestLocked()
707 // clientConnIdleState describes the suitability of a client
708 // connection to initiate a new RoundTrip request.
709 type clientConnIdleState struct {
710 canTakeNewRequest bool
711 freshConn bool // whether it's unused by any previous request
714 func (cc *ClientConn) idleState() clientConnIdleState {
717 return cc.idleStateLocked()
720 func (cc *ClientConn) idleStateLocked() (st clientConnIdleState) {
721 if cc.singleUse && cc.nextStreamID > 1 {
724 var maxConcurrentOkay bool
725 if cc.t.StrictMaxConcurrentStreams {
726 // We'll tell the caller we can take a new request to
727 // prevent the caller from dialing a new TCP
728 // connection, but then we'll block later before
730 maxConcurrentOkay = true
732 maxConcurrentOkay = int64(len(cc.streams)+1) < int64(cc.maxConcurrentStreams)
735 st.canTakeNewRequest = cc.goAway == nil && !cc.closed && !cc.closing && maxConcurrentOkay &&
736 int64(cc.nextStreamID)+2*int64(cc.pendingRequests) < math.MaxInt32
737 st.freshConn = cc.nextStreamID == 1 && st.canTakeNewRequest
741 func (cc *ClientConn) canTakeNewRequestLocked() bool {
742 st := cc.idleStateLocked()
743 return st.canTakeNewRequest
746 // onIdleTimeout is called from a time.AfterFunc goroutine. It will
747 // only be called when we're idle, but because we're coming from a new
748 // goroutine, there could be a new request coming in at the same time,
749 // so this simply calls the synchronized closeIfIdle to shut down this
750 // connection. The timer could just call closeIfIdle, but this is more
752 func (cc *ClientConn) onIdleTimeout() {
756 func (cc *ClientConn) closeIfIdle() {
758 if len(cc.streams) > 0 {
763 nextID := cc.nextStreamID
764 // TODO: do clients send GOAWAY too? maybe? Just Close:
768 cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, nextID-2)
773 var shutdownEnterWaitStateHook = func() {}
775 // Shutdown gracefully close the client connection, waiting for running streams to complete.
776 func (cc *ClientConn) Shutdown(ctx context.Context) error {
777 if err := cc.sendGoAway(); err != nil {
780 // Wait for all in-flight streams to complete or connection to close
781 done := make(chan error, 1)
782 cancelled := false // guarded by cc.mu
787 if len(cc.streams) == 0 || cc.closed {
789 done <- cc.tconn.Close()
798 shutdownEnterWaitStateHook()
804 // Free the goroutine above
812 func (cc *ClientConn) sendGoAway() error {
816 defer cc.wmu.Unlock()
818 // GOAWAY sent already
821 // Send a graceful shutdown frame to server
822 maxStreamID := cc.nextStreamID
823 if err := cc.fr.WriteGoAway(maxStreamID, ErrCodeNo, nil); err != nil {
826 if err := cc.bw.Flush(); err != nil {
829 // Prevent new requests
834 // Close closes the client connection immediately.
836 // In-flight requests are interrupted. For a graceful shutdown, use Shutdown instead.
837 func (cc *ClientConn) Close() error {
839 defer cc.cond.Broadcast()
841 err := errors.New("http2: client connection force closed via ClientConn.Close")
842 for id, cs := range cc.streams {
844 case cs.resc <- resAndError{err: err}:
847 cs.bufPipe.CloseWithError(err)
848 delete(cc.streams, id)
851 return cc.tconn.Close()
854 const maxAllocFrameSize = 512 << 10
856 // frameBuffer returns a scratch buffer suitable for writing DATA frames.
857 // They're capped at the min of the peer's max frame size or 512KB
858 // (kinda arbitrarily), but definitely capped so we don't allocate 4GB
860 func (cc *ClientConn) frameScratchBuffer() []byte {
862 size := cc.maxFrameSize
863 if size > maxAllocFrameSize {
864 size = maxAllocFrameSize
866 for i, buf := range cc.freeBuf {
867 if len(buf) >= int(size) {
874 return make([]byte, size)
877 func (cc *ClientConn) putFrameScratchBuffer(buf []byte) {
880 const maxBufs = 4 // arbitrary; 4 concurrent requests per conn? investigate.
881 if len(cc.freeBuf) < maxBufs {
882 cc.freeBuf = append(cc.freeBuf, buf)
885 for i, old := range cc.freeBuf {
894 // errRequestCanceled is a copy of net/http's errRequestCanceled because it's not
895 // exported. At least they'll be DeepEqual for h1-vs-h2 comparisons tests.
896 var errRequestCanceled = errors.New("net/http: request canceled")
898 func commaSeparatedTrailers(req *http.Request) (string, error) {
899 keys := make([]string, 0, len(req.Trailer))
900 for k := range req.Trailer {
901 k = http.CanonicalHeaderKey(k)
903 case "Transfer-Encoding", "Trailer", "Content-Length":
904 return "", &badStringError{"invalid Trailer key", k}
906 keys = append(keys, k)
910 return strings.Join(keys, ","), nil
915 func (cc *ClientConn) responseHeaderTimeout() time.Duration {
917 return cc.t.t1.ResponseHeaderTimeout
919 // No way to do this (yet?) with just an http2.Transport. Probably
920 // no need. Request.Cancel this is the new way. We only need to support
921 // this for compatibility with the old http.Transport fields when
922 // we're doing transparent http2.
926 // checkConnHeaders checks whether req has any invalid connection-level headers.
927 // per RFC 7540 section 8.1.2.2: Connection-Specific Header Fields.
928 // Certain headers are special-cased as okay but not transmitted later.
929 func checkConnHeaders(req *http.Request) error {
930 if v := req.Header.Get("Upgrade"); v != "" {
931 return fmt.Errorf("http2: invalid Upgrade request header: %q", req.Header["Upgrade"])
933 if vv := req.Header["Transfer-Encoding"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "chunked") {
934 return fmt.Errorf("http2: invalid Transfer-Encoding request header: %q", vv)
936 if vv := req.Header["Connection"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && !strings.EqualFold(vv[0], "close") && !strings.EqualFold(vv[0], "keep-alive")) {
937 return fmt.Errorf("http2: invalid Connection request header: %q", vv)
942 // actualContentLength returns a sanitized version of
943 // req.ContentLength, where 0 actually means zero (not unknown) and -1
945 func actualContentLength(req *http.Request) int64 {
946 if req.Body == nil || req.Body == http.NoBody {
949 if req.ContentLength != 0 {
950 return req.ContentLength
955 func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) {
956 resp, _, err := cc.roundTrip(req)
960 func (cc *ClientConn) roundTrip(req *http.Request) (res *http.Response, gotErrAfterReqBodyWrite bool, err error) {
961 if err := checkConnHeaders(req); err != nil {
962 return nil, false, err
964 if cc.idleTimer != nil {
968 trailers, err := commaSeparatedTrailers(req)
970 return nil, false, err
972 hasTrailers := trailers != ""
975 if err := cc.awaitOpenSlotForRequest(req); err != nil {
977 return nil, false, err
981 contentLen := actualContentLength(req)
982 hasBody := contentLen != 0
984 // TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere?
985 var requestedGzip bool
986 if !cc.t.disableCompression() &&
987 req.Header.Get("Accept-Encoding") == "" &&
988 req.Header.Get("Range") == "" &&
989 req.Method != "HEAD" {
990 // Request gzip only, not deflate. Deflate is ambiguous and
991 // not as universally supported anyway.
992 // See: http://www.gzip.org/zlib/zlib_faq.html#faq38
994 // Note that we don't request this for HEAD requests,
995 // due to a bug in nginx:
996 // http://trac.nginx.org/nginx/ticket/358
997 // https://golang.org/issue/5522
999 // We don't request gzip if the request is for a range, since
1000 // auto-decoding a portion of a gzipped document will just fail
1001 // anyway. See https://golang.org/issue/8923
1002 requestedGzip = true
1005 // we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,} (DATA is
1006 // sent by writeRequestBody below, along with any Trailers,
1007 // again in form HEADERS{1}, CONTINUATION{0,})
1008 hdrs, err := cc.encodeHeaders(req, requestedGzip, trailers, contentLen)
1011 return nil, false, err
1014 cs := cc.newStream()
1016 cs.trace = httptrace.ContextClientTrace(req.Context())
1017 cs.requestedGzip = requestedGzip
1018 bodyWriter := cc.t.getBodyWriterState(cs, body)
1019 cs.on100 = bodyWriter.on100
1022 endStream := !hasBody && !hasTrailers
1023 werr := cc.writeHeaders(cs.ID, endStream, int(cc.maxFrameSize), hdrs)
1025 traceWroteHeaders(cs.trace)
1030 req.Body.Close() // per RoundTripper contract
1033 cc.forgetStreamID(cs.ID)
1034 // Don't bother sending a RST_STREAM (our write already failed;
1035 // no need to keep writing)
1036 traceWroteRequest(cs.trace, werr)
1037 return nil, false, werr
1040 var respHeaderTimer <-chan time.Time
1042 bodyWriter.scheduleBodyWrite()
1044 traceWroteRequest(cs.trace, nil)
1045 if d := cc.responseHeaderTimeout(); d != 0 {
1046 timer := time.NewTimer(d)
1048 respHeaderTimer = timer.C
1052 readLoopResCh := cs.resc
1053 bodyWritten := false
1054 ctx := req.Context()
1056 handleReadLoopResponse := func(re resAndError) (*http.Response, bool, error) {
1058 if re.err != nil || res.StatusCode > 299 {
1059 // On error or status code 3xx, 4xx, 5xx, etc abort any
1060 // ongoing write, assuming that the server doesn't care
1061 // about our request body. If the server replied with 1xx or
1062 // 2xx, however, then assume the server DOES potentially
1063 // want our body (e.g. full-duplex streaming:
1064 // golang.org/issue/13444). If it turns out the server
1065 // doesn't, they'll RST_STREAM us soon enough. This is a
1066 // heuristic to avoid adding knobs to Transport. Hopefully
1069 cs.abortRequestBodyWrite(errStopReqBodyWrite)
1072 cc.forgetStreamID(cs.ID)
1073 return nil, cs.getStartedWrite(), re.err
1076 res.TLS = cc.tlsState
1077 return res, false, nil
1082 case re := <-readLoopResCh:
1083 return handleReadLoopResponse(re)
1084 case <-respHeaderTimer:
1085 if !hasBody || bodyWritten {
1086 cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
1089 cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
1091 cc.forgetStreamID(cs.ID)
1092 return nil, cs.getStartedWrite(), errTimeout
1094 if !hasBody || bodyWritten {
1095 cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
1098 cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
1100 cc.forgetStreamID(cs.ID)
1101 return nil, cs.getStartedWrite(), ctx.Err()
1103 if !hasBody || bodyWritten {
1104 cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
1107 cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
1109 cc.forgetStreamID(cs.ID)
1110 return nil, cs.getStartedWrite(), errRequestCanceled
1111 case <-cs.peerReset:
1112 // processResetStream already removed the
1113 // stream from the streams map; no need for
1115 return nil, cs.getStartedWrite(), cs.resetErr
1116 case err := <-bodyWriter.resc:
1117 // Prefer the read loop's response, if available. Issue 16102.
1119 case re := <-readLoopResCh:
1120 return handleReadLoopResponse(re)
1124 cc.forgetStreamID(cs.ID)
1125 return nil, cs.getStartedWrite(), err
1128 if d := cc.responseHeaderTimeout(); d != 0 {
1129 timer := time.NewTimer(d)
1131 respHeaderTimer = timer.C
1137 // awaitOpenSlotForRequest waits until len(streams) < maxConcurrentStreams.
1139 func (cc *ClientConn) awaitOpenSlotForRequest(req *http.Request) error {
1140 var waitingForConn chan struct{}
1141 var waitingForConnErr error // guarded by cc.mu
1143 cc.lastActive = time.Now()
1144 if cc.closed || !cc.canTakeNewRequestLocked() {
1145 if waitingForConn != nil {
1146 close(waitingForConn)
1148 return errClientConnUnusable
1150 if int64(len(cc.streams))+1 <= int64(cc.maxConcurrentStreams) {
1151 if waitingForConn != nil {
1152 close(waitingForConn)
1156 // Unfortunately, we cannot wait on a condition variable and channel at
1157 // the same time, so instead, we spin up a goroutine to check if the
1158 // request is canceled while we wait for a slot to open in the connection.
1159 if waitingForConn == nil {
1160 waitingForConn = make(chan struct{})
1162 if err := awaitRequestCancel(req, waitingForConn); err != nil {
1164 waitingForConnErr = err
1170 cc.pendingRequests++
1172 cc.pendingRequests--
1173 if waitingForConnErr != nil {
1174 return waitingForConnErr
1179 // requires cc.wmu be held
1180 func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, maxFrameSize int, hdrs []byte) error {
1181 first := true // first frame written (HEADERS is first, then CONTINUATION)
1182 for len(hdrs) > 0 && cc.werr == nil {
1184 if len(chunk) > maxFrameSize {
1185 chunk = chunk[:maxFrameSize]
1187 hdrs = hdrs[len(chunk):]
1188 endHeaders := len(hdrs) == 0
1190 cc.fr.WriteHeaders(HeadersFrameParam{
1192 BlockFragment: chunk,
1193 EndStream: endStream,
1194 EndHeaders: endHeaders,
1198 cc.fr.WriteContinuation(streamID, endHeaders, chunk)
1201 // TODO(bradfitz): this Flush could potentially block (as
1202 // could the WriteHeaders call(s) above), which means they
1203 // wouldn't respond to Request.Cancel being readable. That's
1204 // rare, but this should probably be in a goroutine.
1209 // internal error values; they don't escape to callers
1211 // abort request body write; don't send cancel
1212 errStopReqBodyWrite = errors.New("http2: aborting request body write")
1214 // abort request body write, but send stream reset of cancel.
1215 errStopReqBodyWriteAndCancel = errors.New("http2: canceling request")
1218 func (cs *clientStream) writeRequestBody(body io.Reader, bodyCloser io.Closer) (err error) {
1220 sentEnd := false // whether we sent the final DATA frame w/ END_STREAM
1221 buf := cc.frameScratchBuffer()
1222 defer cc.putFrameScratchBuffer(buf)
1225 traceWroteRequest(cs.trace, err)
1226 // TODO: write h12Compare test showing whether
1227 // Request.Body is closed by the Transport,
1228 // and in multiple cases: server replies <=299 and >299
1229 // while still writing request body
1230 cerr := bodyCloser.Close()
1237 hasTrailers := req.Trailer != nil
1241 n, err := body.Read(buf)
1245 } else if err != nil {
1246 cc.writeStreamReset(cs.ID, ErrCodeCancel, err)
1251 for len(remain) > 0 && err == nil {
1253 allowed, err = cs.awaitFlowControl(len(remain))
1255 case err == errStopReqBodyWrite:
1257 case err == errStopReqBodyWriteAndCancel:
1258 cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
1264 data := remain[:allowed]
1265 remain = remain[allowed:]
1266 sentEnd = sawEOF && len(remain) == 0 && !hasTrailers
1267 err = cc.fr.WriteData(cs.ID, sentEnd, data)
1269 // TODO(bradfitz): this flush is for latency, not bandwidth.
1270 // Most requests won't need this. Make this opt-in or
1271 // opt-out? Use some heuristic on the body type? Nagel-like
1272 // timers? Based on 'n'? Only last chunk of this for loop,
1273 // unless flow control tokens are low? For now, always.
1274 // If we change this, see comment below.
1285 // Already sent END_STREAM (which implies we have no
1286 // trailers) and flushed, because currently all
1287 // WriteData frames above get a flush. So we're done.
1294 trls, err = cc.encodeTrailers(req)
1297 cc.writeStreamReset(cs.ID, ErrCodeInternal, err)
1298 cc.forgetStreamID(cs.ID)
1304 maxFrameSize := int(cc.maxFrameSize)
1308 defer cc.wmu.Unlock()
1310 // Two ways to send END_STREAM: either with trailers, or
1311 // with an empty DATA frame.
1313 err = cc.writeHeaders(cs.ID, true, maxFrameSize, trls)
1315 err = cc.fr.WriteData(cs.ID, true, nil)
1317 if ferr := cc.bw.Flush(); ferr != nil && err == nil {
1323 // awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
1324 // control tokens from the server.
1325 // It returns either the non-zero number of tokens taken or an error
1326 // if the stream is dead.
1327 func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
1330 defer cc.mu.Unlock()
1333 return 0, errClientConnClosed
1335 if cs.stopReqBody != nil {
1336 return 0, cs.stopReqBody
1338 if err := cs.checkResetOrDone(); err != nil {
1341 if a := cs.flow.available(); a > 0 {
1343 if int(take) > maxBytes {
1345 take = int32(maxBytes) // can't truncate int; take is int32
1347 if take > int32(cc.maxFrameSize) {
1348 take = int32(cc.maxFrameSize)
1357 type badStringError struct {
1362 func (e *badStringError) Error() string { return fmt.Sprintf("%s %q", e.what, e.str) }
1364 // requires cc.mu be held.
1365 func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) {
1372 host, err := httpguts.PunycodeHostPort(host)
1378 if req.Method != "CONNECT" {
1379 path = req.URL.RequestURI()
1380 if !validPseudoPath(path) {
1382 path = strings.TrimPrefix(path, req.URL.Scheme+"://"+host)
1383 if !validPseudoPath(path) {
1384 if req.URL.Opaque != "" {
1385 return nil, fmt.Errorf("invalid request :path %q from URL.Opaque = %q", orig, req.URL.Opaque)
1387 return nil, fmt.Errorf("invalid request :path %q", orig)
1393 // Check for any invalid headers and return an error before we
1394 // potentially pollute our hpack state. (We want to be able to
1395 // continue to reuse the hpack encoder for future requests)
1396 for k, vv := range req.Header {
1397 if !httpguts.ValidHeaderFieldName(k) {
1398 return nil, fmt.Errorf("invalid HTTP header name %q", k)
1400 for _, v := range vv {
1401 if !httpguts.ValidHeaderFieldValue(v) {
1402 return nil, fmt.Errorf("invalid HTTP header value %q for header %q", v, k)
1407 enumerateHeaders := func(f func(name, value string)) {
1408 // 8.1.2.3 Request Pseudo-Header Fields
1409 // The :path pseudo-header field includes the path and query parts of the
1410 // target URI (the path-absolute production and optionally a '?' character
1411 // followed by the query production (see Sections 3.3 and 3.4 of
1413 f(":authority", host)
1419 if req.Method != "CONNECT" {
1421 f(":scheme", req.URL.Scheme)
1424 f("trailer", trailers)
1428 for k, vv := range req.Header {
1429 if strings.EqualFold(k, "host") || strings.EqualFold(k, "content-length") {
1430 // Host is :authority, already sent.
1431 // Content-Length is automatic, set below.
1433 } else if strings.EqualFold(k, "connection") || strings.EqualFold(k, "proxy-connection") ||
1434 strings.EqualFold(k, "transfer-encoding") || strings.EqualFold(k, "upgrade") ||
1435 strings.EqualFold(k, "keep-alive") {
1436 // Per 8.1.2.2 Connection-Specific Header
1437 // Fields, don't send connection-specific
1438 // fields. We have already checked if any
1439 // are error-worthy so just ignore the rest.
1441 } else if strings.EqualFold(k, "user-agent") {
1442 // Match Go's http1 behavior: at most one
1443 // User-Agent. If set to nil or empty string,
1444 // then omit it. Otherwise if not mentioned,
1445 // include the default (below).
1457 for _, v := range vv {
1461 if shouldSendReqContentLength(req.Method, contentLength) {
1462 f("content-length", strconv.FormatInt(contentLength, 10))
1465 f("accept-encoding", "gzip")
1468 f("user-agent", defaultUserAgent)
1472 // Do a first pass over the headers counting bytes to ensure
1473 // we don't exceed cc.peerMaxHeaderListSize. This is done as a
1474 // separate pass before encoding the headers to prevent
1475 // modifying the hpack state.
1477 enumerateHeaders(func(name, value string) {
1478 hf := hpack.HeaderField{Name: name, Value: value}
1479 hlSize += uint64(hf.Size())
1482 if hlSize > cc.peerMaxHeaderListSize {
1483 return nil, errRequestHeaderListSize
1486 trace := httptrace.ContextClientTrace(req.Context())
1487 traceHeaders := traceHasWroteHeaderField(trace)
1489 // Header list size is ok. Write the headers.
1490 enumerateHeaders(func(name, value string) {
1491 name = strings.ToLower(name)
1492 cc.writeHeader(name, value)
1494 traceWroteHeaderField(trace, name, value)
1498 return cc.hbuf.Bytes(), nil
1501 // shouldSendReqContentLength reports whether the http2.Transport should send
1502 // a "content-length" request header. This logic is basically a copy of the net/http
1503 // transferWriter.shouldSendContentLength.
1504 // The contentLength is the corrected contentLength (so 0 means actually 0, not unknown).
1505 // -1 means unknown.
1506 func shouldSendReqContentLength(method string, contentLength int64) bool {
1507 if contentLength > 0 {
1510 if contentLength < 0 {
1513 // For zero bodies, whether we send a content-length depends on the method.
1514 // It also kinda doesn't matter for http2 either way, with END_STREAM.
1516 case "POST", "PUT", "PATCH":
1523 // requires cc.mu be held.
1524 func (cc *ClientConn) encodeTrailers(req *http.Request) ([]byte, error) {
1528 for k, vv := range req.Trailer {
1529 for _, v := range vv {
1530 hf := hpack.HeaderField{Name: k, Value: v}
1531 hlSize += uint64(hf.Size())
1534 if hlSize > cc.peerMaxHeaderListSize {
1535 return nil, errRequestHeaderListSize
1538 for k, vv := range req.Trailer {
1539 // Transfer-Encoding, etc.. have already been filtered at the
1540 // start of RoundTrip
1541 lowKey := strings.ToLower(k)
1542 for _, v := range vv {
1543 cc.writeHeader(lowKey, v)
1546 return cc.hbuf.Bytes(), nil
1549 func (cc *ClientConn) writeHeader(name, value string) {
1551 log.Printf("http2: Transport encoding header %q = %q", name, value)
1553 cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
1556 type resAndError struct {
1561 // requires cc.mu be held.
1562 func (cc *ClientConn) newStream() *clientStream {
1563 cs := &clientStream{
1565 ID: cc.nextStreamID,
1566 resc: make(chan resAndError, 1),
1567 peerReset: make(chan struct{}),
1568 done: make(chan struct{}),
1570 cs.flow.add(int32(cc.initialWindowSize))
1571 cs.flow.setConnFlow(&cc.flow)
1572 cs.inflow.add(transportDefaultStreamFlow)
1573 cs.inflow.setConnFlow(&cc.inflow)
1574 cc.nextStreamID += 2
1575 cc.streams[cs.ID] = cs
1579 func (cc *ClientConn) forgetStreamID(id uint32) {
1580 cc.streamByID(id, true)
1583 func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream {
1585 defer cc.mu.Unlock()
1586 cs := cc.streams[id]
1587 if andRemove && cs != nil && !cc.closed {
1588 cc.lastActive = time.Now()
1589 delete(cc.streams, id)
1590 if len(cc.streams) == 0 && cc.idleTimer != nil {
1591 cc.idleTimer.Reset(cc.idleTimeout)
1594 // Wake up checkResetOrDone via clientStream.awaitFlowControl and
1595 // wake up RoundTrip if there is a pending request.
1601 // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.
1602 type clientConnReadLoop struct {
1607 // readLoop runs in its own goroutine and reads and dispatches frames.
1608 func (cc *ClientConn) readLoop() {
1609 rl := &clientConnReadLoop{cc: cc}
1611 cc.readerErr = rl.run()
1612 if ce, ok := cc.readerErr.(ConnectionError); ok {
1614 cc.fr.WriteGoAway(0, ErrCode(ce), nil)
1619 // GoAwayError is returned by the Transport when the server closes the
1620 // TCP connection after sending a GOAWAY frame.
1621 type GoAwayError struct {
1627 func (e GoAwayError) Error() string {
1628 return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q",
1629 e.LastStreamID, e.ErrCode, e.DebugData)
1632 func isEOFOrNetReadError(err error) bool {
1636 ne, ok := err.(*net.OpError)
1637 return ok && ne.Op == "read"
1640 func (rl *clientConnReadLoop) cleanup() {
1642 defer cc.tconn.Close()
1643 defer cc.t.connPool().MarkDead(cc)
1644 defer close(cc.readerDone)
1646 if cc.idleTimer != nil {
1650 // Close any response bodies if the server closes prematurely.
1651 // TODO: also do this if we've written the headers but not
1652 // gotten a response yet.
1655 if cc.goAway != nil && isEOFOrNetReadError(err) {
1657 LastStreamID: cc.goAway.LastStreamID,
1658 ErrCode: cc.goAway.ErrCode,
1659 DebugData: cc.goAwayDebug,
1661 } else if err == io.EOF {
1662 err = io.ErrUnexpectedEOF
1664 for _, cs := range cc.streams {
1665 cs.bufPipe.CloseWithError(err) // no-op if already closed
1667 case cs.resc <- resAndError{err: err}:
1677 func (rl *clientConnReadLoop) run() error {
1679 rl.closeWhenIdle = cc.t.disableKeepAlives() || cc.singleUse
1680 gotReply := false // ever saw a HEADERS reply
1681 gotSettings := false
1683 f, err := cc.fr.ReadFrame()
1685 cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err)
1687 if se, ok := err.(StreamError); ok {
1688 if cs := cc.streamByID(se.StreamID, false); cs != nil {
1689 cs.cc.writeStreamReset(cs.ID, se.Code, err)
1690 cs.cc.forgetStreamID(cs.ID)
1691 if se.Cause == nil {
1692 se.Cause = cc.fr.errDetail
1694 rl.endStreamError(cs, se)
1697 } else if err != nil {
1701 cc.vlogf("http2: Transport received %s", summarizeFrame(f))
1704 if _, ok := f.(*SettingsFrame); !ok {
1705 cc.logf("protocol error: received %T before a SETTINGS frame", f)
1706 return ConnectionError(ErrCodeProtocol)
1710 maybeIdle := false // whether frame might transition us to idle
1712 switch f := f.(type) {
1713 case *MetaHeadersFrame:
1714 err = rl.processHeaders(f)
1718 err = rl.processData(f)
1721 err = rl.processGoAway(f)
1723 case *RSTStreamFrame:
1724 err = rl.processResetStream(f)
1726 case *SettingsFrame:
1727 err = rl.processSettings(f)
1728 case *PushPromiseFrame:
1729 err = rl.processPushPromise(f)
1730 case *WindowUpdateFrame:
1731 err = rl.processWindowUpdate(f)
1733 err = rl.processPing(f)
1735 cc.logf("Transport: unhandled response frame type %T", f)
1739 cc.vlogf("http2: Transport conn %p received error from processing frame %v: %v", cc, summarizeFrame(f), err)
1743 if rl.closeWhenIdle && gotReply && maybeIdle {
1749 func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error {
1751 cs := cc.streamByID(f.StreamID, false)
1753 // We'd get here if we canceled a request while the
1754 // server had its response still in flight. So if this
1755 // was just something we canceled, ignore it.
1758 if f.StreamEnded() {
1759 // Issue 20521: If the stream has ended, streamByID() causes
1760 // clientStream.done to be closed, which causes the request's bodyWriter
1761 // to be closed with an errStreamClosed, which may be received by
1762 // clientConn.RoundTrip before the result of processing these headers.
1763 // Deferring stream closure allows the header processing to occur first.
1764 // clientConn.RoundTrip may still receive the bodyWriter error first, but
1765 // the fix for issue 16102 prioritises any response.
1767 // Issue 22413: If there is no request body, we should close the
1768 // stream before writing to cs.resc so that the stream is closed
1769 // immediately once RoundTrip returns.
1770 if cs.req.Body != nil {
1771 defer cc.forgetStreamID(f.StreamID)
1773 cc.forgetStreamID(f.StreamID)
1777 if cs.trace != nil {
1778 // TODO(bradfitz): move first response byte earlier,
1779 // when we first read the 9 byte header, not waiting
1780 // until all the HEADERS+CONTINUATION frames have been
1781 // merged. This works for now.
1782 traceFirstResponseByte(cs.trace)
1786 if !cs.pastHeaders {
1787 cs.pastHeaders = true
1789 return rl.processTrailers(cs, f)
1792 res, err := rl.handleResponse(cs, f)
1794 if _, ok := err.(ConnectionError); ok {
1797 // Any other error type is a stream error.
1798 cs.cc.writeStreamReset(f.StreamID, ErrCodeProtocol, err)
1799 cc.forgetStreamID(cs.ID)
1800 cs.resc <- resAndError{err: err}
1801 return nil // return nil from process* funcs to keep conn alive
1804 // (nil, nil) special case. See handleResponse docs.
1807 cs.resTrailer = &res.Trailer
1808 cs.resc <- resAndError{res: res}
1812 // may return error types nil, or ConnectionError. Any other error value
1813 // is a StreamError of type ErrCodeProtocol. The returned error in that case
1816 // As a special case, handleResponse may return (nil, nil) to skip the
1817 // frame (currently only used for 1xx responses).
1818 func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFrame) (*http.Response, error) {
1820 return nil, errResponseHeaderListSize
1823 status := f.PseudoValue("status")
1825 return nil, errors.New("malformed response from server: missing status pseudo header")
1827 statusCode, err := strconv.Atoi(status)
1829 return nil, errors.New("malformed response from server: malformed non-numeric status pseudo header")
1832 header := make(http.Header)
1833 res := &http.Response{
1837 StatusCode: statusCode,
1838 Status: status + " " + http.StatusText(statusCode),
1840 for _, hf := range f.RegularFields() {
1841 key := http.CanonicalHeaderKey(hf.Name)
1842 if key == "Trailer" {
1845 t = make(http.Header)
1848 foreachHeaderElement(hf.Value, func(v string) {
1849 t[http.CanonicalHeaderKey(v)] = nil
1852 header[key] = append(header[key], hf.Value)
1856 if statusCode >= 100 && statusCode <= 199 {
1858 const max1xxResponses = 5 // arbitrary bound on number of informational responses, same as net/http
1859 if cs.num1xx > max1xxResponses {
1860 return nil, errors.New("http2: too many 1xx informational responses")
1862 if fn := cs.get1xxTraceFunc(); fn != nil {
1863 if err := fn(statusCode, textproto.MIMEHeader(header)); err != nil {
1867 if statusCode == 100 {
1868 traceGot100Continue(cs.trace)
1869 if cs.on100 != nil {
1870 cs.on100() // forces any write delay timer to fire
1873 cs.pastHeaders = false // do it all again
1877 streamEnded := f.StreamEnded()
1878 isHead := cs.req.Method == "HEAD"
1879 if !streamEnded || isHead {
1880 res.ContentLength = -1
1881 if clens := res.Header["Content-Length"]; len(clens) == 1 {
1882 if clen64, err := strconv.ParseInt(clens[0], 10, 64); err == nil {
1883 res.ContentLength = clen64
1885 // TODO: care? unlike http/1, it won't mess up our framing, so it's
1886 // more safe smuggling-wise to ignore.
1888 } else if len(clens) > 1 {
1889 // TODO: care? unlike http/1, it won't mess up our framing, so it's
1890 // more safe smuggling-wise to ignore.
1894 if streamEnded || isHead {
1899 cs.bufPipe = pipe{b: &dataBuffer{expected: res.ContentLength}}
1900 cs.bytesRemain = res.ContentLength
1901 res.Body = transportResponseBody{cs}
1902 go cs.awaitRequestCancel(cs.req)
1904 if cs.requestedGzip && res.Header.Get("Content-Encoding") == "gzip" {
1905 res.Header.Del("Content-Encoding")
1906 res.Header.Del("Content-Length")
1907 res.ContentLength = -1
1908 res.Body = &gzipReader{body: res.Body}
1909 res.Uncompressed = true
1914 func (rl *clientConnReadLoop) processTrailers(cs *clientStream, f *MetaHeadersFrame) error {
1915 if cs.pastTrailers {
1916 // Too many HEADERS frames for this stream.
1917 return ConnectionError(ErrCodeProtocol)
1919 cs.pastTrailers = true
1920 if !f.StreamEnded() {
1921 // We expect that any headers for trailers also
1923 return ConnectionError(ErrCodeProtocol)
1925 if len(f.PseudoFields()) > 0 {
1926 // No pseudo header fields are defined for trailers.
1927 // TODO: ConnectionError might be overly harsh? Check.
1928 return ConnectionError(ErrCodeProtocol)
1931 trailer := make(http.Header)
1932 for _, hf := range f.RegularFields() {
1933 key := http.CanonicalHeaderKey(hf.Name)
1934 trailer[key] = append(trailer[key], hf.Value)
1936 cs.trailer = trailer
1942 // transportResponseBody is the concrete type of Transport.RoundTrip's
1943 // Response.Body. It is an io.ReadCloser. On Read, it reads from cs.body.
1944 // On Close it sends RST_STREAM if EOF wasn't already seen.
1945 type transportResponseBody struct {
1949 func (b transportResponseBody) Read(p []byte) (n int, err error) {
1953 if cs.readErr != nil {
1954 return 0, cs.readErr
1956 n, err = b.cs.bufPipe.Read(p)
1957 if cs.bytesRemain != -1 {
1958 if int64(n) > cs.bytesRemain {
1959 n = int(cs.bytesRemain)
1961 err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
1962 cc.writeStreamReset(cs.ID, ErrCodeProtocol, err)
1965 return int(cs.bytesRemain), err
1967 cs.bytesRemain -= int64(n)
1968 if err == io.EOF && cs.bytesRemain > 0 {
1969 err = io.ErrUnexpectedEOF
1975 // No flow control tokens to send back.
1980 defer cc.mu.Unlock()
1982 var connAdd, streamAdd int32
1983 // Check the conn-level first, before the stream-level.
1984 if v := cc.inflow.available(); v < transportDefaultConnFlow/2 {
1985 connAdd = transportDefaultConnFlow - v
1986 cc.inflow.add(connAdd)
1988 if err == nil { // No need to refresh if the stream is over or failed.
1989 // Consider any buffered body data (read from the conn but not
1990 // consumed by the client) when computing flow control for this
1992 v := int(cs.inflow.available()) + cs.bufPipe.Len()
1993 if v < transportDefaultStreamFlow-transportDefaultStreamMinRefresh {
1994 streamAdd = int32(transportDefaultStreamFlow - v)
1995 cs.inflow.add(streamAdd)
1998 if connAdd != 0 || streamAdd != 0 {
2000 defer cc.wmu.Unlock()
2002 cc.fr.WriteWindowUpdate(0, mustUint31(connAdd))
2005 cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd))
2012 var errClosedResponseBody = errors.New("http2: response body closed")
2014 func (b transportResponseBody) Close() error {
2018 serverSentStreamEnd := cs.bufPipe.Err() == io.EOF
2019 unread := cs.bufPipe.Len()
2021 if unread > 0 || !serverSentStreamEnd {
2024 if !serverSentStreamEnd {
2025 cc.fr.WriteRSTStream(cs.ID, ErrCodeCancel)
2028 // Return connection-level flow control.
2030 cc.inflow.add(int32(unread))
2031 cc.fr.WriteWindowUpdate(0, uint32(unread))
2038 cs.bufPipe.BreakWithError(errClosedResponseBody)
2039 cc.forgetStreamID(cs.ID)
2043 func (rl *clientConnReadLoop) processData(f *DataFrame) error {
2045 cs := cc.streamByID(f.StreamID, f.StreamEnded())
2049 neverSent := cc.nextStreamID
2051 if f.StreamID >= neverSent {
2052 // We never asked for this.
2053 cc.logf("http2: Transport received unsolicited DATA frame; closing connection")
2054 return ConnectionError(ErrCodeProtocol)
2056 // We probably did ask for this, but canceled. Just ignore it.
2057 // TODO: be stricter here? only silently ignore things which
2058 // we canceled, but not things which were closed normally
2059 // by the peer? Tough without accumulating too much state.
2061 // But at least return their flow control:
2064 cc.inflow.add(int32(f.Length))
2068 cc.fr.WriteWindowUpdate(0, uint32(f.Length))
2075 cc.logf("protocol error: received DATA before a HEADERS frame")
2076 rl.endStreamError(cs, StreamError{
2077 StreamID: f.StreamID,
2078 Code: ErrCodeProtocol,
2083 if cs.req.Method == "HEAD" && len(data) > 0 {
2084 cc.logf("protocol error: received DATA on a HEAD request")
2085 rl.endStreamError(cs, StreamError{
2086 StreamID: f.StreamID,
2087 Code: ErrCodeProtocol,
2091 // Check connection-level flow control.
2093 if cs.inflow.available() >= int32(f.Length) {
2094 cs.inflow.take(int32(f.Length))
2097 return ConnectionError(ErrCodeFlowControl)
2099 // Return any padded flow control now, since we won't
2100 // refund it later on body reads.
2102 if pad := int(f.Length) - len(data); pad > 0 {
2105 // Return len(data) now if the stream is already closed,
2106 // since data will never be read.
2107 didReset := cs.didReset
2112 cc.inflow.add(int32(refund))
2114 cc.fr.WriteWindowUpdate(0, uint32(refund))
2116 cs.inflow.add(int32(refund))
2117 cc.fr.WriteWindowUpdate(cs.ID, uint32(refund))
2124 if len(data) > 0 && !didReset {
2125 if _, err := cs.bufPipe.Write(data); err != nil {
2126 rl.endStreamError(cs, err)
2132 if f.StreamEnded() {
2138 var errInvalidTrailers = errors.New("http2: invalid trailers")
2140 func (rl *clientConnReadLoop) endStream(cs *clientStream) {
2141 // TODO: check that any declared content-length matches, like
2142 // server.go's (*stream).endStream method.
2143 rl.endStreamError(cs, nil)
2146 func (rl *clientConnReadLoop) endStreamError(cs *clientStream, err error) {
2150 code = cs.copyTrailers
2152 if isConnectionCloseRequest(cs.req) {
2153 rl.closeWhenIdle = true
2155 cs.bufPipe.closeWithErrorAndCode(err, code)
2158 case cs.resc <- resAndError{err: err}:
2163 func (cs *clientStream) copyTrailers() {
2164 for k, vv := range cs.trailer {
2167 *t = make(http.Header)
2173 func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error {
2175 cc.t.connPool().MarkDead(cc)
2177 // TODO: deal with GOAWAY more. particularly the error code
2178 cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
2184 func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error {
2187 defer cc.mu.Unlock()
2190 if cc.wantSettingsAck {
2191 cc.wantSettingsAck = false
2194 return ConnectionError(ErrCodeProtocol)
2197 err := f.ForeachSetting(func(s Setting) error {
2199 case SettingMaxFrameSize:
2200 cc.maxFrameSize = s.Val
2201 case SettingMaxConcurrentStreams:
2202 cc.maxConcurrentStreams = s.Val
2203 case SettingMaxHeaderListSize:
2204 cc.peerMaxHeaderListSize = uint64(s.Val)
2205 case SettingInitialWindowSize:
2206 // Values above the maximum flow-control
2207 // window size of 2^31-1 MUST be treated as a
2208 // connection error (Section 5.4.1) of type
2209 // FLOW_CONTROL_ERROR.
2210 if s.Val > math.MaxInt32 {
2211 return ConnectionError(ErrCodeFlowControl)
2214 // Adjust flow control of currently-open
2215 // frames by the difference of the old initial
2216 // window size and this one.
2217 delta := int32(s.Val) - int32(cc.initialWindowSize)
2218 for _, cs := range cc.streams {
2223 cc.initialWindowSize = s.Val
2225 // TODO(bradfitz): handle more settings? SETTINGS_HEADER_TABLE_SIZE probably.
2226 cc.vlogf("Unhandled Setting: %v", s)
2235 defer cc.wmu.Unlock()
2237 cc.fr.WriteSettingsAck()
2242 func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error {
2244 cs := cc.streamByID(f.StreamID, false)
2245 if f.StreamID != 0 && cs == nil {
2250 defer cc.mu.Unlock()
2256 if !fl.add(int32(f.Increment)) {
2257 return ConnectionError(ErrCodeFlowControl)
2263 func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error {
2264 cs := rl.cc.streamByID(f.StreamID, true)
2266 // TODO: return error if server tries to RST_STEAM an idle stream
2270 case <-cs.peerReset:
2272 // This is the only goroutine
2273 // which closes this, so there
2276 err := streamError(cs.ID, f.ErrCode)
2279 cs.bufPipe.CloseWithError(err)
2280 cs.cc.cond.Broadcast() // wake up checkResetOrDone via clientStream.awaitFlowControl
2285 // Ping sends a PING frame to the server and waits for the ack.
2286 func (cc *ClientConn) Ping(ctx context.Context) error {
2287 c := make(chan struct{})
2288 // Generate a random payload
2291 if _, err := rand.Read(p[:]); err != nil {
2295 // check for dup before insert
2296 if _, found := cc.pings[p]; !found {
2304 if err := cc.fr.WritePing(false, p); err != nil {
2308 if err := cc.bw.Flush(); err != nil {
2318 case <-cc.readerDone:
2319 // connection closed
2324 func (rl *clientConnReadLoop) processPing(f *PingFrame) error {
2328 defer cc.mu.Unlock()
2329 // If ack, notify listener if any
2330 if c, ok := cc.pings[f.Data]; ok {
2332 delete(cc.pings, f.Data)
2338 defer cc.wmu.Unlock()
2339 if err := cc.fr.WritePing(true, f.Data); err != nil {
2342 return cc.bw.Flush()
2345 func (rl *clientConnReadLoop) processPushPromise(f *PushPromiseFrame) error {
2346 // We told the peer we don't want them.
2348 // "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH
2349 // setting of the peer endpoint is set to 0. An endpoint that
2350 // has set this setting and has received acknowledgement MUST
2351 // treat the receipt of a PUSH_PROMISE frame as a connection
2352 // error (Section 5.4.1) of type PROTOCOL_ERROR."
2353 return ConnectionError(ErrCodeProtocol)
2356 func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) {
2357 // TODO: map err to more interesting error codes, once the
2358 // HTTP community comes up with some. But currently for
2359 // RST_STREAM there's no equivalent to GOAWAY frame's debug
2360 // data, and the error codes are all pretty vague ("cancel").
2362 cc.fr.WriteRSTStream(streamID, code)
2368 errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
2369 errRequestHeaderListSize = errors.New("http2: request header list larger than peer's advertised limit")
2370 errPseudoTrailers = errors.New("http2: invalid pseudo header in trailers")
2373 func (cc *ClientConn) logf(format string, args ...interface{}) {
2374 cc.t.logf(format, args...)
2377 func (cc *ClientConn) vlogf(format string, args ...interface{}) {
2378 cc.t.vlogf(format, args...)
2381 func (t *Transport) vlogf(format string, args ...interface{}) {
2383 t.logf(format, args...)
2387 func (t *Transport) logf(format string, args ...interface{}) {
2388 log.Printf(format, args...)
2391 var noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
2393 func strSliceContains(ss []string, s string) bool {
2394 for _, v := range ss {
2402 type erringRoundTripper struct{ err error }
2404 func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err }
2406 // gzipReader wraps a response body so it can lazily
2407 // call gzip.NewReader on the first call to Read
2408 type gzipReader struct {
2409 body io.ReadCloser // underlying Response.Body
2410 zr *gzip.Reader // lazily-initialized gzip reader
2411 zerr error // sticky error
2414 func (gz *gzipReader) Read(p []byte) (n int, err error) {
2419 gz.zr, err = gzip.NewReader(gz.body)
2425 return gz.zr.Read(p)
2428 func (gz *gzipReader) Close() error {
2429 return gz.body.Close()
2432 type errorReader struct{ err error }
2434 func (r errorReader) Read(p []byte) (int, error) { return 0, r.err }
2436 // bodyWriterState encapsulates various state around the Transport's writing
2437 // of the request body, particularly regarding doing delayed writes of the body
2438 // when the request contains "Expect: 100-continue".
2439 type bodyWriterState struct {
2441 timer *time.Timer // if non-nil, we're doing a delayed write
2442 fnonce *sync.Once // to call fn with
2443 fn func() // the code to run in the goroutine, writing the body
2444 resc chan error // result of fn's execution
2445 delay time.Duration // how long we should delay a delayed write for
2448 func (t *Transport) getBodyWriterState(cs *clientStream, body io.Reader) (s bodyWriterState) {
2453 resc := make(chan error, 1)
2457 cs.startedWrite = true
2459 resc <- cs.writeRequestBody(body, cs.req.Body)
2461 s.delay = t.expectContinueTimeout()
2463 !httpguts.HeaderValuesContainsToken(
2464 cs.req.Header["Expect"],
2468 s.fnonce = new(sync.Once)
2470 // Arm the timer with a very large duration, which we'll
2471 // intentionally lower later. It has to be large now because
2472 // we need a handle to it before writing the headers, but the
2473 // s.delay value is defined to not start until after the
2474 // request headers were written.
2475 const hugeDuration = 365 * 24 * time.Hour
2476 s.timer = time.AfterFunc(hugeDuration, func() {
2482 func (s bodyWriterState) cancel() {
2488 func (s bodyWriterState) on100() {
2490 // If we didn't do a delayed write, ignore the server's
2491 // bogus 100 continue response.
2495 go func() { s.fnonce.Do(s.fn) }()
2498 // scheduleBodyWrite starts writing the body, either immediately (in
2499 // the common case) or after the delay timeout. It should not be
2500 // called until after the headers have been written.
2501 func (s bodyWriterState) scheduleBodyWrite() {
2503 // We're not doing a delayed write (see
2504 // getBodyWriterState), so just start the writing
2505 // goroutine immediately.
2509 traceWait100Continue(s.cs.trace)
2511 s.timer.Reset(s.delay)
2515 // isConnectionCloseRequest reports whether req should use its own
2516 // connection for a single request and then close the connection.
2517 func isConnectionCloseRequest(req *http.Request) bool {
2518 return req.Close || httpguts.HeaderValuesContainsToken(req.Header["Connection"], "close")
2521 // registerHTTPSProtocol calls Transport.RegisterProtocol but
2522 // converting panics into errors.
2523 func registerHTTPSProtocol(t *http.Transport, rt noDialH2RoundTripper) (err error) {
2525 if e := recover(); e != nil {
2526 err = fmt.Errorf("%v", e)
2529 t.RegisterProtocol("https", rt)
2533 // noDialH2RoundTripper is a RoundTripper which only tries to complete the request
2534 // if there's already has a cached connection to the host.
2535 // (The field is exported so it can be accessed via reflect from net/http; tested
2536 // by TestNoDialH2RoundTripperType)
2537 type noDialH2RoundTripper struct{ *Transport }
2539 func (rt noDialH2RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
2540 res, err := rt.Transport.RoundTrip(req)
2541 if isNoCachedConnError(err) {
2542 return nil, http.ErrSkipAltProtocol
2547 func (t *Transport) idleConnTimeout() time.Duration {
2549 return t.t1.IdleConnTimeout
2554 func traceGetConn(req *http.Request, hostPort string) {
2555 trace := httptrace.ContextClientTrace(req.Context())
2556 if trace == nil || trace.GetConn == nil {
2559 trace.GetConn(hostPort)
2562 func traceGotConn(req *http.Request, cc *ClientConn) {
2563 trace := httptrace.ContextClientTrace(req.Context())
2564 if trace == nil || trace.GotConn == nil {
2567 ci := httptrace.GotConnInfo{Conn: cc.tconn}
2569 ci.Reused = cc.nextStreamID > 1
2570 ci.WasIdle = len(cc.streams) == 0 && ci.Reused
2571 if ci.WasIdle && !cc.lastActive.IsZero() {
2572 ci.IdleTime = time.Now().Sub(cc.lastActive)
2579 func traceWroteHeaders(trace *httptrace.ClientTrace) {
2580 if trace != nil && trace.WroteHeaders != nil {
2581 trace.WroteHeaders()
2585 func traceGot100Continue(trace *httptrace.ClientTrace) {
2586 if trace != nil && trace.Got100Continue != nil {
2587 trace.Got100Continue()
2591 func traceWait100Continue(trace *httptrace.ClientTrace) {
2592 if trace != nil && trace.Wait100Continue != nil {
2593 trace.Wait100Continue()
2597 func traceWroteRequest(trace *httptrace.ClientTrace, err error) {
2598 if trace != nil && trace.WroteRequest != nil {
2599 trace.WroteRequest(httptrace.WroteRequestInfo{Err: err})
2603 func traceFirstResponseByte(trace *httptrace.ClientTrace) {
2604 if trace != nil && trace.GotFirstResponseByte != nil {
2605 trace.GotFirstResponseByte()