forked from ebhomengo/niki
1
0
Fork 0
niki/vendor/golang.org/x/net/http2/transport.go

6143 lines
96 KiB
Go
Raw Normal View History

2024-02-18 10:42:21 +00:00
// Copyright 2015 The Go Authors. All rights reserved.
2024-02-18 10:42:21 +00:00
// Use of this source code is governed by a BSD-style
2024-02-18 10:42:21 +00:00
// license that can be found in the LICENSE file.
// Transport code.
package http2
import (
"bufio"
"bytes"
"compress/gzip"
"context"
"crypto/rand"
"crypto/tls"
"errors"
"fmt"
"io"
"io/fs"
"log"
"math"
"math/bits"
mathrand "math/rand"
"net"
"net/http"
"net/http/httptrace"
"net/textproto"
"os"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"golang.org/x/net/http/httpguts"
"golang.org/x/net/http2/hpack"
"golang.org/x/net/idna"
)
const (
2024-02-18 10:42:21 +00:00
// transportDefaultConnFlow is how many connection-level flow control
2024-02-18 10:42:21 +00:00
// tokens we give the server at start-up, past the default 64k.
2024-02-18 10:42:21 +00:00
transportDefaultConnFlow = 1 << 30
// transportDefaultStreamFlow is how many stream-level flow
2024-02-18 10:42:21 +00:00
// control tokens we announce to the peer, and how many bytes
2024-02-18 10:42:21 +00:00
// we buffer per stream.
2024-02-18 10:42:21 +00:00
transportDefaultStreamFlow = 4 << 20
defaultUserAgent = "Go-http-client/2.0"
// initialMaxConcurrentStreams is a connections maxConcurrentStreams until
2024-02-18 10:42:21 +00:00
// it's received servers initial SETTINGS frame, which corresponds with the
2024-02-18 10:42:21 +00:00
// spec's minimum recommended value.
2024-02-18 10:42:21 +00:00
initialMaxConcurrentStreams = 100
// defaultMaxConcurrentStreams is a connections default maxConcurrentStreams
2024-02-18 10:42:21 +00:00
// if the server doesn't include one in its initial SETTINGS frame.
2024-02-18 10:42:21 +00:00
defaultMaxConcurrentStreams = 1000
)
// Transport is an HTTP/2 Transport.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// A Transport internally caches connections to servers. It is safe
2024-02-18 10:42:21 +00:00
// for concurrent use by multiple goroutines.
2024-02-18 10:42:21 +00:00
type Transport struct {
2024-02-18 10:42:21 +00:00
// DialTLSContext specifies an optional dial function with context for
2024-02-18 10:42:21 +00:00
// creating TLS connections for requests.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// If DialTLSContext and DialTLS is nil, tls.Dial is used.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// If the returned net.Conn has a ConnectionState method like tls.Conn,
2024-02-18 10:42:21 +00:00
// it will be used to set http.Response.TLS.
2024-02-18 10:42:21 +00:00
DialTLSContext func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error)
// DialTLS specifies an optional dial function for creating
2024-02-18 10:42:21 +00:00
// TLS connections for requests.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// If DialTLSContext and DialTLS is nil, tls.Dial is used.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// Deprecated: Use DialTLSContext instead, which allows the transport
2024-02-18 10:42:21 +00:00
// to cancel dials as soon as they are no longer needed.
2024-02-18 10:42:21 +00:00
// If both are set, DialTLSContext takes priority.
2024-02-18 10:42:21 +00:00
DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error)
// TLSClientConfig specifies the TLS configuration to use with
2024-02-18 10:42:21 +00:00
// tls.Client. If nil, the default configuration is used.
2024-02-18 10:42:21 +00:00
TLSClientConfig *tls.Config
// ConnPool optionally specifies an alternate connection pool to use.
2024-02-18 10:42:21 +00:00
// If nil, the default is used.
2024-02-18 10:42:21 +00:00
ConnPool ClientConnPool
// DisableCompression, if true, prevents the Transport from
2024-02-18 10:42:21 +00:00
// requesting compression with an "Accept-Encoding: gzip"
2024-02-18 10:42:21 +00:00
// request header when the Request contains no existing
2024-02-18 10:42:21 +00:00
// Accept-Encoding value. If the Transport requests gzip on
2024-02-18 10:42:21 +00:00
// its own and gets a gzipped response, it's transparently
2024-02-18 10:42:21 +00:00
// decoded in the Response.Body. However, if the user
2024-02-18 10:42:21 +00:00
// explicitly requested gzip it is not automatically
2024-02-18 10:42:21 +00:00
// uncompressed.
2024-02-18 10:42:21 +00:00
DisableCompression bool
// AllowHTTP, if true, permits HTTP/2 requests using the insecure,
2024-02-18 10:42:21 +00:00
// plain-text "http" scheme. Note that this does not enable h2c support.
2024-02-18 10:42:21 +00:00
AllowHTTP bool
// MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
2024-02-18 10:42:21 +00:00
// send in the initial settings frame. It is how many bytes
2024-02-18 10:42:21 +00:00
// of response headers are allowed. Unlike the http2 spec, zero here
2024-02-18 10:42:21 +00:00
// means to use a default limit (currently 10MB). If you actually
2024-02-18 10:42:21 +00:00
// want to advertise an unlimited value to the peer, Transport
2024-02-18 10:42:21 +00:00
// interprets the highest possible value here (0xffffffff or 1<<32-1)
2024-02-18 10:42:21 +00:00
// to mean no limit.
2024-02-18 10:42:21 +00:00
MaxHeaderListSize uint32
// MaxReadFrameSize is the http2 SETTINGS_MAX_FRAME_SIZE to send in the
2024-02-18 10:42:21 +00:00
// initial settings frame. It is the size in bytes of the largest frame
2024-02-18 10:42:21 +00:00
// payload that the sender is willing to receive. If 0, no setting is
2024-02-18 10:42:21 +00:00
// sent, and the value is provided by the peer, which should be 16384
2024-02-18 10:42:21 +00:00
// according to the spec:
2024-02-18 10:42:21 +00:00
// https://datatracker.ietf.org/doc/html/rfc7540#section-6.5.2.
2024-02-18 10:42:21 +00:00
// Values are bounded in the range 16k to 16M.
2024-02-18 10:42:21 +00:00
MaxReadFrameSize uint32
// MaxDecoderHeaderTableSize optionally specifies the http2
2024-02-18 10:42:21 +00:00
// SETTINGS_HEADER_TABLE_SIZE to send in the initial settings frame. It
2024-02-18 10:42:21 +00:00
// informs the remote endpoint of the maximum size of the header compression
2024-02-18 10:42:21 +00:00
// table used to decode header blocks, in octets. If zero, the default value
2024-02-18 10:42:21 +00:00
// of 4096 is used.
2024-02-18 10:42:21 +00:00
MaxDecoderHeaderTableSize uint32
// MaxEncoderHeaderTableSize optionally specifies an upper limit for the
2024-02-18 10:42:21 +00:00
// header compression table used for encoding request headers. Received
2024-02-18 10:42:21 +00:00
// SETTINGS_HEADER_TABLE_SIZE settings are capped at this limit. If zero,
2024-02-18 10:42:21 +00:00
// the default value of 4096 is used.
2024-02-18 10:42:21 +00:00
MaxEncoderHeaderTableSize uint32
// StrictMaxConcurrentStreams controls whether the server's
2024-02-18 10:42:21 +00:00
// SETTINGS_MAX_CONCURRENT_STREAMS should be respected
2024-02-18 10:42:21 +00:00
// globally. If false, new TCP connections are created to the
2024-02-18 10:42:21 +00:00
// server as needed to keep each under the per-connection
2024-02-18 10:42:21 +00:00
// SETTINGS_MAX_CONCURRENT_STREAMS limit. If true, the
2024-02-18 10:42:21 +00:00
// server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as
2024-02-18 10:42:21 +00:00
// a global limit and callers of RoundTrip block when needed,
2024-02-18 10:42:21 +00:00
// waiting for their turn.
2024-02-18 10:42:21 +00:00
StrictMaxConcurrentStreams bool
2024-05-14 13:07:09 +00:00
// IdleConnTimeout is the maximum amount of time an idle
2024-05-14 13:07:09 +00:00
// (keep-alive) connection will remain idle before closing
2024-05-14 13:07:09 +00:00
// itself.
2024-05-14 13:07:09 +00:00
// Zero means no limit.
2024-05-14 13:07:09 +00:00
IdleConnTimeout time.Duration
2024-02-18 10:42:21 +00:00
// ReadIdleTimeout is the timeout after which a health check using ping
2024-02-18 10:42:21 +00:00
// frame will be carried out if no frame is received on the connection.
2024-02-18 10:42:21 +00:00
// Note that a ping response will is considered a received frame, so if
2024-02-18 10:42:21 +00:00
// there is no other traffic on the connection, the health check will
2024-02-18 10:42:21 +00:00
// be performed every ReadIdleTimeout interval.
2024-02-18 10:42:21 +00:00
// If zero, no health check is performed.
2024-02-18 10:42:21 +00:00
ReadIdleTimeout time.Duration
// PingTimeout is the timeout after which the connection will be closed
2024-02-18 10:42:21 +00:00
// if a response to Ping is not received.
2024-02-18 10:42:21 +00:00
// Defaults to 15s.
2024-02-18 10:42:21 +00:00
PingTimeout time.Duration
// WriteByteTimeout is the timeout after which the connection will be
2024-02-18 10:42:21 +00:00
// closed no data can be written to it. The timeout begins when data is
2024-02-18 10:42:21 +00:00
// available to write, and is extended whenever any bytes are written.
2024-02-18 10:42:21 +00:00
WriteByteTimeout time.Duration
// CountError, if non-nil, is called on HTTP/2 transport errors.
2024-02-18 10:42:21 +00:00
// It's intended to increment a metric for monitoring, such
2024-02-18 10:42:21 +00:00
// as an expvar or Prometheus metric.
2024-02-18 10:42:21 +00:00
// The errType consists of only ASCII word characters.
2024-02-18 10:42:21 +00:00
CountError func(errType string)
// t1, if non-nil, is the standard library Transport using
2024-02-18 10:42:21 +00:00
// this transport. Its settings are used (but not its
2024-02-18 10:42:21 +00:00
// RoundTrip method, etc).
2024-02-18 10:42:21 +00:00
t1 *http.Transport
connPoolOnce sync.Once
2024-02-18 10:42:21 +00:00
connPoolOrDef ClientConnPool // non-nil version of ConnPool
2024-05-14 13:07:09 +00:00
syncHooks *testSyncHooks
2024-02-18 10:42:21 +00:00
}
func (t *Transport) maxHeaderListSize() uint32 {
2024-02-18 10:42:21 +00:00
if t.MaxHeaderListSize == 0 {
2024-02-18 10:42:21 +00:00
return 10 << 20
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if t.MaxHeaderListSize == 0xffffffff {
2024-02-18 10:42:21 +00:00
return 0
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return t.MaxHeaderListSize
2024-02-18 10:42:21 +00:00
}
func (t *Transport) maxFrameReadSize() uint32 {
2024-02-18 10:42:21 +00:00
if t.MaxReadFrameSize == 0 {
2024-02-18 10:42:21 +00:00
return 0 // use the default provided by the peer
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if t.MaxReadFrameSize < minMaxFrameSize {
2024-02-18 10:42:21 +00:00
return minMaxFrameSize
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if t.MaxReadFrameSize > maxFrameSize {
2024-02-18 10:42:21 +00:00
return maxFrameSize
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return t.MaxReadFrameSize
2024-02-18 10:42:21 +00:00
}
func (t *Transport) disableCompression() bool {
2024-02-18 10:42:21 +00:00
return t.DisableCompression || (t.t1 != nil && t.t1.DisableCompression)
2024-02-18 10:42:21 +00:00
}
func (t *Transport) pingTimeout() time.Duration {
2024-02-18 10:42:21 +00:00
if t.PingTimeout == 0 {
2024-02-18 10:42:21 +00:00
return 15 * time.Second
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return t.PingTimeout
}
// ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2.
2024-02-18 10:42:21 +00:00
// It returns an error if t1 has already been HTTP/2-enabled.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// Use ConfigureTransports instead to configure the HTTP/2 Transport.
2024-02-18 10:42:21 +00:00
func ConfigureTransport(t1 *http.Transport) error {
2024-02-18 10:42:21 +00:00
_, err := ConfigureTransports(t1)
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
// ConfigureTransports configures a net/http HTTP/1 Transport to use HTTP/2.
2024-02-18 10:42:21 +00:00
// It returns a new HTTP/2 Transport for further configuration.
2024-02-18 10:42:21 +00:00
// It returns an error if t1 has already been HTTP/2-enabled.
2024-02-18 10:42:21 +00:00
func ConfigureTransports(t1 *http.Transport) (*Transport, error) {
2024-02-18 10:42:21 +00:00
return configureTransports(t1)
2024-02-18 10:42:21 +00:00
}
func configureTransports(t1 *http.Transport) (*Transport, error) {
2024-02-18 10:42:21 +00:00
connPool := new(clientConnPool)
2024-02-18 10:42:21 +00:00
t2 := &Transport{
2024-02-18 10:42:21 +00:00
ConnPool: noDialClientConnPool{connPool},
t1: t1,
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
connPool.t = t2
2024-02-18 10:42:21 +00:00
if err := registerHTTPSProtocol(t1, noDialH2RoundTripper{t2}); err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if t1.TLSClientConfig == nil {
2024-02-18 10:42:21 +00:00
t1.TLSClientConfig = new(tls.Config)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if !strSliceContains(t1.TLSClientConfig.NextProtos, "h2") {
2024-02-18 10:42:21 +00:00
t1.TLSClientConfig.NextProtos = append([]string{"h2"}, t1.TLSClientConfig.NextProtos...)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if !strSliceContains(t1.TLSClientConfig.NextProtos, "http/1.1") {
2024-02-18 10:42:21 +00:00
t1.TLSClientConfig.NextProtos = append(t1.TLSClientConfig.NextProtos, "http/1.1")
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
upgradeFn := func(authority string, c *tls.Conn) http.RoundTripper {
2024-02-18 10:42:21 +00:00
addr := authorityAddr("https", authority)
2024-02-18 10:42:21 +00:00
if used, err := connPool.addConnIfNeeded(addr, t2, c); err != nil {
2024-02-18 10:42:21 +00:00
go c.Close()
2024-02-18 10:42:21 +00:00
return erringRoundTripper{err}
2024-02-18 10:42:21 +00:00
} else if !used {
2024-02-18 10:42:21 +00:00
// Turns out we don't need this c.
2024-02-18 10:42:21 +00:00
// For example, two goroutines made requests to the same host
2024-02-18 10:42:21 +00:00
// at the same time, both kicking off TCP dials. (since protocol
2024-02-18 10:42:21 +00:00
// was unknown)
2024-02-18 10:42:21 +00:00
go c.Close()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return t2
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if m := t1.TLSNextProto; len(m) == 0 {
2024-02-18 10:42:21 +00:00
t1.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{
2024-02-18 10:42:21 +00:00
"h2": upgradeFn,
}
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
m["h2"] = upgradeFn
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return t2, nil
2024-02-18 10:42:21 +00:00
}
func (t *Transport) connPool() ClientConnPool {
2024-02-18 10:42:21 +00:00
t.connPoolOnce.Do(t.initConnPool)
2024-02-18 10:42:21 +00:00
return t.connPoolOrDef
2024-02-18 10:42:21 +00:00
}
func (t *Transport) initConnPool() {
2024-02-18 10:42:21 +00:00
if t.ConnPool != nil {
2024-02-18 10:42:21 +00:00
t.connPoolOrDef = t.ConnPool
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
t.connPoolOrDef = &clientConnPool{t: t}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// ClientConn is the state of a single HTTP/2 client connection to an
2024-02-18 10:42:21 +00:00
// HTTP/2 server.
2024-02-18 10:42:21 +00:00
type ClientConn struct {
t *Transport
tconn net.Conn // usually *tls.Conn, except specialized impls
tlsState *tls.ConnectionState // nil only for specialized impls
reused uint32 // whether conn is being reused; atomic
singleUse bool // whether being used for a single http.Request
getConnCalled bool // used by clientConnPool
2024-02-18 10:42:21 +00:00
// readLoop goroutine fields:
2024-02-18 10:42:21 +00:00
readerDone chan struct{} // closed on error
readerErr error // set before readerDone is closed
2024-02-18 10:42:21 +00:00
idleTimeout time.Duration // or 0 for never
idleTimer timer
mu sync.Mutex // guards following
cond *sync.Cond // hold mu; broadcast on flow/closed changes
flow outflow // our conn-level flow control quota (cs.outflow is per stream)
inflow inflow // peer's conn-level flow control
doNotReuse bool // whether conn is marked to not be reused for any future requests
closing bool
closed bool
seenSettings bool // true if we've seen a settings frame, false otherwise
wantSettingsAck bool // we sent a SETTINGS frame and haven't heard back
goAway *GoAwayFrame // if non-nil, the GoAwayFrame we received
goAwayDebug string // goAway frame's debug data, retained as a string
streams map[uint32]*clientStream // client-initiated
streamsReserved int // incr by ReserveNewRequest; decr on RoundTrip
nextStreamID uint32
pendingRequests int // requests blocked and waiting to be sent because len(streams) == maxConcurrentStreams
pings map[[8]byte]chan struct{} // in flight ping data to notification channel
br *bufio.Reader
lastActive time.Time
lastIdle time.Time // time last idle
2024-02-18 10:42:21 +00:00
// Settings from peer: (also guarded by wmu)
maxFrameSize uint32
maxConcurrentStreams uint32
peerMaxHeaderListSize uint64
2024-02-18 10:42:21 +00:00
peerMaxHeaderTableSize uint32
initialWindowSize uint32
2024-02-18 10:42:21 +00:00
// reqHeaderMu is a 1-element semaphore channel controlling access to sending new requests.
2024-02-18 10:42:21 +00:00
// Write to reqHeaderMu to lock it, read from it to unlock.
2024-02-18 10:42:21 +00:00
// Lock reqmu BEFORE mu or wmu.
2024-02-18 10:42:21 +00:00
reqHeaderMu chan struct{}
// wmu is held while writing.
2024-02-18 10:42:21 +00:00
// Acquire BEFORE mu when holding both, to avoid blocking mu on network writes.
2024-02-18 10:42:21 +00:00
// Only acquire both at the same time when changing peer settings.
wmu sync.Mutex
bw *bufio.Writer
fr *Framer
werr error // first write error that has occurred
2024-02-18 10:42:21 +00:00
hbuf bytes.Buffer // HPACK encoder writes into this
2024-02-18 10:42:21 +00:00
henc *hpack.Encoder
2024-05-14 13:07:09 +00:00
syncHooks *testSyncHooks // can be nil
2024-05-14 13:07:09 +00:00
}
// Hook points used for testing.
2024-05-14 13:07:09 +00:00
// Outside of tests, cc.syncHooks is nil and these all have minimal implementations.
2024-05-14 13:07:09 +00:00
// Inside tests, see the testSyncHooks function docs.
// goRun starts a new goroutine.
2024-05-14 13:07:09 +00:00
func (cc *ClientConn) goRun(f func()) {
2024-05-14 13:07:09 +00:00
if cc.syncHooks != nil {
2024-05-14 13:07:09 +00:00
cc.syncHooks.goRun(f)
2024-05-14 13:07:09 +00:00
return
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
go f()
2024-05-14 13:07:09 +00:00
}
// condBroadcast is cc.cond.Broadcast.
2024-05-14 13:07:09 +00:00
func (cc *ClientConn) condBroadcast() {
2024-05-14 13:07:09 +00:00
if cc.syncHooks != nil {
2024-05-14 13:07:09 +00:00
cc.syncHooks.condBroadcast(cc.cond)
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
cc.cond.Broadcast()
2024-05-14 13:07:09 +00:00
}
// condWait is cc.cond.Wait.
2024-05-14 13:07:09 +00:00
func (cc *ClientConn) condWait() {
2024-05-14 13:07:09 +00:00
if cc.syncHooks != nil {
2024-05-14 13:07:09 +00:00
cc.syncHooks.condWait(cc.cond)
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
cc.cond.Wait()
2024-05-14 13:07:09 +00:00
}
// newTimer creates a new time.Timer, or a synthetic timer in tests.
2024-05-14 13:07:09 +00:00
func (cc *ClientConn) newTimer(d time.Duration) timer {
2024-05-14 13:07:09 +00:00
if cc.syncHooks != nil {
2024-05-14 13:07:09 +00:00
return cc.syncHooks.newTimer(d)
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
return newTimeTimer(d)
2024-05-14 13:07:09 +00:00
}
// afterFunc creates a new time.AfterFunc timer, or a synthetic timer in tests.
2024-05-14 13:07:09 +00:00
func (cc *ClientConn) afterFunc(d time.Duration, f func()) timer {
2024-05-14 13:07:09 +00:00
if cc.syncHooks != nil {
2024-05-14 13:07:09 +00:00
return cc.syncHooks.afterFunc(d, f)
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
return newTimeAfterFunc(d, f)
2024-05-14 13:07:09 +00:00
}
func (cc *ClientConn) contextWithTimeout(ctx context.Context, d time.Duration) (context.Context, context.CancelFunc) {
2024-05-14 13:07:09 +00:00
if cc.syncHooks != nil {
2024-05-14 13:07:09 +00:00
return cc.syncHooks.contextWithTimeout(ctx, d)
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
return context.WithTimeout(ctx, d)
2024-02-18 10:42:21 +00:00
}
// clientStream is the state for a single HTTP/2 stream. One of these
2024-02-18 10:42:21 +00:00
// is created for each Transport.RoundTrip call.
2024-02-18 10:42:21 +00:00
type clientStream struct {
cc *ClientConn
// Fields of Request that we may access even after the response body is closed.
ctx context.Context
2024-02-18 10:42:21 +00:00
reqCancel <-chan struct{}
trace *httptrace.ClientTrace // or nil
ID uint32
bufPipe pipe // buffered pipe with the flow-controlled response payload
2024-02-18 10:42:21 +00:00
requestedGzip bool
isHead bool
2024-02-18 10:42:21 +00:00
abortOnce sync.Once
abort chan struct{} // closed to signal stream should end immediately
abortErr error // set if abort is closed
2024-02-18 10:42:21 +00:00
peerClosed chan struct{} // closed when the peer sends an END_STREAM flag
donec chan struct{} // closed after the stream is in the closed state
on100 chan struct{} // buffered; written to if a 100 is received
respHeaderRecv chan struct{} // closed when headers are received
res *http.Response // set if respHeaderRecv is closed
flow outflow // guarded by cc.mu
inflow inflow // guarded by cc.mu
bytesRemain int64 // -1 means unknown; owned by transportResponseBody.Read
2024-02-18 10:42:21 +00:00
readErr error // sticky read error; owned by transportResponseBody.Read
2024-02-18 10:42:21 +00:00
reqBody io.ReadCloser
reqBodyContentLength int64 // -1 means unknown
reqBodyClosed chan struct{} // guarded by cc.mu; non-nil on Close, closed when done
2024-02-18 10:42:21 +00:00
// owned by writeRequest:
2024-02-18 10:42:21 +00:00
sentEndStream bool // sent an END_STREAM flag to the peer
sentHeaders bool
2024-02-18 10:42:21 +00:00
// owned by clientConnReadLoop:
firstByte bool // got the first response byte
pastHeaders bool // got first MetaHeadersFrame (actual headers)
pastTrailers bool // got optional second MetaHeadersFrame (trailers)
num1xx uint8 // number of 1xx responses seen
readClosed bool // peer sent an END_STREAM flag
readAborted bool // read loop reset the stream
trailer http.Header // accumulated trailers
2024-02-18 10:42:21 +00:00
resTrailer *http.Header // client's Response.Trailer
2024-02-18 10:42:21 +00:00
}
var got1xxFuncForTests func(int, textproto.MIMEHeader) error
// get1xxTraceFunc returns the value of request's httptrace.ClientTrace.Got1xxResponse func,
2024-02-18 10:42:21 +00:00
// if any. It returns nil if not set or if the Go version is too old.
2024-02-18 10:42:21 +00:00
func (cs *clientStream) get1xxTraceFunc() func(int, textproto.MIMEHeader) error {
2024-02-18 10:42:21 +00:00
if fn := got1xxFuncForTests; fn != nil {
2024-02-18 10:42:21 +00:00
return fn
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return traceGot1xxResponseFunc(cs.trace)
2024-02-18 10:42:21 +00:00
}
func (cs *clientStream) abortStream(err error) {
2024-02-18 10:42:21 +00:00
cs.cc.mu.Lock()
2024-02-18 10:42:21 +00:00
defer cs.cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
cs.abortStreamLocked(err)
2024-02-18 10:42:21 +00:00
}
func (cs *clientStream) abortStreamLocked(err error) {
2024-02-18 10:42:21 +00:00
cs.abortOnce.Do(func() {
2024-02-18 10:42:21 +00:00
cs.abortErr = err
2024-02-18 10:42:21 +00:00
close(cs.abort)
2024-02-18 10:42:21 +00:00
})
2024-02-18 10:42:21 +00:00
if cs.reqBody != nil {
2024-02-18 10:42:21 +00:00
cs.closeReqBodyLocked()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
// TODO(dneil): Clean up tests where cs.cc.cond is nil.
2024-02-18 10:42:21 +00:00
if cs.cc.cond != nil {
2024-02-18 10:42:21 +00:00
// Wake up writeRequestBody if it is waiting on flow control.
2024-05-14 13:07:09 +00:00
cs.cc.condBroadcast()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func (cs *clientStream) abortRequestBodyWrite() {
2024-02-18 10:42:21 +00:00
cc := cs.cc
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
if cs.reqBody != nil && cs.reqBodyClosed == nil {
2024-02-18 10:42:21 +00:00
cs.closeReqBodyLocked()
2024-05-14 13:07:09 +00:00
cc.condBroadcast()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func (cs *clientStream) closeReqBodyLocked() {
2024-02-18 10:42:21 +00:00
if cs.reqBodyClosed != nil {
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cs.reqBodyClosed = make(chan struct{})
2024-02-18 10:42:21 +00:00
reqBodyClosed := cs.reqBodyClosed
2024-05-14 13:07:09 +00:00
cs.cc.goRun(func() {
2024-02-18 10:42:21 +00:00
cs.reqBody.Close()
2024-02-18 10:42:21 +00:00
close(reqBodyClosed)
2024-05-14 13:07:09 +00:00
})
2024-02-18 10:42:21 +00:00
}
type stickyErrWriter struct {
conn net.Conn
2024-02-18 10:42:21 +00:00
timeout time.Duration
err *error
2024-02-18 10:42:21 +00:00
}
func (sew stickyErrWriter) Write(p []byte) (n int, err error) {
2024-02-18 10:42:21 +00:00
if *sew.err != nil {
2024-02-18 10:42:21 +00:00
return 0, *sew.err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
for {
2024-02-18 10:42:21 +00:00
if sew.timeout != 0 {
2024-02-18 10:42:21 +00:00
sew.conn.SetWriteDeadline(time.Now().Add(sew.timeout))
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
nn, err := sew.conn.Write(p[n:])
2024-02-18 10:42:21 +00:00
n += nn
2024-02-18 10:42:21 +00:00
if n < len(p) && nn > 0 && errors.Is(err, os.ErrDeadlineExceeded) {
2024-02-18 10:42:21 +00:00
// Keep extending the deadline so long as we're making progress.
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if sew.timeout != 0 {
2024-02-18 10:42:21 +00:00
sew.conn.SetWriteDeadline(time.Time{})
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
*sew.err = err
2024-02-18 10:42:21 +00:00
return n, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// noCachedConnError is the concrete type of ErrNoCachedConn, which
2024-02-18 10:42:21 +00:00
// needs to be detected by net/http regardless of whether it's its
2024-02-18 10:42:21 +00:00
// bundled version (in h2_bundle.go with a rewritten type name) or
2024-02-18 10:42:21 +00:00
// from a user's x/net/http2. As such, as it has a unique method name
2024-02-18 10:42:21 +00:00
// (IsHTTP2NoCachedConnError) that net/http sniffs for via func
2024-02-18 10:42:21 +00:00
// isNoCachedConnError.
2024-02-18 10:42:21 +00:00
type noCachedConnError struct{}
func (noCachedConnError) IsHTTP2NoCachedConnError() {}
func (noCachedConnError) Error() string { return "http2: no cached connection was available" }
2024-02-18 10:42:21 +00:00
// isNoCachedConnError reports whether err is of type noCachedConnError
2024-02-18 10:42:21 +00:00
// or its equivalent renamed type in net/http2's h2_bundle.go. Both types
2024-02-18 10:42:21 +00:00
// may coexist in the same running program.
2024-02-18 10:42:21 +00:00
func isNoCachedConnError(err error) bool {
2024-02-18 10:42:21 +00:00
_, ok := err.(interface{ IsHTTP2NoCachedConnError() })
2024-02-18 10:42:21 +00:00
return ok
2024-02-18 10:42:21 +00:00
}
var ErrNoCachedConn error = noCachedConnError{}
// RoundTripOpt are options for the Transport.RoundTripOpt method.
2024-02-18 10:42:21 +00:00
type RoundTripOpt struct {
2024-02-18 10:42:21 +00:00
// OnlyCachedConn controls whether RoundTripOpt may
2024-02-18 10:42:21 +00:00
// create a new TCP connection. If set true and
2024-02-18 10:42:21 +00:00
// no cached connection is available, RoundTripOpt
2024-02-18 10:42:21 +00:00
// will return ErrNoCachedConn.
2024-02-18 10:42:21 +00:00
OnlyCachedConn bool
}
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
2024-02-18 10:42:21 +00:00
return t.RoundTripOpt(req, RoundTripOpt{})
2024-02-18 10:42:21 +00:00
}
// authorityAddr returns a given authority (a host/IP, or host:port / ip:port)
2024-02-18 10:42:21 +00:00
// and returns a host:port. The port 443 is added if needed.
2024-02-18 10:42:21 +00:00
func authorityAddr(scheme string, authority string) (addr string) {
2024-02-18 10:42:21 +00:00
host, port, err := net.SplitHostPort(authority)
2024-02-18 10:42:21 +00:00
if err != nil { // authority didn't have a port
2024-02-18 10:42:21 +00:00
host = authority
2024-02-18 10:42:21 +00:00
port = ""
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if port == "" { // authority's port was empty
2024-02-18 10:42:21 +00:00
port = "443"
2024-02-18 10:42:21 +00:00
if scheme == "http" {
2024-02-18 10:42:21 +00:00
port = "80"
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if a, err := idna.ToASCII(host); err == nil {
2024-02-18 10:42:21 +00:00
host = a
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
// IPv6 address literal, without a port:
2024-02-18 10:42:21 +00:00
if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
2024-02-18 10:42:21 +00:00
return host + ":" + port
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return net.JoinHostPort(host, port)
2024-02-18 10:42:21 +00:00
}
// RoundTripOpt is like RoundTrip, but takes options.
2024-02-18 10:42:21 +00:00
func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) {
2024-02-18 10:42:21 +00:00
if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) {
2024-02-18 10:42:21 +00:00
return nil, errors.New("http2: unsupported scheme")
2024-02-18 10:42:21 +00:00
}
addr := authorityAddr(req.URL.Scheme, req.URL.Host)
2024-02-18 10:42:21 +00:00
for retry := 0; ; retry++ {
2024-02-18 10:42:21 +00:00
cc, err := t.connPool().GetClientConn(req, addr)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
t.vlogf("http2: Transport failed to get client conn for %s: %v", addr, err)
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
reused := !atomic.CompareAndSwapUint32(&cc.reused, 0, 1)
2024-02-18 10:42:21 +00:00
traceGotConn(req, cc, reused)
2024-02-18 10:42:21 +00:00
res, err := cc.RoundTrip(req)
2024-02-18 10:42:21 +00:00
if err != nil && retry <= 6 {
2024-02-18 10:42:21 +00:00
roundTripErr := err
2024-02-18 10:42:21 +00:00
if req, err = shouldRetryRequest(req, err); err == nil {
2024-02-18 10:42:21 +00:00
// After the first retry, do exponential backoff with 10% jitter.
2024-02-18 10:42:21 +00:00
if retry == 0 {
2024-02-18 10:42:21 +00:00
t.vlogf("RoundTrip retrying after failure: %v", roundTripErr)
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
backoff := float64(uint(1) << (uint(retry) - 1))
2024-02-18 10:42:21 +00:00
backoff += backoff * (0.1 * mathrand.Float64())
2024-02-18 10:42:21 +00:00
d := time.Second * time.Duration(backoff)
2024-05-14 13:07:09 +00:00
var tm timer
2024-05-14 13:07:09 +00:00
if t.syncHooks != nil {
2024-05-14 13:07:09 +00:00
tm = t.syncHooks.newTimer(d)
2024-05-14 13:07:09 +00:00
t.syncHooks.blockUntil(func() bool {
2024-05-14 13:07:09 +00:00
select {
2024-05-14 13:07:09 +00:00
case <-tm.C():
2024-05-14 13:07:09 +00:00
case <-req.Context().Done():
2024-05-14 13:07:09 +00:00
default:
2024-05-14 13:07:09 +00:00
return false
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
return true
2024-05-14 13:07:09 +00:00
})
2024-05-14 13:07:09 +00:00
} else {
2024-05-14 13:07:09 +00:00
tm = newTimeTimer(d)
2024-05-14 13:07:09 +00:00
}
2024-02-18 10:42:21 +00:00
select {
2024-05-14 13:07:09 +00:00
case <-tm.C():
2024-02-18 10:42:21 +00:00
t.vlogf("RoundTrip retrying after failure: %v", roundTripErr)
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
case <-req.Context().Done():
2024-05-14 13:07:09 +00:00
tm.Stop()
2024-02-18 10:42:21 +00:00
err = req.Context().Err()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
t.vlogf("RoundTrip failure: %v", err)
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return res, nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// CloseIdleConnections closes any connections which were previously
2024-02-18 10:42:21 +00:00
// connected from previous requests but are now sitting idle.
2024-02-18 10:42:21 +00:00
// It does not interrupt any connections currently in use.
2024-02-18 10:42:21 +00:00
func (t *Transport) CloseIdleConnections() {
2024-02-18 10:42:21 +00:00
if cp, ok := t.connPool().(clientConnPoolIdleCloser); ok {
2024-02-18 10:42:21 +00:00
cp.closeIdleConnections()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
var (
errClientConnClosed = errors.New("http2: client conn is closed")
errClientConnUnusable = errors.New("http2: client conn not usable")
2024-02-18 10:42:21 +00:00
errClientConnGotGoAway = errors.New("http2: Transport received Server's graceful shutdown GOAWAY")
)
// shouldRetryRequest is called by RoundTrip when a request fails to get
2024-02-18 10:42:21 +00:00
// response headers. It is always called with a non-nil error.
2024-02-18 10:42:21 +00:00
// It returns either a request to retry (either the same request, or a
2024-02-18 10:42:21 +00:00
// modified clone), or an error if the request can't be replayed.
2024-02-18 10:42:21 +00:00
func shouldRetryRequest(req *http.Request, err error) (*http.Request, error) {
2024-02-18 10:42:21 +00:00
if !canRetryError(err) {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
// If the Body is nil (or http.NoBody), it's safe to reuse
2024-02-18 10:42:21 +00:00
// this request and its Body.
2024-02-18 10:42:21 +00:00
if req.Body == nil || req.Body == http.NoBody {
2024-02-18 10:42:21 +00:00
return req, nil
2024-02-18 10:42:21 +00:00
}
// If the request body can be reset back to its original
2024-02-18 10:42:21 +00:00
// state via the optional req.GetBody, do that.
2024-02-18 10:42:21 +00:00
if req.GetBody != nil {
2024-02-18 10:42:21 +00:00
body, err := req.GetBody()
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
newReq := *req
2024-02-18 10:42:21 +00:00
newReq.Body = body
2024-02-18 10:42:21 +00:00
return &newReq, nil
2024-02-18 10:42:21 +00:00
}
// The Request.Body can't reset back to the beginning, but we
2024-02-18 10:42:21 +00:00
// don't seem to have started to read from it yet, so reuse
2024-02-18 10:42:21 +00:00
// the request directly.
2024-02-18 10:42:21 +00:00
if err == errClientConnUnusable {
2024-02-18 10:42:21 +00:00
return req, nil
2024-02-18 10:42:21 +00:00
}
return nil, fmt.Errorf("http2: Transport: cannot retry err [%v] after Request.Body was written; define Request.GetBody to avoid this error", err)
2024-02-18 10:42:21 +00:00
}
func canRetryError(err error) bool {
2024-02-18 10:42:21 +00:00
if err == errClientConnUnusable || err == errClientConnGotGoAway {
2024-02-18 10:42:21 +00:00
return true
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if se, ok := err.(StreamError); ok {
2024-02-18 10:42:21 +00:00
if se.Code == ErrCodeProtocol && se.Cause == errFromPeer {
2024-02-18 10:42:21 +00:00
// See golang/go#47635, golang/go#42777
2024-02-18 10:42:21 +00:00
return true
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return se.Code == ErrCodeRefusedStream
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return false
2024-02-18 10:42:21 +00:00
}
func (t *Transport) dialClientConn(ctx context.Context, addr string, singleUse bool) (*ClientConn, error) {
2024-05-14 13:07:09 +00:00
if t.syncHooks != nil {
2024-05-14 13:07:09 +00:00
return t.newClientConn(nil, singleUse, t.syncHooks)
2024-05-14 13:07:09 +00:00
}
2024-02-18 10:42:21 +00:00
host, _, err := net.SplitHostPort(addr)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
tconn, err := t.dialTLS(ctx, "tcp", addr, t.newTLSConfig(host))
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
return t.newClientConn(tconn, singleUse, nil)
2024-02-18 10:42:21 +00:00
}
func (t *Transport) newTLSConfig(host string) *tls.Config {
2024-02-18 10:42:21 +00:00
cfg := new(tls.Config)
2024-02-18 10:42:21 +00:00
if t.TLSClientConfig != nil {
2024-02-18 10:42:21 +00:00
*cfg = *t.TLSClientConfig.Clone()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if !strSliceContains(cfg.NextProtos, NextProtoTLS) {
2024-02-18 10:42:21 +00:00
cfg.NextProtos = append([]string{NextProtoTLS}, cfg.NextProtos...)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if cfg.ServerName == "" {
2024-02-18 10:42:21 +00:00
cfg.ServerName = host
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return cfg
2024-02-18 10:42:21 +00:00
}
func (t *Transport) dialTLS(ctx context.Context, network, addr string, tlsCfg *tls.Config) (net.Conn, error) {
2024-02-18 10:42:21 +00:00
if t.DialTLSContext != nil {
2024-02-18 10:42:21 +00:00
return t.DialTLSContext(ctx, network, addr, tlsCfg)
2024-02-18 10:42:21 +00:00
} else if t.DialTLS != nil {
2024-02-18 10:42:21 +00:00
return t.DialTLS(network, addr, tlsCfg)
2024-02-18 10:42:21 +00:00
}
tlsCn, err := t.dialTLSWithContext(ctx, network, addr, tlsCfg)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
state := tlsCn.ConnectionState()
2024-02-18 10:42:21 +00:00
if p := state.NegotiatedProtocol; p != NextProtoTLS {
2024-02-18 10:42:21 +00:00
return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, NextProtoTLS)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if !state.NegotiatedProtocolIsMutual {
2024-02-18 10:42:21 +00:00
return nil, errors.New("http2: could not negotiate protocol mutually")
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return tlsCn, nil
2024-02-18 10:42:21 +00:00
}
// disableKeepAlives reports whether connections should be closed as
2024-02-18 10:42:21 +00:00
// soon as possible after handling the first request.
2024-02-18 10:42:21 +00:00
func (t *Transport) disableKeepAlives() bool {
2024-02-18 10:42:21 +00:00
return t.t1 != nil && t.t1.DisableKeepAlives
2024-02-18 10:42:21 +00:00
}
func (t *Transport) expectContinueTimeout() time.Duration {
2024-02-18 10:42:21 +00:00
if t.t1 == nil {
2024-02-18 10:42:21 +00:00
return 0
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return t.t1.ExpectContinueTimeout
2024-02-18 10:42:21 +00:00
}
func (t *Transport) maxDecoderHeaderTableSize() uint32 {
2024-02-18 10:42:21 +00:00
if v := t.MaxDecoderHeaderTableSize; v > 0 {
2024-02-18 10:42:21 +00:00
return v
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return initialHeaderTableSize
2024-02-18 10:42:21 +00:00
}
func (t *Transport) maxEncoderHeaderTableSize() uint32 {
2024-02-18 10:42:21 +00:00
if v := t.MaxEncoderHeaderTableSize; v > 0 {
2024-02-18 10:42:21 +00:00
return v
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return initialHeaderTableSize
2024-02-18 10:42:21 +00:00
}
func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) {
2024-05-14 13:07:09 +00:00
return t.newClientConn(c, t.disableKeepAlives(), nil)
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
func (t *Transport) newClientConn(c net.Conn, singleUse bool, hooks *testSyncHooks) (*ClientConn, error) {
2024-02-18 10:42:21 +00:00
cc := &ClientConn{
t: t,
tconn: c,
readerDone: make(chan struct{}),
nextStreamID: 1,
maxFrameSize: 16 << 10, // spec default
initialWindowSize: 65535, // spec default
maxConcurrentStreams: initialMaxConcurrentStreams, // "infinite", per spec. Use a smaller value until we have received server settings.
peerMaxHeaderListSize: 0xffffffffffffffff, // "infinite", per spec. Use 2^64-1 instead.
streams: make(map[uint32]*clientStream),
singleUse: singleUse,
wantSettingsAck: true,
pings: make(map[[8]byte]chan struct{}),
reqHeaderMu: make(chan struct{}, 1),
syncHooks: hooks,
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
if hooks != nil {
2024-05-14 13:07:09 +00:00
hooks.newclientconn(cc)
2024-05-14 13:07:09 +00:00
c = cc.tconn
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if d := t.idleConnTimeout(); d != 0 {
2024-02-18 10:42:21 +00:00
cc.idleTimeout = d
2024-05-14 13:07:09 +00:00
cc.idleTimer = cc.afterFunc(d, cc.onIdleTimeout)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if VerboseLogs {
2024-02-18 10:42:21 +00:00
t.vlogf("http2: Transport creating client conn %p to %v", cc, c.RemoteAddr())
2024-02-18 10:42:21 +00:00
}
cc.cond = sync.NewCond(&cc.mu)
2024-02-18 10:42:21 +00:00
cc.flow.add(int32(initialWindowSize))
// TODO: adjust this writer size to account for frame size +
2024-02-18 10:42:21 +00:00
// MTU + crypto/tls record padding.
2024-02-18 10:42:21 +00:00
cc.bw = bufio.NewWriter(stickyErrWriter{
conn: c,
2024-02-18 10:42:21 +00:00
timeout: t.WriteByteTimeout,
err: &cc.werr,
2024-02-18 10:42:21 +00:00
})
2024-02-18 10:42:21 +00:00
cc.br = bufio.NewReader(c)
2024-02-18 10:42:21 +00:00
cc.fr = NewFramer(cc.bw, cc.br)
2024-02-18 10:42:21 +00:00
if t.maxFrameReadSize() != 0 {
2024-02-18 10:42:21 +00:00
cc.fr.SetMaxReadFrameSize(t.maxFrameReadSize())
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if t.CountError != nil {
2024-02-18 10:42:21 +00:00
cc.fr.countError = t.CountError
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
maxHeaderTableSize := t.maxDecoderHeaderTableSize()
2024-02-18 10:42:21 +00:00
cc.fr.ReadMetaHeaders = hpack.NewDecoder(maxHeaderTableSize, nil)
2024-02-18 10:42:21 +00:00
cc.fr.MaxHeaderListSize = t.maxHeaderListSize()
cc.henc = hpack.NewEncoder(&cc.hbuf)
2024-02-18 10:42:21 +00:00
cc.henc.SetMaxDynamicTableSizeLimit(t.maxEncoderHeaderTableSize())
2024-02-18 10:42:21 +00:00
cc.peerMaxHeaderTableSize = initialHeaderTableSize
if t.AllowHTTP {
2024-02-18 10:42:21 +00:00
cc.nextStreamID = 3
2024-02-18 10:42:21 +00:00
}
if cs, ok := c.(connectionStater); ok {
2024-02-18 10:42:21 +00:00
state := cs.ConnectionState()
2024-02-18 10:42:21 +00:00
cc.tlsState = &state
2024-02-18 10:42:21 +00:00
}
initialSettings := []Setting{
2024-02-18 10:42:21 +00:00
{ID: SettingEnablePush, Val: 0},
2024-02-18 10:42:21 +00:00
{ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow},
}
2024-02-18 10:42:21 +00:00
if max := t.maxFrameReadSize(); max != 0 {
2024-02-18 10:42:21 +00:00
initialSettings = append(initialSettings, Setting{ID: SettingMaxFrameSize, Val: max})
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if max := t.maxHeaderListSize(); max != 0 {
2024-02-18 10:42:21 +00:00
initialSettings = append(initialSettings, Setting{ID: SettingMaxHeaderListSize, Val: max})
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if maxHeaderTableSize != initialHeaderTableSize {
2024-02-18 10:42:21 +00:00
initialSettings = append(initialSettings, Setting{ID: SettingHeaderTableSize, Val: maxHeaderTableSize})
2024-02-18 10:42:21 +00:00
}
cc.bw.Write(clientPreface)
2024-02-18 10:42:21 +00:00
cc.fr.WriteSettings(initialSettings...)
2024-02-18 10:42:21 +00:00
cc.fr.WriteWindowUpdate(0, transportDefaultConnFlow)
2024-02-18 10:42:21 +00:00
cc.inflow.init(transportDefaultConnFlow + initialWindowSize)
2024-02-18 10:42:21 +00:00
cc.bw.Flush()
2024-02-18 10:42:21 +00:00
if cc.werr != nil {
2024-02-18 10:42:21 +00:00
cc.Close()
2024-02-18 10:42:21 +00:00
return nil, cc.werr
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
cc.goRun(cc.readLoop)
2024-02-18 10:42:21 +00:00
return cc, nil
2024-02-18 10:42:21 +00:00
}
func (cc *ClientConn) healthCheck() {
2024-02-18 10:42:21 +00:00
pingTimeout := cc.t.pingTimeout()
2024-02-18 10:42:21 +00:00
// We don't need to periodically ping in the health check, because the readLoop of ClientConn will
2024-02-18 10:42:21 +00:00
// trigger the healthCheck again if there is no frame received.
2024-05-14 13:07:09 +00:00
ctx, cancel := cc.contextWithTimeout(context.Background(), pingTimeout)
2024-02-18 10:42:21 +00:00
defer cancel()
2024-02-18 10:42:21 +00:00
cc.vlogf("http2: Transport sending health check")
2024-02-18 10:42:21 +00:00
err := cc.Ping(ctx)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
cc.vlogf("http2: Transport health check failure: %v", err)
2024-02-18 10:42:21 +00:00
cc.closeForLostPing()
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
cc.vlogf("http2: Transport health check success")
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// SetDoNotReuse marks cc as not reusable for future HTTP requests.
2024-02-18 10:42:21 +00:00
func (cc *ClientConn) SetDoNotReuse() {
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
cc.doNotReuse = true
2024-02-18 10:42:21 +00:00
}
func (cc *ClientConn) setGoAway(f *GoAwayFrame) {
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.mu.Unlock()
old := cc.goAway
2024-02-18 10:42:21 +00:00
cc.goAway = f
// Merge the previous and current GoAway error frames.
2024-02-18 10:42:21 +00:00
if cc.goAwayDebug == "" {
2024-02-18 10:42:21 +00:00
cc.goAwayDebug = string(f.DebugData())
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if old != nil && old.ErrCode != ErrCodeNo {
2024-02-18 10:42:21 +00:00
cc.goAway.ErrCode = old.ErrCode
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
last := f.LastStreamID
2024-02-18 10:42:21 +00:00
for streamID, cs := range cc.streams {
2024-05-14 13:07:09 +00:00
if streamID <= last {
2024-05-14 13:07:09 +00:00
// The server's GOAWAY indicates that it received this stream.
2024-05-14 13:07:09 +00:00
// It will either finish processing it, or close the connection
2024-05-14 13:07:09 +00:00
// without doing so. Either way, leave the stream alone for now.
2024-05-14 13:07:09 +00:00
continue
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
if streamID == 1 && cc.goAway.ErrCode != ErrCodeNo {
2024-05-14 13:07:09 +00:00
// Don't retry the first stream on a connection if we get a non-NO error.
2024-05-14 13:07:09 +00:00
// If the server is sending an error on a new connection,
2024-05-14 13:07:09 +00:00
// retrying the request on a new one probably isn't going to work.
2024-05-14 13:07:09 +00:00
cs.abortStreamLocked(fmt.Errorf("http2: Transport received GOAWAY from server ErrCode:%v", cc.goAway.ErrCode))
2024-05-14 13:07:09 +00:00
} else {
2024-05-14 13:07:09 +00:00
// Aborting the stream with errClentConnGotGoAway indicates that
2024-05-14 13:07:09 +00:00
// the request should be retried on a new connection.
2024-02-18 10:42:21 +00:00
cs.abortStreamLocked(errClientConnGotGoAway)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// CanTakeNewRequest reports whether the connection can take a new request,
2024-02-18 10:42:21 +00:00
// meaning it has not been closed or received or sent a GOAWAY.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// If the caller is going to immediately make a new request on this
2024-02-18 10:42:21 +00:00
// connection, use ReserveNewRequest instead.
2024-02-18 10:42:21 +00:00
func (cc *ClientConn) CanTakeNewRequest() bool {
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
return cc.canTakeNewRequestLocked()
2024-02-18 10:42:21 +00:00
}
// ReserveNewRequest is like CanTakeNewRequest but also reserves a
2024-02-18 10:42:21 +00:00
// concurrent stream in cc. The reservation is decremented on the
2024-02-18 10:42:21 +00:00
// next call to RoundTrip.
2024-02-18 10:42:21 +00:00
func (cc *ClientConn) ReserveNewRequest() bool {
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
if st := cc.idleStateLocked(); !st.canTakeNewRequest {
2024-02-18 10:42:21 +00:00
return false
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.streamsReserved++
2024-02-18 10:42:21 +00:00
return true
2024-02-18 10:42:21 +00:00
}
// ClientConnState describes the state of a ClientConn.
2024-02-18 10:42:21 +00:00
type ClientConnState struct {
2024-02-18 10:42:21 +00:00
// Closed is whether the connection is closed.
2024-02-18 10:42:21 +00:00
Closed bool
// Closing is whether the connection is in the process of
2024-02-18 10:42:21 +00:00
// closing. It may be closing due to shutdown, being a
2024-02-18 10:42:21 +00:00
// single-use connection, being marked as DoNotReuse, or
2024-02-18 10:42:21 +00:00
// having received a GOAWAY frame.
2024-02-18 10:42:21 +00:00
Closing bool
// StreamsActive is how many streams are active.
2024-02-18 10:42:21 +00:00
StreamsActive int
// StreamsReserved is how many streams have been reserved via
2024-02-18 10:42:21 +00:00
// ClientConn.ReserveNewRequest.
2024-02-18 10:42:21 +00:00
StreamsReserved int
// StreamsPending is how many requests have been sent in excess
2024-02-18 10:42:21 +00:00
// of the peer's advertised MaxConcurrentStreams setting and
2024-02-18 10:42:21 +00:00
// are waiting for other streams to complete.
2024-02-18 10:42:21 +00:00
StreamsPending int
// MaxConcurrentStreams is how many concurrent streams the
2024-02-18 10:42:21 +00:00
// peer advertised as acceptable. Zero means no SETTINGS
2024-02-18 10:42:21 +00:00
// frame has been received yet.
2024-02-18 10:42:21 +00:00
MaxConcurrentStreams uint32
// LastIdle, if non-zero, is when the connection last
2024-02-18 10:42:21 +00:00
// transitioned to idle state.
2024-02-18 10:42:21 +00:00
LastIdle time.Time
}
// State returns a snapshot of cc's state.
2024-02-18 10:42:21 +00:00
func (cc *ClientConn) State() ClientConnState {
2024-02-18 10:42:21 +00:00
cc.wmu.Lock()
2024-02-18 10:42:21 +00:00
maxConcurrent := cc.maxConcurrentStreams
2024-02-18 10:42:21 +00:00
if !cc.seenSettings {
2024-02-18 10:42:21 +00:00
maxConcurrent = 0
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.wmu.Unlock()
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
return ClientConnState{
Closed: cc.closed,
Closing: cc.closing || cc.singleUse || cc.doNotReuse || cc.goAway != nil,
StreamsActive: len(cc.streams),
StreamsReserved: cc.streamsReserved,
StreamsPending: cc.pendingRequests,
LastIdle: cc.lastIdle,
2024-02-18 10:42:21 +00:00
MaxConcurrentStreams: maxConcurrent,
}
2024-02-18 10:42:21 +00:00
}
// clientConnIdleState describes the suitability of a client
2024-02-18 10:42:21 +00:00
// connection to initiate a new RoundTrip request.
2024-02-18 10:42:21 +00:00
type clientConnIdleState struct {
canTakeNewRequest bool
}
func (cc *ClientConn) idleState() clientConnIdleState {
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
return cc.idleStateLocked()
2024-02-18 10:42:21 +00:00
}
func (cc *ClientConn) idleStateLocked() (st clientConnIdleState) {
2024-02-18 10:42:21 +00:00
if cc.singleUse && cc.nextStreamID > 1 {
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
var maxConcurrentOkay bool
2024-02-18 10:42:21 +00:00
if cc.t.StrictMaxConcurrentStreams {
2024-02-18 10:42:21 +00:00
// We'll tell the caller we can take a new request to
2024-02-18 10:42:21 +00:00
// prevent the caller from dialing a new TCP
2024-02-18 10:42:21 +00:00
// connection, but then we'll block later before
2024-02-18 10:42:21 +00:00
// writing it.
2024-02-18 10:42:21 +00:00
maxConcurrentOkay = true
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
maxConcurrentOkay = int64(len(cc.streams)+cc.streamsReserved+1) <= int64(cc.maxConcurrentStreams)
2024-02-18 10:42:21 +00:00
}
st.canTakeNewRequest = cc.goAway == nil && !cc.closed && !cc.closing && maxConcurrentOkay &&
2024-02-18 10:42:21 +00:00
!cc.doNotReuse &&
2024-02-18 10:42:21 +00:00
int64(cc.nextStreamID)+2*int64(cc.pendingRequests) < math.MaxInt32 &&
2024-02-18 10:42:21 +00:00
!cc.tooIdleLocked()
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
func (cc *ClientConn) canTakeNewRequestLocked() bool {
2024-02-18 10:42:21 +00:00
st := cc.idleStateLocked()
2024-02-18 10:42:21 +00:00
return st.canTakeNewRequest
2024-02-18 10:42:21 +00:00
}
// tooIdleLocked reports whether this connection has been been sitting idle
2024-02-18 10:42:21 +00:00
// for too much wall time.
2024-02-18 10:42:21 +00:00
func (cc *ClientConn) tooIdleLocked() bool {
2024-02-18 10:42:21 +00:00
// The Round(0) strips the monontonic clock reading so the
2024-02-18 10:42:21 +00:00
// times are compared based on their wall time. We don't want
2024-02-18 10:42:21 +00:00
// to reuse a connection that's been sitting idle during
2024-02-18 10:42:21 +00:00
// VM/laptop suspend if monotonic time was also frozen.
2024-02-18 10:42:21 +00:00
return cc.idleTimeout != 0 && !cc.lastIdle.IsZero() && time.Since(cc.lastIdle.Round(0)) > cc.idleTimeout
2024-02-18 10:42:21 +00:00
}
// onIdleTimeout is called from a time.AfterFunc goroutine. It will
2024-02-18 10:42:21 +00:00
// only be called when we're idle, but because we're coming from a new
2024-02-18 10:42:21 +00:00
// goroutine, there could be a new request coming in at the same time,
2024-02-18 10:42:21 +00:00
// so this simply calls the synchronized closeIfIdle to shut down this
2024-02-18 10:42:21 +00:00
// connection. The timer could just call closeIfIdle, but this is more
2024-02-18 10:42:21 +00:00
// clear.
2024-02-18 10:42:21 +00:00
func (cc *ClientConn) onIdleTimeout() {
2024-02-18 10:42:21 +00:00
cc.closeIfIdle()
2024-02-18 10:42:21 +00:00
}
func (cc *ClientConn) closeConn() {
2024-02-18 10:42:21 +00:00
t := time.AfterFunc(250*time.Millisecond, cc.forceCloseConn)
2024-02-18 10:42:21 +00:00
defer t.Stop()
2024-02-18 10:42:21 +00:00
cc.tconn.Close()
2024-02-18 10:42:21 +00:00
}
// A tls.Conn.Close can hang for a long time if the peer is unresponsive.
2024-02-18 10:42:21 +00:00
// Try to shut it down more aggressively.
2024-02-18 10:42:21 +00:00
func (cc *ClientConn) forceCloseConn() {
2024-02-18 10:42:21 +00:00
tc, ok := cc.tconn.(*tls.Conn)
2024-02-18 10:42:21 +00:00
if !ok {
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if nc := tc.NetConn(); nc != nil {
2024-02-18 10:42:21 +00:00
nc.Close()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func (cc *ClientConn) closeIfIdle() {
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
if len(cc.streams) > 0 || cc.streamsReserved > 0 {
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.closed = true
2024-02-18 10:42:21 +00:00
nextID := cc.nextStreamID
2024-02-18 10:42:21 +00:00
// TODO: do clients send GOAWAY too? maybe? Just Close:
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
if VerboseLogs {
2024-02-18 10:42:21 +00:00
cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, nextID-2)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.closeConn()
2024-02-18 10:42:21 +00:00
}
func (cc *ClientConn) isDoNotReuseAndIdle() bool {
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
return cc.doNotReuse && len(cc.streams) == 0
2024-02-18 10:42:21 +00:00
}
var shutdownEnterWaitStateHook = func() {}
// Shutdown gracefully closes the client connection, waiting for running streams to complete.
2024-02-18 10:42:21 +00:00
func (cc *ClientConn) Shutdown(ctx context.Context) error {
2024-02-18 10:42:21 +00:00
if err := cc.sendGoAway(); err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
// Wait for all in-flight streams to complete or connection to close
2024-02-18 10:42:21 +00:00
done := make(chan struct{})
2024-02-18 10:42:21 +00:00
cancelled := false // guarded by cc.mu
2024-05-14 13:07:09 +00:00
cc.goRun(func() {
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
for {
2024-02-18 10:42:21 +00:00
if len(cc.streams) == 0 || cc.closed {
2024-02-18 10:42:21 +00:00
cc.closed = true
2024-02-18 10:42:21 +00:00
close(done)
2024-02-18 10:42:21 +00:00
break
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if cancelled {
2024-02-18 10:42:21 +00:00
break
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
cc.condWait()
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
})
2024-02-18 10:42:21 +00:00
shutdownEnterWaitStateHook()
2024-02-18 10:42:21 +00:00
select {
2024-02-18 10:42:21 +00:00
case <-done:
2024-02-18 10:42:21 +00:00
cc.closeConn()
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
case <-ctx.Done():
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
// Free the goroutine above
2024-02-18 10:42:21 +00:00
cancelled = true
2024-05-14 13:07:09 +00:00
cc.condBroadcast()
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
return ctx.Err()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func (cc *ClientConn) sendGoAway() error {
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
closing := cc.closing
2024-02-18 10:42:21 +00:00
cc.closing = true
2024-02-18 10:42:21 +00:00
maxStreamID := cc.nextStreamID
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
if closing {
2024-02-18 10:42:21 +00:00
// GOAWAY sent already
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
cc.wmu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.wmu.Unlock()
2024-02-18 10:42:21 +00:00
// Send a graceful shutdown frame to server
2024-02-18 10:42:21 +00:00
if err := cc.fr.WriteGoAway(maxStreamID, ErrCodeNo, nil); err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if err := cc.bw.Flush(); err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
// Prevent new requests
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
// closes the client connection immediately. In-flight requests are interrupted.
2024-02-18 10:42:21 +00:00
// err is sent to streams.
2024-02-18 10:42:21 +00:00
func (cc *ClientConn) closeForError(err error) {
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
cc.closed = true
2024-02-18 10:42:21 +00:00
for _, cs := range cc.streams {
2024-02-18 10:42:21 +00:00
cs.abortStreamLocked(err)
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
cc.condBroadcast()
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
cc.closeConn()
2024-02-18 10:42:21 +00:00
}
// Close closes the client connection immediately.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// In-flight requests are interrupted. For a graceful shutdown, use Shutdown instead.
2024-02-18 10:42:21 +00:00
func (cc *ClientConn) Close() error {
2024-02-18 10:42:21 +00:00
err := errors.New("http2: client connection force closed via ClientConn.Close")
2024-02-18 10:42:21 +00:00
cc.closeForError(err)
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
// closes the client connection immediately. In-flight requests are interrupted.
2024-02-18 10:42:21 +00:00
func (cc *ClientConn) closeForLostPing() {
2024-02-18 10:42:21 +00:00
err := errors.New("http2: client connection lost")
2024-02-18 10:42:21 +00:00
if f := cc.t.CountError; f != nil {
2024-02-18 10:42:21 +00:00
f("conn_close_lost_ping")
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.closeForError(err)
2024-02-18 10:42:21 +00:00
}
// errRequestCanceled is a copy of net/http's errRequestCanceled because it's not
2024-02-18 10:42:21 +00:00
// exported. At least they'll be DeepEqual for h1-vs-h2 comparisons tests.
2024-02-18 10:42:21 +00:00
var errRequestCanceled = errors.New("net/http: request canceled")
func commaSeparatedTrailers(req *http.Request) (string, error) {
2024-02-18 10:42:21 +00:00
keys := make([]string, 0, len(req.Trailer))
2024-02-18 10:42:21 +00:00
for k := range req.Trailer {
2024-02-18 10:42:21 +00:00
k = canonicalHeader(k)
2024-02-18 10:42:21 +00:00
switch k {
2024-02-18 10:42:21 +00:00
case "Transfer-Encoding", "Trailer", "Content-Length":
2024-02-18 10:42:21 +00:00
return "", fmt.Errorf("invalid Trailer key %q", k)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
keys = append(keys, k)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if len(keys) > 0 {
2024-02-18 10:42:21 +00:00
sort.Strings(keys)
2024-02-18 10:42:21 +00:00
return strings.Join(keys, ","), nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return "", nil
2024-02-18 10:42:21 +00:00
}
func (cc *ClientConn) responseHeaderTimeout() time.Duration {
2024-02-18 10:42:21 +00:00
if cc.t.t1 != nil {
2024-02-18 10:42:21 +00:00
return cc.t.t1.ResponseHeaderTimeout
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
// No way to do this (yet?) with just an http2.Transport. Probably
2024-02-18 10:42:21 +00:00
// no need. Request.Cancel this is the new way. We only need to support
2024-02-18 10:42:21 +00:00
// this for compatibility with the old http.Transport fields when
2024-02-18 10:42:21 +00:00
// we're doing transparent http2.
2024-02-18 10:42:21 +00:00
return 0
2024-02-18 10:42:21 +00:00
}
// checkConnHeaders checks whether req has any invalid connection-level headers.
2024-02-18 10:42:21 +00:00
// per RFC 7540 section 8.1.2.2: Connection-Specific Header Fields.
2024-02-18 10:42:21 +00:00
// Certain headers are special-cased as okay but not transmitted later.
2024-02-18 10:42:21 +00:00
func checkConnHeaders(req *http.Request) error {
2024-02-18 10:42:21 +00:00
if v := req.Header.Get("Upgrade"); v != "" {
2024-02-18 10:42:21 +00:00
return fmt.Errorf("http2: invalid Upgrade request header: %q", req.Header["Upgrade"])
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if vv := req.Header["Transfer-Encoding"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "chunked") {
2024-02-18 10:42:21 +00:00
return fmt.Errorf("http2: invalid Transfer-Encoding request header: %q", vv)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if vv := req.Header["Connection"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && !asciiEqualFold(vv[0], "close") && !asciiEqualFold(vv[0], "keep-alive")) {
2024-02-18 10:42:21 +00:00
return fmt.Errorf("http2: invalid Connection request header: %q", vv)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
// actualContentLength returns a sanitized version of
2024-02-18 10:42:21 +00:00
// req.ContentLength, where 0 actually means zero (not unknown) and -1
2024-02-18 10:42:21 +00:00
// means unknown.
2024-02-18 10:42:21 +00:00
func actualContentLength(req *http.Request) int64 {
2024-02-18 10:42:21 +00:00
if req.Body == nil || req.Body == http.NoBody {
2024-02-18 10:42:21 +00:00
return 0
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if req.ContentLength != 0 {
2024-02-18 10:42:21 +00:00
return req.ContentLength
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return -1
2024-02-18 10:42:21 +00:00
}
func (cc *ClientConn) decrStreamReservations() {
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
cc.decrStreamReservationsLocked()
2024-02-18 10:42:21 +00:00
}
func (cc *ClientConn) decrStreamReservationsLocked() {
2024-02-18 10:42:21 +00:00
if cc.streamsReserved > 0 {
2024-02-18 10:42:21 +00:00
cc.streamsReserved--
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) {
2024-05-14 13:07:09 +00:00
return cc.roundTrip(req, nil)
2024-05-14 13:07:09 +00:00
}
func (cc *ClientConn) roundTrip(req *http.Request, streamf func(*clientStream)) (*http.Response, error) {
2024-02-18 10:42:21 +00:00
ctx := req.Context()
2024-02-18 10:42:21 +00:00
cs := &clientStream{
cc: cc,
ctx: ctx,
reqCancel: req.Cancel,
isHead: req.Method == "HEAD",
reqBody: req.Body,
2024-02-18 10:42:21 +00:00
reqBodyContentLength: actualContentLength(req),
trace: httptrace.ContextClientTrace(ctx),
peerClosed: make(chan struct{}),
abort: make(chan struct{}),
respHeaderRecv: make(chan struct{}),
donec: make(chan struct{}),
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
cc.goRun(func() {
2024-05-14 13:07:09 +00:00
cs.doRequest(req)
2024-05-14 13:07:09 +00:00
})
2024-02-18 10:42:21 +00:00
waitDone := func() error {
2024-05-14 13:07:09 +00:00
if cc.syncHooks != nil {
2024-05-14 13:07:09 +00:00
cc.syncHooks.blockUntil(func() bool {
2024-05-14 13:07:09 +00:00
select {
2024-05-14 13:07:09 +00:00
case <-cs.donec:
2024-05-14 13:07:09 +00:00
case <-ctx.Done():
2024-05-14 13:07:09 +00:00
case <-cs.reqCancel:
2024-05-14 13:07:09 +00:00
default:
2024-05-14 13:07:09 +00:00
return false
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
return true
2024-05-14 13:07:09 +00:00
})
2024-05-14 13:07:09 +00:00
}
2024-02-18 10:42:21 +00:00
select {
2024-02-18 10:42:21 +00:00
case <-cs.donec:
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
case <-ctx.Done():
2024-02-18 10:42:21 +00:00
return ctx.Err()
2024-02-18 10:42:21 +00:00
case <-cs.reqCancel:
2024-02-18 10:42:21 +00:00
return errRequestCanceled
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
handleResponseHeaders := func() (*http.Response, error) {
2024-02-18 10:42:21 +00:00
res := cs.res
2024-02-18 10:42:21 +00:00
if res.StatusCode > 299 {
2024-02-18 10:42:21 +00:00
// On error or status code 3xx, 4xx, 5xx, etc abort any
2024-02-18 10:42:21 +00:00
// ongoing write, assuming that the server doesn't care
2024-02-18 10:42:21 +00:00
// about our request body. If the server replied with 1xx or
2024-02-18 10:42:21 +00:00
// 2xx, however, then assume the server DOES potentially
2024-02-18 10:42:21 +00:00
// want our body (e.g. full-duplex streaming:
2024-02-18 10:42:21 +00:00
// golang.org/issue/13444). If it turns out the server
2024-02-18 10:42:21 +00:00
// doesn't, they'll RST_STREAM us soon enough. This is a
2024-02-18 10:42:21 +00:00
// heuristic to avoid adding knobs to Transport. Hopefully
2024-02-18 10:42:21 +00:00
// we can keep it.
2024-02-18 10:42:21 +00:00
cs.abortRequestBodyWrite()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
res.Request = req
2024-02-18 10:42:21 +00:00
res.TLS = cc.tlsState
2024-02-18 10:42:21 +00:00
if res.Body == noBody && actualContentLength(req) == 0 {
2024-02-18 10:42:21 +00:00
// If there isn't a request or response body still being
2024-02-18 10:42:21 +00:00
// written, then wait for the stream to be closed before
2024-02-18 10:42:21 +00:00
// RoundTrip returns.
2024-02-18 10:42:21 +00:00
if err := waitDone(); err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return res, nil
2024-02-18 10:42:21 +00:00
}
cancelRequest := func(cs *clientStream, err error) error {
2024-02-18 10:42:21 +00:00
cs.cc.mu.Lock()
2024-02-18 10:42:21 +00:00
bodyClosed := cs.reqBodyClosed
2024-02-18 10:42:21 +00:00
cs.cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
// Wait for the request body to be closed.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// If nothing closed the body before now, abortStreamLocked
2024-02-18 10:42:21 +00:00
// will have started a goroutine to close it.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// Closing the body before returning avoids a race condition
2024-02-18 10:42:21 +00:00
// with net/http checking its readTrackingBody to see if the
2024-02-18 10:42:21 +00:00
// body was read from or closed. See golang/go#60041.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// The body is closed in a separate goroutine without the
2024-02-18 10:42:21 +00:00
// connection mutex held, but dropping the mutex before waiting
2024-02-18 10:42:21 +00:00
// will keep us from holding it indefinitely if the body
2024-02-18 10:42:21 +00:00
// close is slow for some reason.
2024-02-18 10:42:21 +00:00
if bodyClosed != nil {
2024-02-18 10:42:21 +00:00
<-bodyClosed
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
if streamf != nil {
2024-05-14 13:07:09 +00:00
streamf(cs)
2024-05-14 13:07:09 +00:00
}
2024-02-18 10:42:21 +00:00
for {
2024-05-14 13:07:09 +00:00
if cc.syncHooks != nil {
2024-05-14 13:07:09 +00:00
cc.syncHooks.blockUntil(func() bool {
2024-05-14 13:07:09 +00:00
select {
2024-05-14 13:07:09 +00:00
case <-cs.respHeaderRecv:
2024-05-14 13:07:09 +00:00
case <-cs.abort:
2024-05-14 13:07:09 +00:00
case <-ctx.Done():
2024-05-14 13:07:09 +00:00
case <-cs.reqCancel:
2024-05-14 13:07:09 +00:00
default:
2024-05-14 13:07:09 +00:00
return false
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
return true
2024-05-14 13:07:09 +00:00
})
2024-05-14 13:07:09 +00:00
}
2024-02-18 10:42:21 +00:00
select {
2024-02-18 10:42:21 +00:00
case <-cs.respHeaderRecv:
2024-02-18 10:42:21 +00:00
return handleResponseHeaders()
2024-02-18 10:42:21 +00:00
case <-cs.abort:
2024-02-18 10:42:21 +00:00
select {
2024-02-18 10:42:21 +00:00
case <-cs.respHeaderRecv:
2024-02-18 10:42:21 +00:00
// If both cs.respHeaderRecv and cs.abort are signaling,
2024-02-18 10:42:21 +00:00
// pick respHeaderRecv. The server probably wrote the
2024-02-18 10:42:21 +00:00
// response and immediately reset the stream.
2024-02-18 10:42:21 +00:00
// golang.org/issue/49645
2024-02-18 10:42:21 +00:00
return handleResponseHeaders()
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
waitDone()
2024-02-18 10:42:21 +00:00
return nil, cs.abortErr
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
case <-ctx.Done():
2024-02-18 10:42:21 +00:00
err := ctx.Err()
2024-02-18 10:42:21 +00:00
cs.abortStream(err)
2024-02-18 10:42:21 +00:00
return nil, cancelRequest(cs, err)
2024-02-18 10:42:21 +00:00
case <-cs.reqCancel:
2024-02-18 10:42:21 +00:00
cs.abortStream(errRequestCanceled)
2024-02-18 10:42:21 +00:00
return nil, cancelRequest(cs, errRequestCanceled)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// doRequest runs for the duration of the request lifetime.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// It sends the request and performs post-request cleanup (closing Request.Body, etc.).
2024-02-18 10:42:21 +00:00
func (cs *clientStream) doRequest(req *http.Request) {
2024-02-18 10:42:21 +00:00
err := cs.writeRequest(req)
2024-02-18 10:42:21 +00:00
cs.cleanupWriteRequest(err)
2024-02-18 10:42:21 +00:00
}
// writeRequest sends a request.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// It returns nil after the request is written, the response read,
2024-02-18 10:42:21 +00:00
// and the request stream is half-closed by the peer.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// It returns non-nil if the request ends otherwise.
2024-02-18 10:42:21 +00:00
// If the returned error is StreamError, the error Code may be used in resetting the stream.
2024-02-18 10:42:21 +00:00
func (cs *clientStream) writeRequest(req *http.Request) (err error) {
2024-02-18 10:42:21 +00:00
cc := cs.cc
2024-02-18 10:42:21 +00:00
ctx := cs.ctx
if err := checkConnHeaders(req); err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
// Acquire the new-request lock by writing to reqHeaderMu.
2024-02-18 10:42:21 +00:00
// This lock guards the critical section covering allocating a new stream ID
2024-02-18 10:42:21 +00:00
// (requires mu) and creating the stream (requires wmu).
2024-02-18 10:42:21 +00:00
if cc.reqHeaderMu == nil {
2024-02-18 10:42:21 +00:00
panic("RoundTrip on uninitialized ClientConn") // for tests
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
var newStreamHook func(*clientStream)
2024-05-14 13:07:09 +00:00
if cc.syncHooks != nil {
2024-05-14 13:07:09 +00:00
newStreamHook = cc.syncHooks.newstream
2024-05-14 13:07:09 +00:00
cc.syncHooks.blockUntil(func() bool {
2024-05-14 13:07:09 +00:00
select {
2024-05-14 13:07:09 +00:00
case cc.reqHeaderMu <- struct{}{}:
2024-05-14 13:07:09 +00:00
<-cc.reqHeaderMu
2024-05-14 13:07:09 +00:00
case <-cs.reqCancel:
2024-05-14 13:07:09 +00:00
case <-ctx.Done():
2024-05-14 13:07:09 +00:00
default:
2024-05-14 13:07:09 +00:00
return false
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
return true
2024-05-14 13:07:09 +00:00
})
2024-05-14 13:07:09 +00:00
}
2024-02-18 10:42:21 +00:00
select {
2024-02-18 10:42:21 +00:00
case cc.reqHeaderMu <- struct{}{}:
2024-02-18 10:42:21 +00:00
case <-cs.reqCancel:
2024-02-18 10:42:21 +00:00
return errRequestCanceled
2024-02-18 10:42:21 +00:00
case <-ctx.Done():
2024-02-18 10:42:21 +00:00
return ctx.Err()
2024-02-18 10:42:21 +00:00
}
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
if cc.idleTimer != nil {
2024-02-18 10:42:21 +00:00
cc.idleTimer.Stop()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.decrStreamReservationsLocked()
2024-02-18 10:42:21 +00:00
if err := cc.awaitOpenSlotForStreamLocked(cs); err != nil {
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
<-cc.reqHeaderMu
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.addStreamLocked(cs) // assigns stream ID
2024-02-18 10:42:21 +00:00
if isConnectionCloseRequest(req) {
2024-02-18 10:42:21 +00:00
cc.doNotReuse = true
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
2024-05-14 13:07:09 +00:00
if newStreamHook != nil {
2024-05-14 13:07:09 +00:00
newStreamHook(cs)
2024-05-14 13:07:09 +00:00
}
2024-02-18 10:42:21 +00:00
// TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere?
2024-02-18 10:42:21 +00:00
if !cc.t.disableCompression() &&
2024-02-18 10:42:21 +00:00
req.Header.Get("Accept-Encoding") == "" &&
2024-02-18 10:42:21 +00:00
req.Header.Get("Range") == "" &&
2024-02-18 10:42:21 +00:00
!cs.isHead {
2024-02-18 10:42:21 +00:00
// Request gzip only, not deflate. Deflate is ambiguous and
2024-02-18 10:42:21 +00:00
// not as universally supported anyway.
2024-02-18 10:42:21 +00:00
// See: https://zlib.net/zlib_faq.html#faq39
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// Note that we don't request this for HEAD requests,
2024-02-18 10:42:21 +00:00
// due to a bug in nginx:
2024-02-18 10:42:21 +00:00
// http://trac.nginx.org/nginx/ticket/358
2024-02-18 10:42:21 +00:00
// https://golang.org/issue/5522
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// We don't request gzip if the request is for a range, since
2024-02-18 10:42:21 +00:00
// auto-decoding a portion of a gzipped document will just fail
2024-02-18 10:42:21 +00:00
// anyway. See https://golang.org/issue/8923
2024-02-18 10:42:21 +00:00
cs.requestedGzip = true
2024-02-18 10:42:21 +00:00
}
continueTimeout := cc.t.expectContinueTimeout()
2024-02-18 10:42:21 +00:00
if continueTimeout != 0 {
2024-02-18 10:42:21 +00:00
if !httpguts.HeaderValuesContainsToken(req.Header["Expect"], "100-continue") {
2024-02-18 10:42:21 +00:00
continueTimeout = 0
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
cs.on100 = make(chan struct{}, 1)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// Past this point (where we send request headers), it is possible for
2024-02-18 10:42:21 +00:00
// RoundTrip to return successfully. Since the RoundTrip contract permits
2024-02-18 10:42:21 +00:00
// the caller to "mutate or reuse" the Request after closing the Response's Body,
2024-02-18 10:42:21 +00:00
// we must take care when referencing the Request from here on.
2024-02-18 10:42:21 +00:00
err = cs.encodeAndWriteHeaders(req)
2024-02-18 10:42:21 +00:00
<-cc.reqHeaderMu
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
hasBody := cs.reqBodyContentLength != 0
2024-02-18 10:42:21 +00:00
if !hasBody {
2024-02-18 10:42:21 +00:00
cs.sentEndStream = true
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
if continueTimeout != 0 {
2024-02-18 10:42:21 +00:00
traceWait100Continue(cs.trace)
2024-02-18 10:42:21 +00:00
timer := time.NewTimer(continueTimeout)
2024-02-18 10:42:21 +00:00
select {
2024-02-18 10:42:21 +00:00
case <-timer.C:
2024-02-18 10:42:21 +00:00
err = nil
2024-02-18 10:42:21 +00:00
case <-cs.on100:
2024-02-18 10:42:21 +00:00
err = nil
2024-02-18 10:42:21 +00:00
case <-cs.abort:
2024-02-18 10:42:21 +00:00
err = cs.abortErr
2024-02-18 10:42:21 +00:00
case <-ctx.Done():
2024-02-18 10:42:21 +00:00
err = ctx.Err()
2024-02-18 10:42:21 +00:00
case <-cs.reqCancel:
2024-02-18 10:42:21 +00:00
err = errRequestCanceled
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
timer.Stop()
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
traceWroteRequest(cs.trace, err)
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
if err = cs.writeRequestBody(req); err != nil {
2024-02-18 10:42:21 +00:00
if err != errStopReqBodyWrite {
2024-02-18 10:42:21 +00:00
traceWroteRequest(cs.trace, err)
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
cs.sentEndStream = true
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
traceWroteRequest(cs.trace, err)
var respHeaderTimer <-chan time.Time
2024-02-18 10:42:21 +00:00
var respHeaderRecv chan struct{}
2024-02-18 10:42:21 +00:00
if d := cc.responseHeaderTimeout(); d != 0 {
2024-05-14 13:07:09 +00:00
timer := cc.newTimer(d)
2024-02-18 10:42:21 +00:00
defer timer.Stop()
2024-05-14 13:07:09 +00:00
respHeaderTimer = timer.C()
2024-02-18 10:42:21 +00:00
respHeaderRecv = cs.respHeaderRecv
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
// Wait until the peer half-closes its end of the stream,
2024-02-18 10:42:21 +00:00
// or until the request is aborted (via context, error, or otherwise),
2024-02-18 10:42:21 +00:00
// whichever comes first.
2024-02-18 10:42:21 +00:00
for {
2024-05-14 13:07:09 +00:00
if cc.syncHooks != nil {
2024-05-14 13:07:09 +00:00
cc.syncHooks.blockUntil(func() bool {
2024-05-14 13:07:09 +00:00
select {
2024-05-14 13:07:09 +00:00
case <-cs.peerClosed:
2024-05-14 13:07:09 +00:00
case <-respHeaderTimer:
2024-05-14 13:07:09 +00:00
case <-respHeaderRecv:
2024-05-14 13:07:09 +00:00
case <-cs.abort:
2024-05-14 13:07:09 +00:00
case <-ctx.Done():
2024-05-14 13:07:09 +00:00
case <-cs.reqCancel:
2024-05-14 13:07:09 +00:00
default:
2024-05-14 13:07:09 +00:00
return false
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
return true
2024-05-14 13:07:09 +00:00
})
2024-05-14 13:07:09 +00:00
}
2024-02-18 10:42:21 +00:00
select {
2024-02-18 10:42:21 +00:00
case <-cs.peerClosed:
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
case <-respHeaderTimer:
2024-02-18 10:42:21 +00:00
return errTimeout
2024-02-18 10:42:21 +00:00
case <-respHeaderRecv:
2024-02-18 10:42:21 +00:00
respHeaderRecv = nil
2024-02-18 10:42:21 +00:00
respHeaderTimer = nil // keep waiting for END_STREAM
2024-02-18 10:42:21 +00:00
case <-cs.abort:
2024-02-18 10:42:21 +00:00
return cs.abortErr
2024-02-18 10:42:21 +00:00
case <-ctx.Done():
2024-02-18 10:42:21 +00:00
return ctx.Err()
2024-02-18 10:42:21 +00:00
case <-cs.reqCancel:
2024-02-18 10:42:21 +00:00
return errRequestCanceled
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func (cs *clientStream) encodeAndWriteHeaders(req *http.Request) error {
2024-02-18 10:42:21 +00:00
cc := cs.cc
2024-02-18 10:42:21 +00:00
ctx := cs.ctx
cc.wmu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.wmu.Unlock()
// If the request was canceled while waiting for cc.mu, just quit.
2024-02-18 10:42:21 +00:00
select {
2024-02-18 10:42:21 +00:00
case <-cs.abort:
2024-02-18 10:42:21 +00:00
return cs.abortErr
2024-02-18 10:42:21 +00:00
case <-ctx.Done():
2024-02-18 10:42:21 +00:00
return ctx.Err()
2024-02-18 10:42:21 +00:00
case <-cs.reqCancel:
2024-02-18 10:42:21 +00:00
return errRequestCanceled
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
}
// Encode headers.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,} (DATA is
2024-02-18 10:42:21 +00:00
// sent by writeRequestBody below, along with any Trailers,
2024-02-18 10:42:21 +00:00
// again in form HEADERS{1}, CONTINUATION{0,})
2024-02-18 10:42:21 +00:00
trailers, err := commaSeparatedTrailers(req)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
hasTrailers := trailers != ""
2024-02-18 10:42:21 +00:00
contentLen := actualContentLength(req)
2024-02-18 10:42:21 +00:00
hasBody := contentLen != 0
2024-02-18 10:42:21 +00:00
hdrs, err := cc.encodeHeaders(req, cs.requestedGzip, trailers, contentLen)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
// Write the request.
2024-02-18 10:42:21 +00:00
endStream := !hasBody && !hasTrailers
2024-02-18 10:42:21 +00:00
cs.sentHeaders = true
2024-02-18 10:42:21 +00:00
err = cc.writeHeaders(cs.ID, endStream, int(cc.maxFrameSize), hdrs)
2024-02-18 10:42:21 +00:00
traceWroteHeaders(cs.trace)
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
// cleanupWriteRequest performs post-request tasks.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// If err (the result of writeRequest) is non-nil and the stream is not closed,
2024-02-18 10:42:21 +00:00
// cleanupWriteRequest will send a reset to the peer.
2024-02-18 10:42:21 +00:00
func (cs *clientStream) cleanupWriteRequest(err error) {
2024-02-18 10:42:21 +00:00
cc := cs.cc
if cs.ID == 0 {
2024-02-18 10:42:21 +00:00
// We were canceled before creating the stream, so return our reservation.
2024-02-18 10:42:21 +00:00
cc.decrStreamReservations()
2024-02-18 10:42:21 +00:00
}
// TODO: write h12Compare test showing whether
2024-02-18 10:42:21 +00:00
// Request.Body is closed by the Transport,
2024-02-18 10:42:21 +00:00
// and in multiple cases: server replies <=299 and >299
2024-02-18 10:42:21 +00:00
// while still writing request body
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
mustCloseBody := false
2024-02-18 10:42:21 +00:00
if cs.reqBody != nil && cs.reqBodyClosed == nil {
2024-02-18 10:42:21 +00:00
mustCloseBody = true
2024-02-18 10:42:21 +00:00
cs.reqBodyClosed = make(chan struct{})
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
bodyClosed := cs.reqBodyClosed
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
if mustCloseBody {
2024-02-18 10:42:21 +00:00
cs.reqBody.Close()
2024-02-18 10:42:21 +00:00
close(bodyClosed)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if bodyClosed != nil {
2024-02-18 10:42:21 +00:00
<-bodyClosed
2024-02-18 10:42:21 +00:00
}
if err != nil && cs.sentEndStream {
2024-02-18 10:42:21 +00:00
// If the connection is closed immediately after the response is read,
2024-02-18 10:42:21 +00:00
// we may be aborted before finishing up here. If the stream was closed
2024-02-18 10:42:21 +00:00
// cleanly on both sides, there is no error.
2024-02-18 10:42:21 +00:00
select {
2024-02-18 10:42:21 +00:00
case <-cs.peerClosed:
2024-02-18 10:42:21 +00:00
err = nil
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
cs.abortStream(err) // possibly redundant, but harmless
2024-02-18 10:42:21 +00:00
if cs.sentHeaders {
2024-02-18 10:42:21 +00:00
if se, ok := err.(StreamError); ok {
2024-02-18 10:42:21 +00:00
if se.Cause != errFromPeer {
2024-02-18 10:42:21 +00:00
cc.writeStreamReset(cs.ID, se.Code, err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
cc.writeStreamReset(cs.ID, ErrCodeCancel, err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cs.bufPipe.CloseWithError(err) // no-op if already closed
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
if cs.sentHeaders && !cs.sentEndStream {
2024-02-18 10:42:21 +00:00
cc.writeStreamReset(cs.ID, ErrCodeNo, nil)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cs.bufPipe.CloseWithError(errRequestCanceled)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if cs.ID != 0 {
2024-02-18 10:42:21 +00:00
cc.forgetStreamID(cs.ID)
2024-02-18 10:42:21 +00:00
}
cc.wmu.Lock()
2024-02-18 10:42:21 +00:00
werr := cc.werr
2024-02-18 10:42:21 +00:00
cc.wmu.Unlock()
2024-02-18 10:42:21 +00:00
if werr != nil {
2024-02-18 10:42:21 +00:00
cc.Close()
2024-02-18 10:42:21 +00:00
}
close(cs.donec)
2024-02-18 10:42:21 +00:00
}
// awaitOpenSlotForStreamLocked waits until len(streams) < maxConcurrentStreams.
2024-02-18 10:42:21 +00:00
// Must hold cc.mu.
2024-02-18 10:42:21 +00:00
func (cc *ClientConn) awaitOpenSlotForStreamLocked(cs *clientStream) error {
2024-02-18 10:42:21 +00:00
for {
2024-02-18 10:42:21 +00:00
cc.lastActive = time.Now()
2024-02-18 10:42:21 +00:00
if cc.closed || !cc.canTakeNewRequestLocked() {
2024-02-18 10:42:21 +00:00
return errClientConnUnusable
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.lastIdle = time.Time{}
2024-02-18 10:42:21 +00:00
if int64(len(cc.streams)) < int64(cc.maxConcurrentStreams) {
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.pendingRequests++
2024-05-14 13:07:09 +00:00
cc.condWait()
2024-02-18 10:42:21 +00:00
cc.pendingRequests--
2024-02-18 10:42:21 +00:00
select {
2024-02-18 10:42:21 +00:00
case <-cs.abort:
2024-02-18 10:42:21 +00:00
return cs.abortErr
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// requires cc.wmu be held
2024-02-18 10:42:21 +00:00
func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, maxFrameSize int, hdrs []byte) error {
2024-02-18 10:42:21 +00:00
first := true // first frame written (HEADERS is first, then CONTINUATION)
2024-02-18 10:42:21 +00:00
for len(hdrs) > 0 && cc.werr == nil {
2024-02-18 10:42:21 +00:00
chunk := hdrs
2024-02-18 10:42:21 +00:00
if len(chunk) > maxFrameSize {
2024-02-18 10:42:21 +00:00
chunk = chunk[:maxFrameSize]
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
hdrs = hdrs[len(chunk):]
2024-02-18 10:42:21 +00:00
endHeaders := len(hdrs) == 0
2024-02-18 10:42:21 +00:00
if first {
2024-02-18 10:42:21 +00:00
cc.fr.WriteHeaders(HeadersFrameParam{
StreamID: streamID,
2024-02-18 10:42:21 +00:00
BlockFragment: chunk,
EndStream: endStream,
EndHeaders: endHeaders,
2024-02-18 10:42:21 +00:00
})
2024-02-18 10:42:21 +00:00
first = false
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
cc.fr.WriteContinuation(streamID, endHeaders, chunk)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.bw.Flush()
2024-02-18 10:42:21 +00:00
return cc.werr
2024-02-18 10:42:21 +00:00
}
// internal error values; they don't escape to callers
2024-02-18 10:42:21 +00:00
var (
2024-02-18 10:42:21 +00:00
// abort request body write; don't send cancel
2024-02-18 10:42:21 +00:00
errStopReqBodyWrite = errors.New("http2: aborting request body write")
// abort request body write, but send stream reset of cancel.
2024-02-18 10:42:21 +00:00
errStopReqBodyWriteAndCancel = errors.New("http2: canceling request")
errReqBodyTooLong = errors.New("http2: request body larger than specified content length")
)
// frameScratchBufferLen returns the length of a buffer to use for
2024-02-18 10:42:21 +00:00
// outgoing request bodies to read/write to/from.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// It returns max(1, min(peer's advertised max frame size,
2024-02-18 10:42:21 +00:00
// Request.ContentLength+1, 512KB)).
2024-02-18 10:42:21 +00:00
func (cs *clientStream) frameScratchBufferLen(maxFrameSize int) int {
2024-02-18 10:42:21 +00:00
const max = 512 << 10
2024-02-18 10:42:21 +00:00
n := int64(maxFrameSize)
2024-02-18 10:42:21 +00:00
if n > max {
2024-02-18 10:42:21 +00:00
n = max
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if cl := cs.reqBodyContentLength; cl != -1 && cl+1 < n {
2024-02-18 10:42:21 +00:00
// Add an extra byte past the declared content-length to
2024-02-18 10:42:21 +00:00
// give the caller's Request.Body io.Reader a chance to
2024-02-18 10:42:21 +00:00
// give us more bytes than they declared, so we can catch it
2024-02-18 10:42:21 +00:00
// early.
2024-02-18 10:42:21 +00:00
n = cl + 1
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if n < 1 {
2024-02-18 10:42:21 +00:00
return 1
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return int(n) // doesn't truncate; max is 512K
2024-02-18 10:42:21 +00:00
}
// Seven bufPools manage different frame sizes. This helps to avoid scenarios where long-running
2024-02-18 10:42:21 +00:00
// streaming requests using small frame sizes occupy large buffers initially allocated for prior
2024-02-18 10:42:21 +00:00
// requests needing big buffers. The size ranges are as follows:
2024-02-18 10:42:21 +00:00
// {0 KB, 16 KB], {16 KB, 32 KB], {32 KB, 64 KB], {64 KB, 128 KB], {128 KB, 256 KB],
2024-02-18 10:42:21 +00:00
// {256 KB, 512 KB], {512 KB, infinity}
2024-02-18 10:42:21 +00:00
// In practice, the maximum scratch buffer size should not exceed 512 KB due to
2024-02-18 10:42:21 +00:00
// frameScratchBufferLen(maxFrameSize), thus the "infinity pool" should never be used.
2024-02-18 10:42:21 +00:00
// It exists mainly as a safety measure, for potential future increases in max buffer size.
2024-02-18 10:42:21 +00:00
var bufPools [7]sync.Pool // of *[]byte
2024-02-18 10:42:21 +00:00
func bufPoolIndex(size int) int {
2024-02-18 10:42:21 +00:00
if size <= 16384 {
2024-02-18 10:42:21 +00:00
return 0
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
size -= 1
2024-02-18 10:42:21 +00:00
bits := bits.Len(uint(size))
2024-02-18 10:42:21 +00:00
index := bits - 14
2024-02-18 10:42:21 +00:00
if index >= len(bufPools) {
2024-02-18 10:42:21 +00:00
return len(bufPools) - 1
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return index
2024-02-18 10:42:21 +00:00
}
func (cs *clientStream) writeRequestBody(req *http.Request) (err error) {
2024-02-18 10:42:21 +00:00
cc := cs.cc
2024-02-18 10:42:21 +00:00
body := cs.reqBody
2024-02-18 10:42:21 +00:00
sentEnd := false // whether we sent the final DATA frame w/ END_STREAM
hasTrailers := req.Trailer != nil
2024-02-18 10:42:21 +00:00
remainLen := cs.reqBodyContentLength
2024-02-18 10:42:21 +00:00
hasContentLen := remainLen != -1
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
maxFrameSize := int(cc.maxFrameSize)
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
// Scratch buffer for reading into & writing from.
2024-02-18 10:42:21 +00:00
scratchLen := cs.frameScratchBufferLen(maxFrameSize)
2024-02-18 10:42:21 +00:00
var buf []byte
2024-02-18 10:42:21 +00:00
index := bufPoolIndex(scratchLen)
2024-02-18 10:42:21 +00:00
if bp, ok := bufPools[index].Get().(*[]byte); ok && len(*bp) >= scratchLen {
2024-02-18 10:42:21 +00:00
defer bufPools[index].Put(bp)
2024-02-18 10:42:21 +00:00
buf = *bp
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
buf = make([]byte, scratchLen)
2024-02-18 10:42:21 +00:00
defer bufPools[index].Put(&buf)
2024-02-18 10:42:21 +00:00
}
var sawEOF bool
2024-02-18 10:42:21 +00:00
for !sawEOF {
2024-02-18 10:42:21 +00:00
n, err := body.Read(buf)
2024-02-18 10:42:21 +00:00
if hasContentLen {
2024-02-18 10:42:21 +00:00
remainLen -= int64(n)
2024-02-18 10:42:21 +00:00
if remainLen == 0 && err == nil {
2024-02-18 10:42:21 +00:00
// The request body's Content-Length was predeclared and
2024-02-18 10:42:21 +00:00
// we just finished reading it all, but the underlying io.Reader
2024-02-18 10:42:21 +00:00
// returned the final chunk with a nil error (which is one of
2024-02-18 10:42:21 +00:00
// the two valid things a Reader can do at EOF). Because we'd prefer
2024-02-18 10:42:21 +00:00
// to send the END_STREAM bit early, double-check that we're actually
2024-02-18 10:42:21 +00:00
// at EOF. Subsequent reads should return (0, EOF) at this point.
2024-02-18 10:42:21 +00:00
// If either value is different, we return an error in one of two ways below.
2024-02-18 10:42:21 +00:00
var scratch [1]byte
2024-02-18 10:42:21 +00:00
var n1 int
2024-02-18 10:42:21 +00:00
n1, err = body.Read(scratch[:])
2024-02-18 10:42:21 +00:00
remainLen -= int64(n1)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if remainLen < 0 {
2024-02-18 10:42:21 +00:00
err = errReqBodyTooLong
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
bodyClosed := cs.reqBodyClosed != nil
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
switch {
2024-02-18 10:42:21 +00:00
case bodyClosed:
2024-02-18 10:42:21 +00:00
return errStopReqBodyWrite
2024-02-18 10:42:21 +00:00
case err == io.EOF:
2024-02-18 10:42:21 +00:00
sawEOF = true
2024-02-18 10:42:21 +00:00
err = nil
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
remain := buf[:n]
2024-02-18 10:42:21 +00:00
for len(remain) > 0 && err == nil {
2024-02-18 10:42:21 +00:00
var allowed int32
2024-02-18 10:42:21 +00:00
allowed, err = cs.awaitFlowControl(len(remain))
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.wmu.Lock()
2024-02-18 10:42:21 +00:00
data := remain[:allowed]
2024-02-18 10:42:21 +00:00
remain = remain[allowed:]
2024-02-18 10:42:21 +00:00
sentEnd = sawEOF && len(remain) == 0 && !hasTrailers
2024-02-18 10:42:21 +00:00
err = cc.fr.WriteData(cs.ID, sentEnd, data)
2024-02-18 10:42:21 +00:00
if err == nil {
2024-02-18 10:42:21 +00:00
// TODO(bradfitz): this flush is for latency, not bandwidth.
2024-02-18 10:42:21 +00:00
// Most requests won't need this. Make this opt-in or
2024-02-18 10:42:21 +00:00
// opt-out? Use some heuristic on the body type? Nagel-like
2024-02-18 10:42:21 +00:00
// timers? Based on 'n'? Only last chunk of this for loop,
2024-02-18 10:42:21 +00:00
// unless flow control tokens are low? For now, always.
2024-02-18 10:42:21 +00:00
// If we change this, see comment below.
2024-02-18 10:42:21 +00:00
err = cc.bw.Flush()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.wmu.Unlock()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
if sentEnd {
2024-02-18 10:42:21 +00:00
// Already sent END_STREAM (which implies we have no
2024-02-18 10:42:21 +00:00
// trailers) and flushed, because currently all
2024-02-18 10:42:21 +00:00
// WriteData frames above get a flush. So we're done.
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
// Since the RoundTrip contract permits the caller to "mutate or reuse"
2024-02-18 10:42:21 +00:00
// a request after the Response's Body is closed, verify that this hasn't
2024-02-18 10:42:21 +00:00
// happened before accessing the trailers.
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
trailer := req.Trailer
2024-02-18 10:42:21 +00:00
err = cs.abortErr
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
cc.wmu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.wmu.Unlock()
2024-02-18 10:42:21 +00:00
var trls []byte
2024-02-18 10:42:21 +00:00
if len(trailer) > 0 {
2024-02-18 10:42:21 +00:00
trls, err = cc.encodeTrailers(trailer)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// Two ways to send END_STREAM: either with trailers, or
2024-02-18 10:42:21 +00:00
// with an empty DATA frame.
2024-02-18 10:42:21 +00:00
if len(trls) > 0 {
2024-02-18 10:42:21 +00:00
err = cc.writeHeaders(cs.ID, true, maxFrameSize, trls)
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
err = cc.fr.WriteData(cs.ID, true, nil)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if ferr := cc.bw.Flush(); ferr != nil && err == nil {
2024-02-18 10:42:21 +00:00
err = ferr
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
// awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
2024-02-18 10:42:21 +00:00
// control tokens from the server.
2024-02-18 10:42:21 +00:00
// It returns either the non-zero number of tokens taken or an error
2024-02-18 10:42:21 +00:00
// if the stream is dead.
2024-02-18 10:42:21 +00:00
func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
2024-02-18 10:42:21 +00:00
cc := cs.cc
2024-02-18 10:42:21 +00:00
ctx := cs.ctx
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
for {
2024-02-18 10:42:21 +00:00
if cc.closed {
2024-02-18 10:42:21 +00:00
return 0, errClientConnClosed
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if cs.reqBodyClosed != nil {
2024-02-18 10:42:21 +00:00
return 0, errStopReqBodyWrite
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
select {
2024-02-18 10:42:21 +00:00
case <-cs.abort:
2024-02-18 10:42:21 +00:00
return 0, cs.abortErr
2024-02-18 10:42:21 +00:00
case <-ctx.Done():
2024-02-18 10:42:21 +00:00
return 0, ctx.Err()
2024-02-18 10:42:21 +00:00
case <-cs.reqCancel:
2024-02-18 10:42:21 +00:00
return 0, errRequestCanceled
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if a := cs.flow.available(); a > 0 {
2024-02-18 10:42:21 +00:00
take := a
2024-02-18 10:42:21 +00:00
if int(take) > maxBytes {
take = int32(maxBytes) // can't truncate int; take is int32
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if take > int32(cc.maxFrameSize) {
2024-02-18 10:42:21 +00:00
take = int32(cc.maxFrameSize)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cs.flow.take(take)
2024-02-18 10:42:21 +00:00
return take, nil
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
cc.condWait()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
func validateHeaders(hdrs http.Header) string {
2024-05-14 13:07:09 +00:00
for k, vv := range hdrs {
2024-05-14 13:07:09 +00:00
if !httpguts.ValidHeaderFieldName(k) {
2024-05-14 13:07:09 +00:00
return fmt.Sprintf("name %q", k)
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
for _, v := range vv {
2024-05-14 13:07:09 +00:00
if !httpguts.ValidHeaderFieldValue(v) {
2024-05-14 13:07:09 +00:00
// Don't include the value in the error,
2024-05-14 13:07:09 +00:00
// because it may be sensitive.
2024-05-14 13:07:09 +00:00
return fmt.Sprintf("value for header %q", k)
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
return ""
2024-05-14 13:07:09 +00:00
}
2024-02-18 10:42:21 +00:00
var errNilRequestURL = errors.New("http2: Request.URI is nil")
// requires cc.wmu be held.
2024-02-18 10:42:21 +00:00
func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) {
2024-02-18 10:42:21 +00:00
cc.hbuf.Reset()
2024-02-18 10:42:21 +00:00
if req.URL == nil {
2024-02-18 10:42:21 +00:00
return nil, errNilRequestURL
2024-02-18 10:42:21 +00:00
}
host := req.Host
2024-02-18 10:42:21 +00:00
if host == "" {
2024-02-18 10:42:21 +00:00
host = req.URL.Host
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
host, err := httpguts.PunycodeHostPort(host)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if !httpguts.ValidHostHeader(host) {
2024-02-18 10:42:21 +00:00
return nil, errors.New("http2: invalid Host header")
2024-02-18 10:42:21 +00:00
}
var path string
2024-02-18 10:42:21 +00:00
if req.Method != "CONNECT" {
2024-02-18 10:42:21 +00:00
path = req.URL.RequestURI()
2024-02-18 10:42:21 +00:00
if !validPseudoPath(path) {
2024-02-18 10:42:21 +00:00
orig := path
2024-02-18 10:42:21 +00:00
path = strings.TrimPrefix(path, req.URL.Scheme+"://"+host)
2024-02-18 10:42:21 +00:00
if !validPseudoPath(path) {
2024-02-18 10:42:21 +00:00
if req.URL.Opaque != "" {
2024-02-18 10:42:21 +00:00
return nil, fmt.Errorf("invalid request :path %q from URL.Opaque = %q", orig, req.URL.Opaque)
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
return nil, fmt.Errorf("invalid request :path %q", orig)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
// Check for any invalid headers+trailers and return an error before we
2024-02-18 10:42:21 +00:00
// potentially pollute our hpack state. (We want to be able to
2024-02-18 10:42:21 +00:00
// continue to reuse the hpack encoder for future requests)
2024-05-14 13:07:09 +00:00
if err := validateHeaders(req.Header); err != "" {
2024-05-14 13:07:09 +00:00
return nil, fmt.Errorf("invalid HTTP header %s", err)
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
if err := validateHeaders(req.Trailer); err != "" {
2024-05-14 13:07:09 +00:00
return nil, fmt.Errorf("invalid HTTP trailer %s", err)
2024-02-18 10:42:21 +00:00
}
enumerateHeaders := func(f func(name, value string)) {
2024-02-18 10:42:21 +00:00
// 8.1.2.3 Request Pseudo-Header Fields
2024-02-18 10:42:21 +00:00
// The :path pseudo-header field includes the path and query parts of the
2024-02-18 10:42:21 +00:00
// target URI (the path-absolute production and optionally a '?' character
2024-02-18 10:42:21 +00:00
// followed by the query production, see Sections 3.3 and 3.4 of
2024-02-18 10:42:21 +00:00
// [RFC3986]).
2024-02-18 10:42:21 +00:00
f(":authority", host)
2024-02-18 10:42:21 +00:00
m := req.Method
2024-02-18 10:42:21 +00:00
if m == "" {
2024-02-18 10:42:21 +00:00
m = http.MethodGet
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
f(":method", m)
2024-02-18 10:42:21 +00:00
if req.Method != "CONNECT" {
2024-02-18 10:42:21 +00:00
f(":path", path)
2024-02-18 10:42:21 +00:00
f(":scheme", req.URL.Scheme)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if trailers != "" {
2024-02-18 10:42:21 +00:00
f("trailer", trailers)
2024-02-18 10:42:21 +00:00
}
var didUA bool
2024-02-18 10:42:21 +00:00
for k, vv := range req.Header {
2024-02-18 10:42:21 +00:00
if asciiEqualFold(k, "host") || asciiEqualFold(k, "content-length") {
2024-02-18 10:42:21 +00:00
// Host is :authority, already sent.
2024-02-18 10:42:21 +00:00
// Content-Length is automatic, set below.
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
} else if asciiEqualFold(k, "connection") ||
2024-02-18 10:42:21 +00:00
asciiEqualFold(k, "proxy-connection") ||
2024-02-18 10:42:21 +00:00
asciiEqualFold(k, "transfer-encoding") ||
2024-02-18 10:42:21 +00:00
asciiEqualFold(k, "upgrade") ||
2024-02-18 10:42:21 +00:00
asciiEqualFold(k, "keep-alive") {
2024-02-18 10:42:21 +00:00
// Per 8.1.2.2 Connection-Specific Header
2024-02-18 10:42:21 +00:00
// Fields, don't send connection-specific
2024-02-18 10:42:21 +00:00
// fields. We have already checked if any
2024-02-18 10:42:21 +00:00
// are error-worthy so just ignore the rest.
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
} else if asciiEqualFold(k, "user-agent") {
2024-02-18 10:42:21 +00:00
// Match Go's http1 behavior: at most one
2024-02-18 10:42:21 +00:00
// User-Agent. If set to nil or empty string,
2024-02-18 10:42:21 +00:00
// then omit it. Otherwise if not mentioned,
2024-02-18 10:42:21 +00:00
// include the default (below).
2024-02-18 10:42:21 +00:00
didUA = true
2024-02-18 10:42:21 +00:00
if len(vv) < 1 {
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
vv = vv[:1]
2024-02-18 10:42:21 +00:00
if vv[0] == "" {
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
} else if asciiEqualFold(k, "cookie") {
2024-02-18 10:42:21 +00:00
// Per 8.1.2.5 To allow for better compression efficiency, the
2024-02-18 10:42:21 +00:00
// Cookie header field MAY be split into separate header fields,
2024-02-18 10:42:21 +00:00
// each with one or more cookie-pairs.
2024-02-18 10:42:21 +00:00
for _, v := range vv {
2024-02-18 10:42:21 +00:00
for {
2024-02-18 10:42:21 +00:00
p := strings.IndexByte(v, ';')
2024-02-18 10:42:21 +00:00
if p < 0 {
2024-02-18 10:42:21 +00:00
break
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
f("cookie", v[:p])
2024-02-18 10:42:21 +00:00
p++
2024-02-18 10:42:21 +00:00
// strip space after semicolon if any.
2024-02-18 10:42:21 +00:00
for p+1 <= len(v) && v[p] == ' ' {
2024-02-18 10:42:21 +00:00
p++
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
v = v[p:]
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if len(v) > 0 {
2024-02-18 10:42:21 +00:00
f("cookie", v)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
for _, v := range vv {
2024-02-18 10:42:21 +00:00
f(k, v)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if shouldSendReqContentLength(req.Method, contentLength) {
2024-02-18 10:42:21 +00:00
f("content-length", strconv.FormatInt(contentLength, 10))
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if addGzipHeader {
2024-02-18 10:42:21 +00:00
f("accept-encoding", "gzip")
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if !didUA {
2024-02-18 10:42:21 +00:00
f("user-agent", defaultUserAgent)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// Do a first pass over the headers counting bytes to ensure
2024-02-18 10:42:21 +00:00
// we don't exceed cc.peerMaxHeaderListSize. This is done as a
2024-02-18 10:42:21 +00:00
// separate pass before encoding the headers to prevent
2024-02-18 10:42:21 +00:00
// modifying the hpack state.
2024-02-18 10:42:21 +00:00
hlSize := uint64(0)
2024-02-18 10:42:21 +00:00
enumerateHeaders(func(name, value string) {
2024-02-18 10:42:21 +00:00
hf := hpack.HeaderField{Name: name, Value: value}
2024-02-18 10:42:21 +00:00
hlSize += uint64(hf.Size())
2024-02-18 10:42:21 +00:00
})
if hlSize > cc.peerMaxHeaderListSize {
2024-02-18 10:42:21 +00:00
return nil, errRequestHeaderListSize
2024-02-18 10:42:21 +00:00
}
trace := httptrace.ContextClientTrace(req.Context())
2024-02-18 10:42:21 +00:00
traceHeaders := traceHasWroteHeaderField(trace)
// Header list size is ok. Write the headers.
2024-02-18 10:42:21 +00:00
enumerateHeaders(func(name, value string) {
2024-02-18 10:42:21 +00:00
name, ascii := lowerHeader(name)
2024-02-18 10:42:21 +00:00
if !ascii {
2024-02-18 10:42:21 +00:00
// Skip writing invalid headers. Per RFC 7540, Section 8.1.2, header
2024-02-18 10:42:21 +00:00
// field names have to be ASCII characters (just as in HTTP/1.x).
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.writeHeader(name, value)
2024-02-18 10:42:21 +00:00
if traceHeaders {
2024-02-18 10:42:21 +00:00
traceWroteHeaderField(trace, name, value)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
})
return cc.hbuf.Bytes(), nil
2024-02-18 10:42:21 +00:00
}
// shouldSendReqContentLength reports whether the http2.Transport should send
2024-02-18 10:42:21 +00:00
// a "content-length" request header. This logic is basically a copy of the net/http
2024-02-18 10:42:21 +00:00
// transferWriter.shouldSendContentLength.
2024-02-18 10:42:21 +00:00
// The contentLength is the corrected contentLength (so 0 means actually 0, not unknown).
2024-02-18 10:42:21 +00:00
// -1 means unknown.
2024-02-18 10:42:21 +00:00
func shouldSendReqContentLength(method string, contentLength int64) bool {
2024-02-18 10:42:21 +00:00
if contentLength > 0 {
2024-02-18 10:42:21 +00:00
return true
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if contentLength < 0 {
2024-02-18 10:42:21 +00:00
return false
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
// For zero bodies, whether we send a content-length depends on the method.
2024-02-18 10:42:21 +00:00
// It also kinda doesn't matter for http2 either way, with END_STREAM.
2024-02-18 10:42:21 +00:00
switch method {
2024-02-18 10:42:21 +00:00
case "POST", "PUT", "PATCH":
2024-02-18 10:42:21 +00:00
return true
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
return false
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// requires cc.wmu be held.
2024-02-18 10:42:21 +00:00
func (cc *ClientConn) encodeTrailers(trailer http.Header) ([]byte, error) {
2024-02-18 10:42:21 +00:00
cc.hbuf.Reset()
hlSize := uint64(0)
2024-02-18 10:42:21 +00:00
for k, vv := range trailer {
2024-02-18 10:42:21 +00:00
for _, v := range vv {
2024-02-18 10:42:21 +00:00
hf := hpack.HeaderField{Name: k, Value: v}
2024-02-18 10:42:21 +00:00
hlSize += uint64(hf.Size())
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if hlSize > cc.peerMaxHeaderListSize {
2024-02-18 10:42:21 +00:00
return nil, errRequestHeaderListSize
2024-02-18 10:42:21 +00:00
}
for k, vv := range trailer {
2024-02-18 10:42:21 +00:00
lowKey, ascii := lowerHeader(k)
2024-02-18 10:42:21 +00:00
if !ascii {
2024-02-18 10:42:21 +00:00
// Skip writing invalid headers. Per RFC 7540, Section 8.1.2, header
2024-02-18 10:42:21 +00:00
// field names have to be ASCII characters (just as in HTTP/1.x).
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
// Transfer-Encoding, etc.. have already been filtered at the
2024-02-18 10:42:21 +00:00
// start of RoundTrip
2024-02-18 10:42:21 +00:00
for _, v := range vv {
2024-02-18 10:42:21 +00:00
cc.writeHeader(lowKey, v)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return cc.hbuf.Bytes(), nil
2024-02-18 10:42:21 +00:00
}
func (cc *ClientConn) writeHeader(name, value string) {
2024-02-18 10:42:21 +00:00
if VerboseLogs {
2024-02-18 10:42:21 +00:00
log.Printf("http2: Transport encoding header %q = %q", name, value)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
2024-02-18 10:42:21 +00:00
}
type resAndError struct {
_ incomparable
2024-02-18 10:42:21 +00:00
res *http.Response
2024-02-18 10:42:21 +00:00
err error
}
// requires cc.mu be held.
2024-02-18 10:42:21 +00:00
func (cc *ClientConn) addStreamLocked(cs *clientStream) {
2024-02-18 10:42:21 +00:00
cs.flow.add(int32(cc.initialWindowSize))
2024-02-18 10:42:21 +00:00
cs.flow.setConnFlow(&cc.flow)
2024-02-18 10:42:21 +00:00
cs.inflow.init(transportDefaultStreamFlow)
2024-02-18 10:42:21 +00:00
cs.ID = cc.nextStreamID
2024-02-18 10:42:21 +00:00
cc.nextStreamID += 2
2024-02-18 10:42:21 +00:00
cc.streams[cs.ID] = cs
2024-02-18 10:42:21 +00:00
if cs.ID == 0 {
2024-02-18 10:42:21 +00:00
panic("assigned stream ID 0")
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func (cc *ClientConn) forgetStreamID(id uint32) {
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
slen := len(cc.streams)
2024-02-18 10:42:21 +00:00
delete(cc.streams, id)
2024-02-18 10:42:21 +00:00
if len(cc.streams) != slen-1 {
2024-02-18 10:42:21 +00:00
panic("forgetting unknown stream id")
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.lastActive = time.Now()
2024-02-18 10:42:21 +00:00
if len(cc.streams) == 0 && cc.idleTimer != nil {
2024-02-18 10:42:21 +00:00
cc.idleTimer.Reset(cc.idleTimeout)
2024-02-18 10:42:21 +00:00
cc.lastIdle = time.Now()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
// Wake up writeRequestBody via clientStream.awaitFlowControl and
2024-02-18 10:42:21 +00:00
// wake up RoundTrip if there is a pending request.
2024-05-14 13:07:09 +00:00
cc.condBroadcast()
2024-02-18 10:42:21 +00:00
closeOnIdle := cc.singleUse || cc.doNotReuse || cc.t.disableKeepAlives() || cc.goAway != nil
2024-02-18 10:42:21 +00:00
if closeOnIdle && cc.streamsReserved == 0 && len(cc.streams) == 0 {
2024-02-18 10:42:21 +00:00
if VerboseLogs {
2024-02-18 10:42:21 +00:00
cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, cc.nextStreamID-2)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.closed = true
2024-02-18 10:42:21 +00:00
defer cc.closeConn()
2024-02-18 10:42:21 +00:00
}
cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
}
// clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.
2024-02-18 10:42:21 +00:00
type clientConnReadLoop struct {
_ incomparable
2024-02-18 10:42:21 +00:00
cc *ClientConn
}
// readLoop runs in its own goroutine and reads and dispatches frames.
2024-02-18 10:42:21 +00:00
func (cc *ClientConn) readLoop() {
2024-02-18 10:42:21 +00:00
rl := &clientConnReadLoop{cc: cc}
2024-02-18 10:42:21 +00:00
defer rl.cleanup()
2024-02-18 10:42:21 +00:00
cc.readerErr = rl.run()
2024-02-18 10:42:21 +00:00
if ce, ok := cc.readerErr.(ConnectionError); ok {
2024-02-18 10:42:21 +00:00
cc.wmu.Lock()
2024-02-18 10:42:21 +00:00
cc.fr.WriteGoAway(0, ErrCode(ce), nil)
2024-02-18 10:42:21 +00:00
cc.wmu.Unlock()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
// GoAwayError is returned by the Transport when the server closes the
2024-02-18 10:42:21 +00:00
// TCP connection after sending a GOAWAY frame.
2024-02-18 10:42:21 +00:00
type GoAwayError struct {
LastStreamID uint32
ErrCode ErrCode
DebugData string
2024-02-18 10:42:21 +00:00
}
func (e GoAwayError) Error() string {
2024-02-18 10:42:21 +00:00
return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q",
2024-02-18 10:42:21 +00:00
e.LastStreamID, e.ErrCode, e.DebugData)
2024-02-18 10:42:21 +00:00
}
func isEOFOrNetReadError(err error) bool {
2024-02-18 10:42:21 +00:00
if err == io.EOF {
2024-02-18 10:42:21 +00:00
return true
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
ne, ok := err.(*net.OpError)
2024-02-18 10:42:21 +00:00
return ok && ne.Op == "read"
2024-02-18 10:42:21 +00:00
}
func (rl *clientConnReadLoop) cleanup() {
2024-02-18 10:42:21 +00:00
cc := rl.cc
2024-02-18 10:42:21 +00:00
cc.t.connPool().MarkDead(cc)
2024-02-18 10:42:21 +00:00
defer cc.closeConn()
2024-02-18 10:42:21 +00:00
defer close(cc.readerDone)
if cc.idleTimer != nil {
2024-02-18 10:42:21 +00:00
cc.idleTimer.Stop()
2024-02-18 10:42:21 +00:00
}
// Close any response bodies if the server closes prematurely.
2024-02-18 10:42:21 +00:00
// TODO: also do this if we've written the headers but not
2024-02-18 10:42:21 +00:00
// gotten a response yet.
2024-02-18 10:42:21 +00:00
err := cc.readerErr
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
if cc.goAway != nil && isEOFOrNetReadError(err) {
2024-02-18 10:42:21 +00:00
err = GoAwayError{
2024-02-18 10:42:21 +00:00
LastStreamID: cc.goAway.LastStreamID,
ErrCode: cc.goAway.ErrCode,
DebugData: cc.goAwayDebug,
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
} else if err == io.EOF {
2024-02-18 10:42:21 +00:00
err = io.ErrUnexpectedEOF
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.closed = true
for _, cs := range cc.streams {
2024-02-18 10:42:21 +00:00
select {
2024-02-18 10:42:21 +00:00
case <-cs.peerClosed:
2024-02-18 10:42:21 +00:00
// The server closed the stream before closing the conn,
2024-02-18 10:42:21 +00:00
// so no need to interrupt it.
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
cs.abortStreamLocked(err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
cc.condBroadcast()
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
}
// countReadFrameError calls Transport.CountError with a string
2024-02-18 10:42:21 +00:00
// representing err.
2024-02-18 10:42:21 +00:00
func (cc *ClientConn) countReadFrameError(err error) {
2024-02-18 10:42:21 +00:00
f := cc.t.CountError
2024-02-18 10:42:21 +00:00
if f == nil || err == nil {
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if ce, ok := err.(ConnectionError); ok {
2024-02-18 10:42:21 +00:00
errCode := ErrCode(ce)
2024-02-18 10:42:21 +00:00
f(fmt.Sprintf("read_frame_conn_error_%s", errCode.stringToken()))
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if errors.Is(err, io.EOF) {
2024-02-18 10:42:21 +00:00
f("read_frame_eof")
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if errors.Is(err, io.ErrUnexpectedEOF) {
2024-02-18 10:42:21 +00:00
f("read_frame_unexpected_eof")
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if errors.Is(err, ErrFrameTooLarge) {
2024-02-18 10:42:21 +00:00
f("read_frame_too_large")
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
f("read_frame_other")
2024-02-18 10:42:21 +00:00
}
func (rl *clientConnReadLoop) run() error {
2024-02-18 10:42:21 +00:00
cc := rl.cc
2024-02-18 10:42:21 +00:00
gotSettings := false
2024-02-18 10:42:21 +00:00
readIdleTimeout := cc.t.ReadIdleTimeout
2024-05-14 13:07:09 +00:00
var t timer
2024-02-18 10:42:21 +00:00
if readIdleTimeout != 0 {
2024-05-14 13:07:09 +00:00
t = cc.afterFunc(readIdleTimeout, cc.healthCheck)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
for {
2024-02-18 10:42:21 +00:00
f, err := cc.fr.ReadFrame()
2024-02-18 10:42:21 +00:00
if t != nil {
2024-02-18 10:42:21 +00:00
t.Reset(readIdleTimeout)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if se, ok := err.(StreamError); ok {
2024-02-18 10:42:21 +00:00
if cs := rl.streamByID(se.StreamID); cs != nil {
2024-02-18 10:42:21 +00:00
if se.Cause == nil {
2024-02-18 10:42:21 +00:00
se.Cause = cc.fr.errDetail
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
rl.endStreamError(cs, se)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
continue
2024-02-18 10:42:21 +00:00
} else if err != nil {
2024-02-18 10:42:21 +00:00
cc.countReadFrameError(err)
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if VerboseLogs {
2024-02-18 10:42:21 +00:00
cc.vlogf("http2: Transport received %s", summarizeFrame(f))
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if !gotSettings {
2024-02-18 10:42:21 +00:00
if _, ok := f.(*SettingsFrame); !ok {
2024-02-18 10:42:21 +00:00
cc.logf("protocol error: received %T before a SETTINGS frame", f)
2024-02-18 10:42:21 +00:00
return ConnectionError(ErrCodeProtocol)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
gotSettings = true
2024-02-18 10:42:21 +00:00
}
switch f := f.(type) {
2024-02-18 10:42:21 +00:00
case *MetaHeadersFrame:
2024-02-18 10:42:21 +00:00
err = rl.processHeaders(f)
2024-02-18 10:42:21 +00:00
case *DataFrame:
2024-02-18 10:42:21 +00:00
err = rl.processData(f)
2024-02-18 10:42:21 +00:00
case *GoAwayFrame:
2024-02-18 10:42:21 +00:00
err = rl.processGoAway(f)
2024-02-18 10:42:21 +00:00
case *RSTStreamFrame:
2024-02-18 10:42:21 +00:00
err = rl.processResetStream(f)
2024-02-18 10:42:21 +00:00
case *SettingsFrame:
2024-02-18 10:42:21 +00:00
err = rl.processSettings(f)
2024-02-18 10:42:21 +00:00
case *PushPromiseFrame:
2024-02-18 10:42:21 +00:00
err = rl.processPushPromise(f)
2024-02-18 10:42:21 +00:00
case *WindowUpdateFrame:
2024-02-18 10:42:21 +00:00
err = rl.processWindowUpdate(f)
2024-02-18 10:42:21 +00:00
case *PingFrame:
2024-02-18 10:42:21 +00:00
err = rl.processPing(f)
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
cc.logf("Transport: unhandled response frame type %T", f)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
if VerboseLogs {
2024-02-18 10:42:21 +00:00
cc.vlogf("http2: Transport conn %p received error from processing frame %v: %v", cc, summarizeFrame(f), err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error {
2024-02-18 10:42:21 +00:00
cs := rl.streamByID(f.StreamID)
2024-02-18 10:42:21 +00:00
if cs == nil {
2024-02-18 10:42:21 +00:00
// We'd get here if we canceled a request while the
2024-02-18 10:42:21 +00:00
// server had its response still in flight. So if this
2024-02-18 10:42:21 +00:00
// was just something we canceled, ignore it.
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if cs.readClosed {
2024-02-18 10:42:21 +00:00
rl.endStreamError(cs, StreamError{
2024-02-18 10:42:21 +00:00
StreamID: f.StreamID,
Code: ErrCodeProtocol,
Cause: errors.New("protocol error: headers after END_STREAM"),
2024-02-18 10:42:21 +00:00
})
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if !cs.firstByte {
2024-02-18 10:42:21 +00:00
if cs.trace != nil {
2024-02-18 10:42:21 +00:00
// TODO(bradfitz): move first response byte earlier,
2024-02-18 10:42:21 +00:00
// when we first read the 9 byte header, not waiting
2024-02-18 10:42:21 +00:00
// until all the HEADERS+CONTINUATION frames have been
2024-02-18 10:42:21 +00:00
// merged. This works for now.
2024-02-18 10:42:21 +00:00
traceFirstResponseByte(cs.trace)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cs.firstByte = true
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if !cs.pastHeaders {
2024-02-18 10:42:21 +00:00
cs.pastHeaders = true
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
return rl.processTrailers(cs, f)
2024-02-18 10:42:21 +00:00
}
res, err := rl.handleResponse(cs, f)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
if _, ok := err.(ConnectionError); ok {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
// Any other error type is a stream error.
2024-02-18 10:42:21 +00:00
rl.endStreamError(cs, StreamError{
2024-02-18 10:42:21 +00:00
StreamID: f.StreamID,
Code: ErrCodeProtocol,
Cause: err,
2024-02-18 10:42:21 +00:00
})
2024-02-18 10:42:21 +00:00
return nil // return nil from process* funcs to keep conn alive
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if res == nil {
2024-02-18 10:42:21 +00:00
// (nil, nil) special case. See handleResponse docs.
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cs.resTrailer = &res.Trailer
2024-02-18 10:42:21 +00:00
cs.res = res
2024-02-18 10:42:21 +00:00
close(cs.respHeaderRecv)
2024-02-18 10:42:21 +00:00
if f.StreamEnded() {
2024-02-18 10:42:21 +00:00
rl.endStream(cs)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
// may return error types nil, or ConnectionError. Any other error value
2024-02-18 10:42:21 +00:00
// is a StreamError of type ErrCodeProtocol. The returned error in that case
2024-02-18 10:42:21 +00:00
// is the detail.
2024-02-18 10:42:21 +00:00
//
2024-02-18 10:42:21 +00:00
// As a special case, handleResponse may return (nil, nil) to skip the
2024-02-18 10:42:21 +00:00
// frame (currently only used for 1xx responses).
2024-02-18 10:42:21 +00:00
func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFrame) (*http.Response, error) {
2024-02-18 10:42:21 +00:00
if f.Truncated {
2024-02-18 10:42:21 +00:00
return nil, errResponseHeaderListSize
2024-02-18 10:42:21 +00:00
}
status := f.PseudoValue("status")
2024-02-18 10:42:21 +00:00
if status == "" {
2024-02-18 10:42:21 +00:00
return nil, errors.New("malformed response from server: missing status pseudo header")
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
statusCode, err := strconv.Atoi(status)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, errors.New("malformed response from server: malformed non-numeric status pseudo header")
2024-02-18 10:42:21 +00:00
}
regularFields := f.RegularFields()
2024-02-18 10:42:21 +00:00
strs := make([]string, len(regularFields))
2024-02-18 10:42:21 +00:00
header := make(http.Header, len(regularFields))
2024-02-18 10:42:21 +00:00
res := &http.Response{
Proto: "HTTP/2.0",
2024-02-18 10:42:21 +00:00
ProtoMajor: 2,
Header: header,
2024-02-18 10:42:21 +00:00
StatusCode: statusCode,
Status: status + " " + http.StatusText(statusCode),
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
for _, hf := range regularFields {
2024-02-18 10:42:21 +00:00
key := canonicalHeader(hf.Name)
2024-02-18 10:42:21 +00:00
if key == "Trailer" {
2024-02-18 10:42:21 +00:00
t := res.Trailer
2024-02-18 10:42:21 +00:00
if t == nil {
2024-02-18 10:42:21 +00:00
t = make(http.Header)
2024-02-18 10:42:21 +00:00
res.Trailer = t
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
foreachHeaderElement(hf.Value, func(v string) {
2024-02-18 10:42:21 +00:00
t[canonicalHeader(v)] = nil
2024-02-18 10:42:21 +00:00
})
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
vv := header[key]
2024-02-18 10:42:21 +00:00
if vv == nil && len(strs) > 0 {
2024-02-18 10:42:21 +00:00
// More than likely this will be a single-element key.
2024-02-18 10:42:21 +00:00
// Most headers aren't multi-valued.
2024-02-18 10:42:21 +00:00
// Set the capacity on strs[0] to 1, so any future append
2024-02-18 10:42:21 +00:00
// won't extend the slice into the other strings.
2024-02-18 10:42:21 +00:00
vv, strs = strs[:1:1], strs[1:]
2024-02-18 10:42:21 +00:00
vv[0] = hf.Value
2024-02-18 10:42:21 +00:00
header[key] = vv
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
header[key] = append(vv, hf.Value)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
if statusCode >= 100 && statusCode <= 199 {
2024-02-18 10:42:21 +00:00
if f.StreamEnded() {
2024-02-18 10:42:21 +00:00
return nil, errors.New("1xx informational response with END_STREAM flag")
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cs.num1xx++
2024-02-18 10:42:21 +00:00
const max1xxResponses = 5 // arbitrary bound on number of informational responses, same as net/http
2024-02-18 10:42:21 +00:00
if cs.num1xx > max1xxResponses {
2024-02-18 10:42:21 +00:00
return nil, errors.New("http2: too many 1xx informational responses")
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if fn := cs.get1xxTraceFunc(); fn != nil {
2024-02-18 10:42:21 +00:00
if err := fn(statusCode, textproto.MIMEHeader(header)); err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if statusCode == 100 {
2024-02-18 10:42:21 +00:00
traceGot100Continue(cs.trace)
2024-02-18 10:42:21 +00:00
select {
2024-02-18 10:42:21 +00:00
case cs.on100 <- struct{}{}:
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cs.pastHeaders = false // do it all again
2024-02-18 10:42:21 +00:00
return nil, nil
2024-02-18 10:42:21 +00:00
}
res.ContentLength = -1
2024-02-18 10:42:21 +00:00
if clens := res.Header["Content-Length"]; len(clens) == 1 {
2024-02-18 10:42:21 +00:00
if cl, err := strconv.ParseUint(clens[0], 10, 63); err == nil {
2024-02-18 10:42:21 +00:00
res.ContentLength = int64(cl)
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
// TODO: care? unlike http/1, it won't mess up our framing, so it's
2024-02-18 10:42:21 +00:00
// more safe smuggling-wise to ignore.
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
} else if len(clens) > 1 {
2024-02-18 10:42:21 +00:00
// TODO: care? unlike http/1, it won't mess up our framing, so it's
2024-02-18 10:42:21 +00:00
// more safe smuggling-wise to ignore.
2024-02-18 10:42:21 +00:00
} else if f.StreamEnded() && !cs.isHead {
2024-02-18 10:42:21 +00:00
res.ContentLength = 0
2024-02-18 10:42:21 +00:00
}
if cs.isHead {
2024-02-18 10:42:21 +00:00
res.Body = noBody
2024-02-18 10:42:21 +00:00
return res, nil
2024-02-18 10:42:21 +00:00
}
if f.StreamEnded() {
2024-02-18 10:42:21 +00:00
if res.ContentLength > 0 {
2024-02-18 10:42:21 +00:00
res.Body = missingBody{}
2024-02-18 10:42:21 +00:00
} else {
2024-02-18 10:42:21 +00:00
res.Body = noBody
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return res, nil
2024-02-18 10:42:21 +00:00
}
cs.bufPipe.setBuffer(&dataBuffer{expected: res.ContentLength})
2024-02-18 10:42:21 +00:00
cs.bytesRemain = res.ContentLength
2024-02-18 10:42:21 +00:00
res.Body = transportResponseBody{cs}
if cs.requestedGzip && asciiEqualFold(res.Header.Get("Content-Encoding"), "gzip") {
2024-02-18 10:42:21 +00:00
res.Header.Del("Content-Encoding")
2024-02-18 10:42:21 +00:00
res.Header.Del("Content-Length")
2024-02-18 10:42:21 +00:00
res.ContentLength = -1
2024-02-18 10:42:21 +00:00
res.Body = &gzipReader{body: res.Body}
2024-02-18 10:42:21 +00:00
res.Uncompressed = true
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return res, nil
2024-02-18 10:42:21 +00:00
}
func (rl *clientConnReadLoop) processTrailers(cs *clientStream, f *MetaHeadersFrame) error {
2024-02-18 10:42:21 +00:00
if cs.pastTrailers {
2024-02-18 10:42:21 +00:00
// Too many HEADERS frames for this stream.
2024-02-18 10:42:21 +00:00
return ConnectionError(ErrCodeProtocol)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cs.pastTrailers = true
2024-02-18 10:42:21 +00:00
if !f.StreamEnded() {
2024-02-18 10:42:21 +00:00
// We expect that any headers for trailers also
2024-02-18 10:42:21 +00:00
// has END_STREAM.
2024-02-18 10:42:21 +00:00
return ConnectionError(ErrCodeProtocol)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if len(f.PseudoFields()) > 0 {
2024-02-18 10:42:21 +00:00
// No pseudo header fields are defined for trailers.
2024-02-18 10:42:21 +00:00
// TODO: ConnectionError might be overly harsh? Check.
2024-02-18 10:42:21 +00:00
return ConnectionError(ErrCodeProtocol)
2024-02-18 10:42:21 +00:00
}
trailer := make(http.Header)
2024-02-18 10:42:21 +00:00
for _, hf := range f.RegularFields() {
2024-02-18 10:42:21 +00:00
key := canonicalHeader(hf.Name)
2024-02-18 10:42:21 +00:00
trailer[key] = append(trailer[key], hf.Value)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cs.trailer = trailer
rl.endStream(cs)
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
// transportResponseBody is the concrete type of Transport.RoundTrip's
2024-02-18 10:42:21 +00:00
// Response.Body. It is an io.ReadCloser.
2024-02-18 10:42:21 +00:00
type transportResponseBody struct {
cs *clientStream
}
func (b transportResponseBody) Read(p []byte) (n int, err error) {
2024-02-18 10:42:21 +00:00
cs := b.cs
2024-02-18 10:42:21 +00:00
cc := cs.cc
if cs.readErr != nil {
2024-02-18 10:42:21 +00:00
return 0, cs.readErr
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
n, err = b.cs.bufPipe.Read(p)
2024-02-18 10:42:21 +00:00
if cs.bytesRemain != -1 {
2024-02-18 10:42:21 +00:00
if int64(n) > cs.bytesRemain {
2024-02-18 10:42:21 +00:00
n = int(cs.bytesRemain)
2024-02-18 10:42:21 +00:00
if err == nil {
2024-02-18 10:42:21 +00:00
err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
2024-02-18 10:42:21 +00:00
cs.abortStream(err)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cs.readErr = err
2024-02-18 10:42:21 +00:00
return int(cs.bytesRemain), err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cs.bytesRemain -= int64(n)
2024-02-18 10:42:21 +00:00
if err == io.EOF && cs.bytesRemain > 0 {
2024-02-18 10:42:21 +00:00
err = io.ErrUnexpectedEOF
2024-02-18 10:42:21 +00:00
cs.readErr = err
2024-02-18 10:42:21 +00:00
return n, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if n == 0 {
2024-02-18 10:42:21 +00:00
// No flow control tokens to send back.
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
connAdd := cc.inflow.add(n)
2024-02-18 10:42:21 +00:00
var streamAdd int32
2024-02-18 10:42:21 +00:00
if err == nil { // No need to refresh if the stream is over or failed.
2024-02-18 10:42:21 +00:00
streamAdd = cs.inflow.add(n)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
if connAdd != 0 || streamAdd != 0 {
2024-02-18 10:42:21 +00:00
cc.wmu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.wmu.Unlock()
2024-02-18 10:42:21 +00:00
if connAdd != 0 {
2024-02-18 10:42:21 +00:00
cc.fr.WriteWindowUpdate(0, mustUint31(connAdd))
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if streamAdd != 0 {
2024-02-18 10:42:21 +00:00
cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd))
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.bw.Flush()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
var errClosedResponseBody = errors.New("http2: response body closed")
func (b transportResponseBody) Close() error {
2024-02-18 10:42:21 +00:00
cs := b.cs
2024-02-18 10:42:21 +00:00
cc := cs.cc
cs.bufPipe.BreakWithError(errClosedResponseBody)
2024-02-18 10:42:21 +00:00
cs.abortStream(errClosedResponseBody)
unread := cs.bufPipe.Len()
2024-02-18 10:42:21 +00:00
if unread > 0 {
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
// Return connection-level flow control.
2024-02-18 10:42:21 +00:00
connAdd := cc.inflow.add(unread)
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
// TODO(dneil): Acquiring this mutex can block indefinitely.
2024-02-18 10:42:21 +00:00
// Move flow control return to a goroutine?
2024-02-18 10:42:21 +00:00
cc.wmu.Lock()
2024-02-18 10:42:21 +00:00
// Return connection-level flow control.
2024-02-18 10:42:21 +00:00
if connAdd > 0 {
2024-02-18 10:42:21 +00:00
cc.fr.WriteWindowUpdate(0, uint32(connAdd))
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.bw.Flush()
2024-02-18 10:42:21 +00:00
cc.wmu.Unlock()
2024-02-18 10:42:21 +00:00
}
select {
2024-02-18 10:42:21 +00:00
case <-cs.donec:
2024-02-18 10:42:21 +00:00
case <-cs.ctx.Done():
2024-02-18 10:42:21 +00:00
// See golang/go#49366: The net/http package can cancel the
2024-02-18 10:42:21 +00:00
// request context after the response body is fully read.
2024-02-18 10:42:21 +00:00
// Don't treat this as an error.
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
case <-cs.reqCancel:
2024-02-18 10:42:21 +00:00
return errRequestCanceled
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
func (rl *clientConnReadLoop) processData(f *DataFrame) error {
2024-02-18 10:42:21 +00:00
cc := rl.cc
2024-02-18 10:42:21 +00:00
cs := rl.streamByID(f.StreamID)
2024-02-18 10:42:21 +00:00
data := f.Data()
2024-02-18 10:42:21 +00:00
if cs == nil {
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
neverSent := cc.nextStreamID
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
if f.StreamID >= neverSent {
2024-02-18 10:42:21 +00:00
// We never asked for this.
2024-02-18 10:42:21 +00:00
cc.logf("http2: Transport received unsolicited DATA frame; closing connection")
2024-02-18 10:42:21 +00:00
return ConnectionError(ErrCodeProtocol)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
// We probably did ask for this, but canceled. Just ignore it.
2024-02-18 10:42:21 +00:00
// TODO: be stricter here? only silently ignore things which
2024-02-18 10:42:21 +00:00
// we canceled, but not things which were closed normally
2024-02-18 10:42:21 +00:00
// by the peer? Tough without accumulating too much state.
// But at least return their flow control:
2024-02-18 10:42:21 +00:00
if f.Length > 0 {
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
ok := cc.inflow.take(f.Length)
2024-02-18 10:42:21 +00:00
connAdd := cc.inflow.add(int(f.Length))
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
if !ok {
2024-02-18 10:42:21 +00:00
return ConnectionError(ErrCodeFlowControl)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if connAdd > 0 {
2024-02-18 10:42:21 +00:00
cc.wmu.Lock()
2024-02-18 10:42:21 +00:00
cc.fr.WriteWindowUpdate(0, uint32(connAdd))
2024-02-18 10:42:21 +00:00
cc.bw.Flush()
2024-02-18 10:42:21 +00:00
cc.wmu.Unlock()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if cs.readClosed {
2024-02-18 10:42:21 +00:00
cc.logf("protocol error: received DATA after END_STREAM")
2024-02-18 10:42:21 +00:00
rl.endStreamError(cs, StreamError{
2024-02-18 10:42:21 +00:00
StreamID: f.StreamID,
Code: ErrCodeProtocol,
2024-02-18 10:42:21 +00:00
})
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
if !cs.pastHeaders {
2024-02-18 10:42:21 +00:00
cc.logf("protocol error: received DATA before a HEADERS frame")
2024-02-18 10:42:21 +00:00
rl.endStreamError(cs, StreamError{
2024-02-18 10:42:21 +00:00
StreamID: f.StreamID,
Code: ErrCodeProtocol,
2024-02-18 10:42:21 +00:00
})
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if f.Length > 0 {
2024-02-18 10:42:21 +00:00
if cs.isHead && len(data) > 0 {
2024-02-18 10:42:21 +00:00
cc.logf("protocol error: received DATA on a HEAD request")
2024-02-18 10:42:21 +00:00
rl.endStreamError(cs, StreamError{
2024-02-18 10:42:21 +00:00
StreamID: f.StreamID,
Code: ErrCodeProtocol,
2024-02-18 10:42:21 +00:00
})
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
// Check connection-level flow control.
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
if !takeInflows(&cc.inflow, &cs.inflow, f.Length) {
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
return ConnectionError(ErrCodeFlowControl)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
// Return any padded flow control now, since we won't
2024-02-18 10:42:21 +00:00
// refund it later on body reads.
2024-02-18 10:42:21 +00:00
var refund int
2024-02-18 10:42:21 +00:00
if pad := int(f.Length) - len(data); pad > 0 {
2024-02-18 10:42:21 +00:00
refund += pad
2024-02-18 10:42:21 +00:00
}
didReset := false
2024-02-18 10:42:21 +00:00
var err error
2024-02-18 10:42:21 +00:00
if len(data) > 0 {
2024-02-18 10:42:21 +00:00
if _, err = cs.bufPipe.Write(data); err != nil {
2024-02-18 10:42:21 +00:00
// Return len(data) now if the stream is already closed,
2024-02-18 10:42:21 +00:00
// since data will never be read.
2024-02-18 10:42:21 +00:00
didReset = true
2024-02-18 10:42:21 +00:00
refund += len(data)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
sendConn := cc.inflow.add(refund)
2024-02-18 10:42:21 +00:00
var sendStream int32
2024-02-18 10:42:21 +00:00
if !didReset {
2024-02-18 10:42:21 +00:00
sendStream = cs.inflow.add(refund)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
if sendConn > 0 || sendStream > 0 {
2024-02-18 10:42:21 +00:00
cc.wmu.Lock()
2024-02-18 10:42:21 +00:00
if sendConn > 0 {
2024-02-18 10:42:21 +00:00
cc.fr.WriteWindowUpdate(0, uint32(sendConn))
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if sendStream > 0 {
2024-02-18 10:42:21 +00:00
cc.fr.WriteWindowUpdate(cs.ID, uint32(sendStream))
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.bw.Flush()
2024-02-18 10:42:21 +00:00
cc.wmu.Unlock()
2024-02-18 10:42:21 +00:00
}
if err != nil {
2024-02-18 10:42:21 +00:00
rl.endStreamError(cs, err)
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
if f.StreamEnded() {
2024-02-18 10:42:21 +00:00
rl.endStream(cs)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
func (rl *clientConnReadLoop) endStream(cs *clientStream) {
2024-02-18 10:42:21 +00:00
// TODO: check that any declared content-length matches, like
2024-02-18 10:42:21 +00:00
// server.go's (*stream).endStream method.
2024-02-18 10:42:21 +00:00
if !cs.readClosed {
2024-02-18 10:42:21 +00:00
cs.readClosed = true
2024-02-18 10:42:21 +00:00
// Close cs.bufPipe and cs.peerClosed with cc.mu held to avoid a
2024-02-18 10:42:21 +00:00
// race condition: The caller can read io.EOF from Response.Body
2024-02-18 10:42:21 +00:00
// and close the body before we close cs.peerClosed, causing
2024-02-18 10:42:21 +00:00
// cleanupWriteRequest to send a RST_STREAM.
2024-02-18 10:42:21 +00:00
rl.cc.mu.Lock()
2024-02-18 10:42:21 +00:00
defer rl.cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
cs.bufPipe.closeWithErrorAndCode(io.EOF, cs.copyTrailers)
2024-02-18 10:42:21 +00:00
close(cs.peerClosed)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func (rl *clientConnReadLoop) endStreamError(cs *clientStream, err error) {
2024-02-18 10:42:21 +00:00
cs.readAborted = true
2024-02-18 10:42:21 +00:00
cs.abortStream(err)
2024-02-18 10:42:21 +00:00
}
func (rl *clientConnReadLoop) streamByID(id uint32) *clientStream {
2024-02-18 10:42:21 +00:00
rl.cc.mu.Lock()
2024-02-18 10:42:21 +00:00
defer rl.cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
cs := rl.cc.streams[id]
2024-02-18 10:42:21 +00:00
if cs != nil && !cs.readAborted {
2024-02-18 10:42:21 +00:00
return cs
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
func (cs *clientStream) copyTrailers() {
2024-02-18 10:42:21 +00:00
for k, vv := range cs.trailer {
2024-02-18 10:42:21 +00:00
t := cs.resTrailer
2024-02-18 10:42:21 +00:00
if *t == nil {
2024-02-18 10:42:21 +00:00
*t = make(http.Header)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
(*t)[k] = vv
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error {
2024-02-18 10:42:21 +00:00
cc := rl.cc
2024-02-18 10:42:21 +00:00
cc.t.connPool().MarkDead(cc)
2024-02-18 10:42:21 +00:00
if f.ErrCode != 0 {
2024-02-18 10:42:21 +00:00
// TODO: deal with GOAWAY more. particularly the error code
2024-02-18 10:42:21 +00:00
cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
2024-02-18 10:42:21 +00:00
if fn := cc.t.CountError; fn != nil {
2024-02-18 10:42:21 +00:00
fn("recv_goaway_" + f.ErrCode.stringToken())
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.setGoAway(f)
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error {
2024-02-18 10:42:21 +00:00
cc := rl.cc
2024-02-18 10:42:21 +00:00
// Locking both mu and wmu here allows frame encoding to read settings with only wmu held.
2024-02-18 10:42:21 +00:00
// Acquiring wmu when f.IsAck() is unnecessary, but convenient and mostly harmless.
2024-02-18 10:42:21 +00:00
cc.wmu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.wmu.Unlock()
if err := rl.processSettingsNoWrite(f); err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if !f.IsAck() {
2024-02-18 10:42:21 +00:00
cc.fr.WriteSettingsAck()
2024-02-18 10:42:21 +00:00
cc.bw.Flush()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
func (rl *clientConnReadLoop) processSettingsNoWrite(f *SettingsFrame) error {
2024-02-18 10:42:21 +00:00
cc := rl.cc
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.mu.Unlock()
if f.IsAck() {
2024-02-18 10:42:21 +00:00
if cc.wantSettingsAck {
2024-02-18 10:42:21 +00:00
cc.wantSettingsAck = false
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return ConnectionError(ErrCodeProtocol)
2024-02-18 10:42:21 +00:00
}
var seenMaxConcurrentStreams bool
2024-02-18 10:42:21 +00:00
err := f.ForeachSetting(func(s Setting) error {
2024-02-18 10:42:21 +00:00
switch s.ID {
2024-02-18 10:42:21 +00:00
case SettingMaxFrameSize:
2024-02-18 10:42:21 +00:00
cc.maxFrameSize = s.Val
2024-02-18 10:42:21 +00:00
case SettingMaxConcurrentStreams:
2024-02-18 10:42:21 +00:00
cc.maxConcurrentStreams = s.Val
2024-02-18 10:42:21 +00:00
seenMaxConcurrentStreams = true
2024-02-18 10:42:21 +00:00
case SettingMaxHeaderListSize:
2024-02-18 10:42:21 +00:00
cc.peerMaxHeaderListSize = uint64(s.Val)
2024-02-18 10:42:21 +00:00
case SettingInitialWindowSize:
2024-02-18 10:42:21 +00:00
// Values above the maximum flow-control
2024-02-18 10:42:21 +00:00
// window size of 2^31-1 MUST be treated as a
2024-02-18 10:42:21 +00:00
// connection error (Section 5.4.1) of type
2024-02-18 10:42:21 +00:00
// FLOW_CONTROL_ERROR.
2024-02-18 10:42:21 +00:00
if s.Val > math.MaxInt32 {
2024-02-18 10:42:21 +00:00
return ConnectionError(ErrCodeFlowControl)
2024-02-18 10:42:21 +00:00
}
// Adjust flow control of currently-open
2024-02-18 10:42:21 +00:00
// frames by the difference of the old initial
2024-02-18 10:42:21 +00:00
// window size and this one.
2024-02-18 10:42:21 +00:00
delta := int32(s.Val) - int32(cc.initialWindowSize)
2024-02-18 10:42:21 +00:00
for _, cs := range cc.streams {
2024-02-18 10:42:21 +00:00
cs.flow.add(delta)
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
cc.condBroadcast()
2024-02-18 10:42:21 +00:00
cc.initialWindowSize = s.Val
2024-02-18 10:42:21 +00:00
case SettingHeaderTableSize:
2024-02-18 10:42:21 +00:00
cc.henc.SetMaxDynamicTableSize(s.Val)
2024-02-18 10:42:21 +00:00
cc.peerMaxHeaderTableSize = s.Val
2024-02-18 10:42:21 +00:00
default:
2024-02-18 10:42:21 +00:00
cc.vlogf("Unhandled Setting: %v", s)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
})
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
if !cc.seenSettings {
2024-02-18 10:42:21 +00:00
if !seenMaxConcurrentStreams {
2024-02-18 10:42:21 +00:00
// This was the servers initial SETTINGS frame and it
2024-02-18 10:42:21 +00:00
// didn't contain a MAX_CONCURRENT_STREAMS field so
2024-02-18 10:42:21 +00:00
// increase the number of concurrent streams this
2024-02-18 10:42:21 +00:00
// connection can establish to our default.
2024-02-18 10:42:21 +00:00
cc.maxConcurrentStreams = defaultMaxConcurrentStreams
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.seenSettings = true
2024-02-18 10:42:21 +00:00
}
return nil
2024-02-18 10:42:21 +00:00
}
func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error {
2024-02-18 10:42:21 +00:00
cc := rl.cc
2024-02-18 10:42:21 +00:00
cs := rl.streamByID(f.StreamID)
2024-02-18 10:42:21 +00:00
if f.StreamID != 0 && cs == nil {
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.mu.Unlock()
fl := &cc.flow
2024-02-18 10:42:21 +00:00
if cs != nil {
2024-02-18 10:42:21 +00:00
fl = &cs.flow
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if !fl.add(int32(f.Increment)) {
2024-05-14 13:07:09 +00:00
// For stream, the sender sends RST_STREAM with an error code of FLOW_CONTROL_ERROR
2024-05-14 13:07:09 +00:00
if cs != nil {
2024-05-14 13:07:09 +00:00
rl.endStreamError(cs, StreamError{
2024-05-14 13:07:09 +00:00
StreamID: f.StreamID,
Code: ErrCodeFlowControl,
2024-05-14 13:07:09 +00:00
})
2024-05-14 13:07:09 +00:00
return nil
2024-05-14 13:07:09 +00:00
}
2024-02-18 10:42:21 +00:00
return ConnectionError(ErrCodeFlowControl)
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
cc.condBroadcast()
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error {
2024-02-18 10:42:21 +00:00
cs := rl.streamByID(f.StreamID)
2024-02-18 10:42:21 +00:00
if cs == nil {
2024-02-18 10:42:21 +00:00
// TODO: return error if server tries to RST_STREAM an idle stream
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
serr := streamError(cs.ID, f.ErrCode)
2024-02-18 10:42:21 +00:00
serr.Cause = errFromPeer
2024-02-18 10:42:21 +00:00
if f.ErrCode == ErrCodeProtocol {
2024-02-18 10:42:21 +00:00
rl.cc.SetDoNotReuse()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if fn := cs.cc.t.CountError; fn != nil {
2024-02-18 10:42:21 +00:00
fn("recv_rststream_" + f.ErrCode.stringToken())
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cs.abortStream(serr)
cs.bufPipe.CloseWithError(serr)
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
// Ping sends a PING frame to the server and waits for the ack.
2024-02-18 10:42:21 +00:00
func (cc *ClientConn) Ping(ctx context.Context) error {
2024-02-18 10:42:21 +00:00
c := make(chan struct{})
2024-02-18 10:42:21 +00:00
// Generate a random payload
2024-02-18 10:42:21 +00:00
var p [8]byte
2024-02-18 10:42:21 +00:00
for {
2024-02-18 10:42:21 +00:00
if _, err := rand.Read(p[:]); err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
// check for dup before insert
2024-02-18 10:42:21 +00:00
if _, found := cc.pings[p]; !found {
2024-02-18 10:42:21 +00:00
cc.pings[p] = c
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
break
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
var pingError error
2024-05-14 13:07:09 +00:00
errc := make(chan struct{})
2024-05-14 13:07:09 +00:00
cc.goRun(func() {
2024-02-18 10:42:21 +00:00
cc.wmu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.wmu.Unlock()
2024-05-14 13:07:09 +00:00
if pingError = cc.fr.WritePing(false, p); pingError != nil {
2024-05-14 13:07:09 +00:00
close(errc)
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
if pingError = cc.bw.Flush(); pingError != nil {
2024-05-14 13:07:09 +00:00
close(errc)
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
})
2024-05-14 13:07:09 +00:00
if cc.syncHooks != nil {
2024-05-14 13:07:09 +00:00
cc.syncHooks.blockUntil(func() bool {
2024-05-14 13:07:09 +00:00
select {
2024-05-14 13:07:09 +00:00
case <-c:
2024-05-14 13:07:09 +00:00
case <-errc:
2024-05-14 13:07:09 +00:00
case <-ctx.Done():
2024-05-14 13:07:09 +00:00
case <-cc.readerDone:
2024-05-14 13:07:09 +00:00
default:
2024-05-14 13:07:09 +00:00
return false
2024-05-14 13:07:09 +00:00
}
2024-05-14 13:07:09 +00:00
return true
2024-05-14 13:07:09 +00:00
})
2024-05-14 13:07:09 +00:00
}
2024-02-18 10:42:21 +00:00
select {
2024-02-18 10:42:21 +00:00
case <-c:
2024-02-18 10:42:21 +00:00
return nil
2024-05-14 13:07:09 +00:00
case <-errc:
2024-05-14 13:07:09 +00:00
return pingError
2024-02-18 10:42:21 +00:00
case <-ctx.Done():
2024-02-18 10:42:21 +00:00
return ctx.Err()
2024-02-18 10:42:21 +00:00
case <-cc.readerDone:
2024-02-18 10:42:21 +00:00
// connection closed
2024-02-18 10:42:21 +00:00
return cc.readerErr
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func (rl *clientConnReadLoop) processPing(f *PingFrame) error {
2024-02-18 10:42:21 +00:00
if f.IsAck() {
2024-02-18 10:42:21 +00:00
cc := rl.cc
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.mu.Unlock()
2024-02-18 10:42:21 +00:00
// If ack, notify listener if any
2024-02-18 10:42:21 +00:00
if c, ok := cc.pings[f.Data]; ok {
2024-02-18 10:42:21 +00:00
close(c)
2024-02-18 10:42:21 +00:00
delete(cc.pings, f.Data)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc := rl.cc
2024-02-18 10:42:21 +00:00
cc.wmu.Lock()
2024-02-18 10:42:21 +00:00
defer cc.wmu.Unlock()
2024-02-18 10:42:21 +00:00
if err := cc.fr.WritePing(true, f.Data); err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return cc.bw.Flush()
2024-02-18 10:42:21 +00:00
}
func (rl *clientConnReadLoop) processPushPromise(f *PushPromiseFrame) error {
2024-02-18 10:42:21 +00:00
// We told the peer we don't want them.
2024-02-18 10:42:21 +00:00
// Spec says:
2024-02-18 10:42:21 +00:00
// "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH
2024-02-18 10:42:21 +00:00
// setting of the peer endpoint is set to 0. An endpoint that
2024-02-18 10:42:21 +00:00
// has set this setting and has received acknowledgement MUST
2024-02-18 10:42:21 +00:00
// treat the receipt of a PUSH_PROMISE frame as a connection
2024-02-18 10:42:21 +00:00
// error (Section 5.4.1) of type PROTOCOL_ERROR."
2024-02-18 10:42:21 +00:00
return ConnectionError(ErrCodeProtocol)
2024-02-18 10:42:21 +00:00
}
func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) {
2024-02-18 10:42:21 +00:00
// TODO: map err to more interesting error codes, once the
2024-02-18 10:42:21 +00:00
// HTTP community comes up with some. But currently for
2024-02-18 10:42:21 +00:00
// RST_STREAM there's no equivalent to GOAWAY frame's debug
2024-02-18 10:42:21 +00:00
// data, and the error codes are all pretty vague ("cancel").
2024-02-18 10:42:21 +00:00
cc.wmu.Lock()
2024-02-18 10:42:21 +00:00
cc.fr.WriteRSTStream(streamID, code)
2024-02-18 10:42:21 +00:00
cc.bw.Flush()
2024-02-18 10:42:21 +00:00
cc.wmu.Unlock()
2024-02-18 10:42:21 +00:00
}
var (
errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
errRequestHeaderListSize = errors.New("http2: request header list larger than peer's advertised limit")
2024-02-18 10:42:21 +00:00
)
func (cc *ClientConn) logf(format string, args ...interface{}) {
2024-02-18 10:42:21 +00:00
cc.t.logf(format, args...)
2024-02-18 10:42:21 +00:00
}
func (cc *ClientConn) vlogf(format string, args ...interface{}) {
2024-02-18 10:42:21 +00:00
cc.t.vlogf(format, args...)
2024-02-18 10:42:21 +00:00
}
func (t *Transport) vlogf(format string, args ...interface{}) {
2024-02-18 10:42:21 +00:00
if VerboseLogs {
2024-02-18 10:42:21 +00:00
t.logf(format, args...)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func (t *Transport) logf(format string, args ...interface{}) {
2024-02-18 10:42:21 +00:00
log.Printf(format, args...)
2024-02-18 10:42:21 +00:00
}
var noBody io.ReadCloser = noBodyReader{}
type noBodyReader struct{}
func (noBodyReader) Close() error { return nil }
2024-02-18 10:42:21 +00:00
func (noBodyReader) Read([]byte) (int, error) { return 0, io.EOF }
type missingBody struct{}
func (missingBody) Close() error { return nil }
2024-02-18 10:42:21 +00:00
func (missingBody) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF }
func strSliceContains(ss []string, s string) bool {
2024-02-18 10:42:21 +00:00
for _, v := range ss {
2024-02-18 10:42:21 +00:00
if v == s {
2024-02-18 10:42:21 +00:00
return true
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return false
2024-02-18 10:42:21 +00:00
}
type erringRoundTripper struct{ err error }
func (rt erringRoundTripper) RoundTripErr() error { return rt.err }
2024-02-18 10:42:21 +00:00
func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err }
// gzipReader wraps a response body so it can lazily
2024-02-18 10:42:21 +00:00
// call gzip.NewReader on the first call to Read
2024-02-18 10:42:21 +00:00
type gzipReader struct {
_ incomparable
2024-02-18 10:42:21 +00:00
body io.ReadCloser // underlying Response.Body
zr *gzip.Reader // lazily-initialized gzip reader
zerr error // sticky error
2024-02-18 10:42:21 +00:00
}
func (gz *gzipReader) Read(p []byte) (n int, err error) {
2024-02-18 10:42:21 +00:00
if gz.zerr != nil {
2024-02-18 10:42:21 +00:00
return 0, gz.zerr
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
if gz.zr == nil {
2024-02-18 10:42:21 +00:00
gz.zr, err = gzip.NewReader(gz.body)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
gz.zerr = err
2024-02-18 10:42:21 +00:00
return 0, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return gz.zr.Read(p)
2024-02-18 10:42:21 +00:00
}
func (gz *gzipReader) Close() error {
2024-02-18 10:42:21 +00:00
if err := gz.body.Close(); err != nil {
2024-02-18 10:42:21 +00:00
return err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
gz.zerr = fs.ErrClosed
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
type errorReader struct{ err error }
func (r errorReader) Read(p []byte) (int, error) { return 0, r.err }
// isConnectionCloseRequest reports whether req should use its own
2024-02-18 10:42:21 +00:00
// connection for a single request and then close the connection.
2024-02-18 10:42:21 +00:00
func isConnectionCloseRequest(req *http.Request) bool {
2024-02-18 10:42:21 +00:00
return req.Close || httpguts.HeaderValuesContainsToken(req.Header["Connection"], "close")
2024-02-18 10:42:21 +00:00
}
// registerHTTPSProtocol calls Transport.RegisterProtocol but
2024-02-18 10:42:21 +00:00
// converting panics into errors.
2024-02-18 10:42:21 +00:00
func registerHTTPSProtocol(t *http.Transport, rt noDialH2RoundTripper) (err error) {
2024-02-18 10:42:21 +00:00
defer func() {
2024-02-18 10:42:21 +00:00
if e := recover(); e != nil {
2024-02-18 10:42:21 +00:00
err = fmt.Errorf("%v", e)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}()
2024-02-18 10:42:21 +00:00
t.RegisterProtocol("https", rt)
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
// noDialH2RoundTripper is a RoundTripper which only tries to complete the request
2024-02-18 10:42:21 +00:00
// if there's already has a cached connection to the host.
2024-02-18 10:42:21 +00:00
// (The field is exported so it can be accessed via reflect from net/http; tested
2024-02-18 10:42:21 +00:00
// by TestNoDialH2RoundTripperType)
2024-02-18 10:42:21 +00:00
type noDialH2RoundTripper struct{ *Transport }
func (rt noDialH2RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
2024-02-18 10:42:21 +00:00
res, err := rt.Transport.RoundTrip(req)
2024-02-18 10:42:21 +00:00
if isNoCachedConnError(err) {
2024-02-18 10:42:21 +00:00
return nil, http.ErrSkipAltProtocol
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return res, err
2024-02-18 10:42:21 +00:00
}
func (t *Transport) idleConnTimeout() time.Duration {
2024-05-14 13:07:09 +00:00
// to keep things backwards compatible, we use non-zero values of
2024-05-14 13:07:09 +00:00
// IdleConnTimeout, followed by using the IdleConnTimeout on the underlying
2024-05-14 13:07:09 +00:00
// http1 transport, followed by 0
2024-05-14 13:07:09 +00:00
if t.IdleConnTimeout != 0 {
2024-05-14 13:07:09 +00:00
return t.IdleConnTimeout
2024-05-14 13:07:09 +00:00
}
2024-02-18 10:42:21 +00:00
if t.t1 != nil {
2024-02-18 10:42:21 +00:00
return t.t1.IdleConnTimeout
2024-02-18 10:42:21 +00:00
}
2024-05-14 13:07:09 +00:00
2024-02-18 10:42:21 +00:00
return 0
2024-02-18 10:42:21 +00:00
}
func traceGetConn(req *http.Request, hostPort string) {
2024-02-18 10:42:21 +00:00
trace := httptrace.ContextClientTrace(req.Context())
2024-02-18 10:42:21 +00:00
if trace == nil || trace.GetConn == nil {
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
trace.GetConn(hostPort)
2024-02-18 10:42:21 +00:00
}
func traceGotConn(req *http.Request, cc *ClientConn, reused bool) {
2024-02-18 10:42:21 +00:00
trace := httptrace.ContextClientTrace(req.Context())
2024-02-18 10:42:21 +00:00
if trace == nil || trace.GotConn == nil {
2024-02-18 10:42:21 +00:00
return
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
ci := httptrace.GotConnInfo{Conn: cc.tconn}
2024-02-18 10:42:21 +00:00
ci.Reused = reused
2024-02-18 10:42:21 +00:00
cc.mu.Lock()
2024-02-18 10:42:21 +00:00
ci.WasIdle = len(cc.streams) == 0 && reused
2024-02-18 10:42:21 +00:00
if ci.WasIdle && !cc.lastActive.IsZero() {
2024-02-18 10:42:21 +00:00
ci.IdleTime = time.Since(cc.lastActive)
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
cc.mu.Unlock()
trace.GotConn(ci)
2024-02-18 10:42:21 +00:00
}
func traceWroteHeaders(trace *httptrace.ClientTrace) {
2024-02-18 10:42:21 +00:00
if trace != nil && trace.WroteHeaders != nil {
2024-02-18 10:42:21 +00:00
trace.WroteHeaders()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func traceGot100Continue(trace *httptrace.ClientTrace) {
2024-02-18 10:42:21 +00:00
if trace != nil && trace.Got100Continue != nil {
2024-02-18 10:42:21 +00:00
trace.Got100Continue()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func traceWait100Continue(trace *httptrace.ClientTrace) {
2024-02-18 10:42:21 +00:00
if trace != nil && trace.Wait100Continue != nil {
2024-02-18 10:42:21 +00:00
trace.Wait100Continue()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func traceWroteRequest(trace *httptrace.ClientTrace, err error) {
2024-02-18 10:42:21 +00:00
if trace != nil && trace.WroteRequest != nil {
2024-02-18 10:42:21 +00:00
trace.WroteRequest(httptrace.WroteRequestInfo{Err: err})
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func traceFirstResponseByte(trace *httptrace.ClientTrace) {
2024-02-18 10:42:21 +00:00
if trace != nil && trace.GotFirstResponseByte != nil {
2024-02-18 10:42:21 +00:00
trace.GotFirstResponseByte()
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func traceHasWroteHeaderField(trace *httptrace.ClientTrace) bool {
2024-02-18 10:42:21 +00:00
return trace != nil && trace.WroteHeaderField != nil
2024-02-18 10:42:21 +00:00
}
func traceWroteHeaderField(trace *httptrace.ClientTrace, k, v string) {
2024-02-18 10:42:21 +00:00
if trace != nil && trace.WroteHeaderField != nil {
2024-02-18 10:42:21 +00:00
trace.WroteHeaderField(k, []string{v})
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
}
func traceGot1xxResponseFunc(trace *httptrace.ClientTrace) func(int, textproto.MIMEHeader) error {
2024-02-18 10:42:21 +00:00
if trace != nil {
2024-02-18 10:42:21 +00:00
return trace.Got1xxResponse
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
return nil
2024-02-18 10:42:21 +00:00
}
// dialTLSWithContext uses tls.Dialer, added in Go 1.15, to open a TLS
2024-02-18 10:42:21 +00:00
// connection.
2024-02-18 10:42:21 +00:00
func (t *Transport) dialTLSWithContext(ctx context.Context, network, addr string, cfg *tls.Config) (*tls.Conn, error) {
2024-02-18 10:42:21 +00:00
dialer := &tls.Dialer{
2024-02-18 10:42:21 +00:00
Config: cfg,
}
2024-02-18 10:42:21 +00:00
cn, err := dialer.DialContext(ctx, network, addr)
2024-02-18 10:42:21 +00:00
if err != nil {
2024-02-18 10:42:21 +00:00
return nil, err
2024-02-18 10:42:21 +00:00
}
2024-02-18 10:42:21 +00:00
tlsCn := cn.(*tls.Conn) // DialContext comment promises this will always succeed
2024-02-18 10:42:21 +00:00
return tlsCn, nil
2024-02-18 10:42:21 +00:00
}