PageRenderTime 58ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/vendor/golang.org/x/net/http2/transport.go

http://github.com/bradfitz/camlistore
Go | 2610 lines | 1980 code | 248 blank | 382 comment | 614 complexity | ec236f8a8e8fa8ca0d2c74c1f907dab5 MD5 | raw file
Possible License(s): CC0-1.0, MIT, BSD-3-Clause, 0BSD, MPL-2.0-no-copyleft-exception, BSD-2-Clause, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. // Copyright 2015 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Transport code.
  5. package http2
  6. import (
  7. "bufio"
  8. "bytes"
  9. "compress/gzip"
  10. "context"
  11. "crypto/rand"
  12. "crypto/tls"
  13. "errors"
  14. "fmt"
  15. "io"
  16. "io/ioutil"
  17. "log"
  18. "math"
  19. mathrand "math/rand"
  20. "net"
  21. "net/http"
  22. "net/http/httptrace"
  23. "net/textproto"
  24. "sort"
  25. "strconv"
  26. "strings"
  27. "sync"
  28. "sync/atomic"
  29. "time"
  30. "golang.org/x/net/http/httpguts"
  31. "golang.org/x/net/http2/hpack"
  32. "golang.org/x/net/idna"
  33. )
  34. const (
  35. // transportDefaultConnFlow is how many connection-level flow control
  36. // tokens we give the server at start-up, past the default 64k.
  37. transportDefaultConnFlow = 1 << 30
  38. // transportDefaultStreamFlow is how many stream-level flow
  39. // control tokens we announce to the peer, and how many bytes
  40. // we buffer per stream.
  41. transportDefaultStreamFlow = 4 << 20
  42. // transportDefaultStreamMinRefresh is the minimum number of bytes we'll send
  43. // a stream-level WINDOW_UPDATE for at a time.
  44. transportDefaultStreamMinRefresh = 4 << 10
  45. defaultUserAgent = "Go-http-client/2.0"
  46. )
  47. // Transport is an HTTP/2 Transport.
  48. //
  49. // A Transport internally caches connections to servers. It is safe
  50. // for concurrent use by multiple goroutines.
  51. type Transport struct {
  52. // DialTLS specifies an optional dial function for creating
  53. // TLS connections for requests.
  54. //
  55. // If DialTLS is nil, tls.Dial is used.
  56. //
  57. // If the returned net.Conn has a ConnectionState method like tls.Conn,
  58. // it will be used to set http.Response.TLS.
  59. DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error)
  60. // TLSClientConfig specifies the TLS configuration to use with
  61. // tls.Client. If nil, the default configuration is used.
  62. TLSClientConfig *tls.Config
  63. // ConnPool optionally specifies an alternate connection pool to use.
  64. // If nil, the default is used.
  65. ConnPool ClientConnPool
  66. // DisableCompression, if true, prevents the Transport from
  67. // requesting compression with an "Accept-Encoding: gzip"
  68. // request header when the Request contains no existing
  69. // Accept-Encoding value. If the Transport requests gzip on
  70. // its own and gets a gzipped response, it's transparently
  71. // decoded in the Response.Body. However, if the user
  72. // explicitly requested gzip it is not automatically
  73. // uncompressed.
  74. DisableCompression bool
  75. // AllowHTTP, if true, permits HTTP/2 requests using the insecure,
  76. // plain-text "http" scheme. Note that this does not enable h2c support.
  77. AllowHTTP bool
  78. // MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
  79. // send in the initial settings frame. It is how many bytes
  80. // of response headers are allowed. Unlike the http2 spec, zero here
  81. // means to use a default limit (currently 10MB). If you actually
  82. // want to advertise an ulimited value to the peer, Transport
  83. // interprets the highest possible value here (0xffffffff or 1<<32-1)
  84. // to mean no limit.
  85. MaxHeaderListSize uint32
  86. // StrictMaxConcurrentStreams controls whether the server's
  87. // SETTINGS_MAX_CONCURRENT_STREAMS should be respected
  88. // globally. If false, new TCP connections are created to the
  89. // server as needed to keep each under the per-connection
  90. // SETTINGS_MAX_CONCURRENT_STREAMS limit. If true, the
  91. // server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as
  92. // a global limit and callers of RoundTrip block when needed,
  93. // waiting for their turn.
  94. StrictMaxConcurrentStreams bool
  95. // t1, if non-nil, is the standard library Transport using
  96. // this transport. Its settings are used (but not its
  97. // RoundTrip method, etc).
  98. t1 *http.Transport
  99. connPoolOnce sync.Once
  100. connPoolOrDef ClientConnPool // non-nil version of ConnPool
  101. }
  102. func (t *Transport) maxHeaderListSize() uint32 {
  103. if t.MaxHeaderListSize == 0 {
  104. return 10 << 20
  105. }
  106. if t.MaxHeaderListSize == 0xffffffff {
  107. return 0
  108. }
  109. return t.MaxHeaderListSize
  110. }
  111. func (t *Transport) disableCompression() bool {
  112. return t.DisableCompression || (t.t1 != nil && t.t1.DisableCompression)
  113. }
  114. // ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2.
  115. // It returns an error if t1 has already been HTTP/2-enabled.
  116. func ConfigureTransport(t1 *http.Transport) error {
  117. _, err := configureTransport(t1)
  118. return err
  119. }
  120. func configureTransport(t1 *http.Transport) (*Transport, error) {
  121. connPool := new(clientConnPool)
  122. t2 := &Transport{
  123. ConnPool: noDialClientConnPool{connPool},
  124. t1: t1,
  125. }
  126. connPool.t = t2
  127. if err := registerHTTPSProtocol(t1, noDialH2RoundTripper{t2}); err != nil {
  128. return nil, err
  129. }
  130. if t1.TLSClientConfig == nil {
  131. t1.TLSClientConfig = new(tls.Config)
  132. }
  133. if !strSliceContains(t1.TLSClientConfig.NextProtos, "h2") {
  134. t1.TLSClientConfig.NextProtos = append([]string{"h2"}, t1.TLSClientConfig.NextProtos...)
  135. }
  136. if !strSliceContains(t1.TLSClientConfig.NextProtos, "http/1.1") {
  137. t1.TLSClientConfig.NextProtos = append(t1.TLSClientConfig.NextProtos, "http/1.1")
  138. }
  139. upgradeFn := func(authority string, c *tls.Conn) http.RoundTripper {
  140. addr := authorityAddr("https", authority)
  141. if used, err := connPool.addConnIfNeeded(addr, t2, c); err != nil {
  142. go c.Close()
  143. return erringRoundTripper{err}
  144. } else if !used {
  145. // Turns out we don't need this c.
  146. // For example, two goroutines made requests to the same host
  147. // at the same time, both kicking off TCP dials. (since protocol
  148. // was unknown)
  149. go c.Close()
  150. }
  151. return t2
  152. }
  153. if m := t1.TLSNextProto; len(m) == 0 {
  154. t1.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{
  155. "h2": upgradeFn,
  156. }
  157. } else {
  158. m["h2"] = upgradeFn
  159. }
  160. return t2, nil
  161. }
  162. func (t *Transport) connPool() ClientConnPool {
  163. t.connPoolOnce.Do(t.initConnPool)
  164. return t.connPoolOrDef
  165. }
  166. func (t *Transport) initConnPool() {
  167. if t.ConnPool != nil {
  168. t.connPoolOrDef = t.ConnPool
  169. } else {
  170. t.connPoolOrDef = &clientConnPool{t: t}
  171. }
  172. }
  173. // ClientConn is the state of a single HTTP/2 client connection to an
  174. // HTTP/2 server.
  175. type ClientConn struct {
  176. t *Transport
  177. tconn net.Conn // usually *tls.Conn, except specialized impls
  178. tlsState *tls.ConnectionState // nil only for specialized impls
  179. reused uint32 // whether conn is being reused; atomic
  180. singleUse bool // whether being used for a single http.Request
  181. // readLoop goroutine fields:
  182. readerDone chan struct{} // closed on error
  183. readerErr error // set before readerDone is closed
  184. idleTimeout time.Duration // or 0 for never
  185. idleTimer *time.Timer
  186. mu sync.Mutex // guards following
  187. cond *sync.Cond // hold mu; broadcast on flow/closed changes
  188. flow flow // our conn-level flow control quota (cs.flow is per stream)
  189. inflow flow // peer's conn-level flow control
  190. closing bool
  191. closed bool
  192. wantSettingsAck bool // we sent a SETTINGS frame and haven't heard back
  193. goAway *GoAwayFrame // if non-nil, the GoAwayFrame we received
  194. goAwayDebug string // goAway frame's debug data, retained as a string
  195. streams map[uint32]*clientStream // client-initiated
  196. nextStreamID uint32
  197. pendingRequests int // requests blocked and waiting to be sent because len(streams) == maxConcurrentStreams
  198. pings map[[8]byte]chan struct{} // in flight ping data to notification channel
  199. bw *bufio.Writer
  200. br *bufio.Reader
  201. fr *Framer
  202. lastActive time.Time
  203. // Settings from peer: (also guarded by mu)
  204. maxFrameSize uint32
  205. maxConcurrentStreams uint32
  206. peerMaxHeaderListSize uint64
  207. initialWindowSize uint32
  208. hbuf bytes.Buffer // HPACK encoder writes into this
  209. henc *hpack.Encoder
  210. freeBuf [][]byte
  211. wmu sync.Mutex // held while writing; acquire AFTER mu if holding both
  212. werr error // first write error that has occurred
  213. }
  214. // clientStream is the state for a single HTTP/2 stream. One of these
  215. // is created for each Transport.RoundTrip call.
  216. type clientStream struct {
  217. cc *ClientConn
  218. req *http.Request
  219. trace *httptrace.ClientTrace // or nil
  220. ID uint32
  221. resc chan resAndError
  222. bufPipe pipe // buffered pipe with the flow-controlled response payload
  223. startedWrite bool // started request body write; guarded by cc.mu
  224. requestedGzip bool
  225. on100 func() // optional code to run if get a 100 continue response
  226. flow flow // guarded by cc.mu
  227. inflow flow // guarded by cc.mu
  228. bytesRemain int64 // -1 means unknown; owned by transportResponseBody.Read
  229. readErr error // sticky read error; owned by transportResponseBody.Read
  230. stopReqBody error // if non-nil, stop writing req body; guarded by cc.mu
  231. didReset bool // whether we sent a RST_STREAM to the server; guarded by cc.mu
  232. peerReset chan struct{} // closed on peer reset
  233. resetErr error // populated before peerReset is closed
  234. done chan struct{} // closed when stream remove from cc.streams map; close calls guarded by cc.mu
  235. // owned by clientConnReadLoop:
  236. firstByte bool // got the first response byte
  237. pastHeaders bool // got first MetaHeadersFrame (actual headers)
  238. pastTrailers bool // got optional second MetaHeadersFrame (trailers)
  239. num1xx uint8 // number of 1xx responses seen
  240. trailer http.Header // accumulated trailers
  241. resTrailer *http.Header // client's Response.Trailer
  242. }
  243. // awaitRequestCancel waits for the user to cancel a request or for the done
  244. // channel to be signaled. A non-nil error is returned only if the request was
  245. // canceled.
  246. func awaitRequestCancel(req *http.Request, done <-chan struct{}) error {
  247. ctx := req.Context()
  248. if req.Cancel == nil && ctx.Done() == nil {
  249. return nil
  250. }
  251. select {
  252. case <-req.Cancel:
  253. return errRequestCanceled
  254. case <-ctx.Done():
  255. return ctx.Err()
  256. case <-done:
  257. return nil
  258. }
  259. }
  260. var got1xxFuncForTests func(int, textproto.MIMEHeader) error
  261. // get1xxTraceFunc returns the value of request's httptrace.ClientTrace.Got1xxResponse func,
  262. // if any. It returns nil if not set or if the Go version is too old.
  263. func (cs *clientStream) get1xxTraceFunc() func(int, textproto.MIMEHeader) error {
  264. if fn := got1xxFuncForTests; fn != nil {
  265. return fn
  266. }
  267. return traceGot1xxResponseFunc(cs.trace)
  268. }
  269. // awaitRequestCancel waits for the user to cancel a request, its context to
  270. // expire, or for the request to be done (any way it might be removed from the
  271. // cc.streams map: peer reset, successful completion, TCP connection breakage,
  272. // etc). If the request is canceled, then cs will be canceled and closed.
  273. func (cs *clientStream) awaitRequestCancel(req *http.Request) {
  274. if err := awaitRequestCancel(req, cs.done); err != nil {
  275. cs.cancelStream()
  276. cs.bufPipe.CloseWithError(err)
  277. }
  278. }
  279. func (cs *clientStream) cancelStream() {
  280. cc := cs.cc
  281. cc.mu.Lock()
  282. didReset := cs.didReset
  283. cs.didReset = true
  284. cc.mu.Unlock()
  285. if !didReset {
  286. cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  287. cc.forgetStreamID(cs.ID)
  288. }
  289. }
  290. // checkResetOrDone reports any error sent in a RST_STREAM frame by the
  291. // server, or errStreamClosed if the stream is complete.
  292. func (cs *clientStream) checkResetOrDone() error {
  293. select {
  294. case <-cs.peerReset:
  295. return cs.resetErr
  296. case <-cs.done:
  297. return errStreamClosed
  298. default:
  299. return nil
  300. }
  301. }
  302. func (cs *clientStream) getStartedWrite() bool {
  303. cc := cs.cc
  304. cc.mu.Lock()
  305. defer cc.mu.Unlock()
  306. return cs.startedWrite
  307. }
  308. func (cs *clientStream) abortRequestBodyWrite(err error) {
  309. if err == nil {
  310. panic("nil error")
  311. }
  312. cc := cs.cc
  313. cc.mu.Lock()
  314. cs.stopReqBody = err
  315. cc.cond.Broadcast()
  316. cc.mu.Unlock()
  317. }
  318. type stickyErrWriter struct {
  319. w io.Writer
  320. err *error
  321. }
  322. func (sew stickyErrWriter) Write(p []byte) (n int, err error) {
  323. if *sew.err != nil {
  324. return 0, *sew.err
  325. }
  326. n, err = sew.w.Write(p)
  327. *sew.err = err
  328. return
  329. }
  330. // noCachedConnError is the concrete type of ErrNoCachedConn, which
  331. // needs to be detected by net/http regardless of whether it's its
  332. // bundled version (in h2_bundle.go with a rewritten type name) or
  333. // from a user's x/net/http2. As such, as it has a unique method name
  334. // (IsHTTP2NoCachedConnError) that net/http sniffs for via func
  335. // isNoCachedConnError.
  336. type noCachedConnError struct{}
  337. func (noCachedConnError) IsHTTP2NoCachedConnError() {}
  338. func (noCachedConnError) Error() string { return "http2: no cached connection was available" }
  339. // isNoCachedConnError reports whether err is of type noCachedConnError
  340. // or its equivalent renamed type in net/http2's h2_bundle.go. Both types
  341. // may coexist in the same running program.
  342. func isNoCachedConnError(err error) bool {
  343. _, ok := err.(interface{ IsHTTP2NoCachedConnError() })
  344. return ok
  345. }
  346. var ErrNoCachedConn error = noCachedConnError{}
  347. // RoundTripOpt are options for the Transport.RoundTripOpt method.
  348. type RoundTripOpt struct {
  349. // OnlyCachedConn controls whether RoundTripOpt may
  350. // create a new TCP connection. If set true and
  351. // no cached connection is available, RoundTripOpt
  352. // will return ErrNoCachedConn.
  353. OnlyCachedConn bool
  354. }
  355. func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
  356. return t.RoundTripOpt(req, RoundTripOpt{})
  357. }
  358. // authorityAddr returns a given authority (a host/IP, or host:port / ip:port)
  359. // and returns a host:port. The port 443 is added if needed.
  360. func authorityAddr(scheme string, authority string) (addr string) {
  361. host, port, err := net.SplitHostPort(authority)
  362. if err != nil { // authority didn't have a port
  363. port = "443"
  364. if scheme == "http" {
  365. port = "80"
  366. }
  367. host = authority
  368. }
  369. if a, err := idna.ToASCII(host); err == nil {
  370. host = a
  371. }
  372. // IPv6 address literal, without a port:
  373. if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
  374. return host + ":" + port
  375. }
  376. return net.JoinHostPort(host, port)
  377. }
  378. // RoundTripOpt is like RoundTrip, but takes options.
  379. func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) {
  380. if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) {
  381. return nil, errors.New("http2: unsupported scheme")
  382. }
  383. addr := authorityAddr(req.URL.Scheme, req.URL.Host)
  384. for retry := 0; ; retry++ {
  385. cc, err := t.connPool().GetClientConn(req, addr)
  386. if err != nil {
  387. t.vlogf("http2: Transport failed to get client conn for %s: %v", addr, err)
  388. return nil, err
  389. }
  390. reused := !atomic.CompareAndSwapUint32(&cc.reused, 0, 1)
  391. traceGotConn(req, cc, reused)
  392. res, gotErrAfterReqBodyWrite, err := cc.roundTrip(req)
  393. if err != nil && retry <= 6 {
  394. if req, err = shouldRetryRequest(req, err, gotErrAfterReqBodyWrite); err == nil {
  395. // After the first retry, do exponential backoff with 10% jitter.
  396. if retry == 0 {
  397. continue
  398. }
  399. backoff := float64(uint(1) << (uint(retry) - 1))
  400. backoff += backoff * (0.1 * mathrand.Float64())
  401. select {
  402. case <-time.After(time.Second * time.Duration(backoff)):
  403. continue
  404. case <-req.Context().Done():
  405. return nil, req.Context().Err()
  406. }
  407. }
  408. }
  409. if err != nil {
  410. t.vlogf("RoundTrip failure: %v", err)
  411. return nil, err
  412. }
  413. return res, nil
  414. }
  415. }
  416. // CloseIdleConnections closes any connections which were previously
  417. // connected from previous requests but are now sitting idle.
  418. // It does not interrupt any connections currently in use.
  419. func (t *Transport) CloseIdleConnections() {
  420. if cp, ok := t.connPool().(clientConnPoolIdleCloser); ok {
  421. cp.closeIdleConnections()
  422. }
  423. }
  424. var (
  425. errClientConnClosed = errors.New("http2: client conn is closed")
  426. errClientConnUnusable = errors.New("http2: client conn not usable")
  427. errClientConnGotGoAway = errors.New("http2: Transport received Server's graceful shutdown GOAWAY")
  428. )
  429. // shouldRetryRequest is called by RoundTrip when a request fails to get
  430. // response headers. It is always called with a non-nil error.
  431. // It returns either a request to retry (either the same request, or a
  432. // modified clone), or an error if the request can't be replayed.
  433. func shouldRetryRequest(req *http.Request, err error, afterBodyWrite bool) (*http.Request, error) {
  434. if !canRetryError(err) {
  435. return nil, err
  436. }
  437. // If the Body is nil (or http.NoBody), it's safe to reuse
  438. // this request and its Body.
  439. if req.Body == nil || req.Body == http.NoBody {
  440. return req, nil
  441. }
  442. // If the request body can be reset back to its original
  443. // state via the optional req.GetBody, do that.
  444. if req.GetBody != nil {
  445. // TODO: consider a req.Body.Close here? or audit that all caller paths do?
  446. body, err := req.GetBody()
  447. if err != nil {
  448. return nil, err
  449. }
  450. newReq := *req
  451. newReq.Body = body
  452. return &newReq, nil
  453. }
  454. // The Request.Body can't reset back to the beginning, but we
  455. // don't seem to have started to read from it yet, so reuse
  456. // the request directly. The "afterBodyWrite" means the
  457. // bodyWrite process has started, which becomes true before
  458. // the first Read.
  459. if !afterBodyWrite {
  460. return req, nil
  461. }
  462. return nil, fmt.Errorf("http2: Transport: cannot retry err [%v] after Request.Body was written; define Request.GetBody to avoid this error", err)
  463. }
  464. func canRetryError(err error) bool {
  465. if err == errClientConnUnusable || err == errClientConnGotGoAway {
  466. return true
  467. }
  468. if se, ok := err.(StreamError); ok {
  469. return se.Code == ErrCodeRefusedStream
  470. }
  471. return false
  472. }
  473. func (t *Transport) dialClientConn(addr string, singleUse bool) (*ClientConn, error) {
  474. host, _, err := net.SplitHostPort(addr)
  475. if err != nil {
  476. return nil, err
  477. }
  478. tconn, err := t.dialTLS()("tcp", addr, t.newTLSConfig(host))
  479. if err != nil {
  480. return nil, err
  481. }
  482. return t.newClientConn(tconn, singleUse)
  483. }
  484. func (t *Transport) newTLSConfig(host string) *tls.Config {
  485. cfg := new(tls.Config)
  486. if t.TLSClientConfig != nil {
  487. *cfg = *t.TLSClientConfig.Clone()
  488. }
  489. if !strSliceContains(cfg.NextProtos, NextProtoTLS) {
  490. cfg.NextProtos = append([]string{NextProtoTLS}, cfg.NextProtos...)
  491. }
  492. if cfg.ServerName == "" {
  493. cfg.ServerName = host
  494. }
  495. return cfg
  496. }
  497. func (t *Transport) dialTLS() func(string, string, *tls.Config) (net.Conn, error) {
  498. if t.DialTLS != nil {
  499. return t.DialTLS
  500. }
  501. return t.dialTLSDefault
  502. }
  503. func (t *Transport) dialTLSDefault(network, addr string, cfg *tls.Config) (net.Conn, error) {
  504. cn, err := tls.Dial(network, addr, cfg)
  505. if err != nil {
  506. return nil, err
  507. }
  508. if err := cn.Handshake(); err != nil {
  509. return nil, err
  510. }
  511. if !cfg.InsecureSkipVerify {
  512. if err := cn.VerifyHostname(cfg.ServerName); err != nil {
  513. return nil, err
  514. }
  515. }
  516. state := cn.ConnectionState()
  517. if p := state.NegotiatedProtocol; p != NextProtoTLS {
  518. return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, NextProtoTLS)
  519. }
  520. if !state.NegotiatedProtocolIsMutual {
  521. return nil, errors.New("http2: could not negotiate protocol mutually")
  522. }
  523. return cn, nil
  524. }
  525. // disableKeepAlives reports whether connections should be closed as
  526. // soon as possible after handling the first request.
  527. func (t *Transport) disableKeepAlives() bool {
  528. return t.t1 != nil && t.t1.DisableKeepAlives
  529. }
  530. func (t *Transport) expectContinueTimeout() time.Duration {
  531. if t.t1 == nil {
  532. return 0
  533. }
  534. return t.t1.ExpectContinueTimeout
  535. }
  536. func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) {
  537. return t.newClientConn(c, false)
  538. }
  539. func (t *Transport) newClientConn(c net.Conn, singleUse bool) (*ClientConn, error) {
  540. cc := &ClientConn{
  541. t: t,
  542. tconn: c,
  543. readerDone: make(chan struct{}),
  544. nextStreamID: 1,
  545. maxFrameSize: 16 << 10, // spec default
  546. initialWindowSize: 65535, // spec default
  547. maxConcurrentStreams: 1000, // "infinite", per spec. 1000 seems good enough.
  548. peerMaxHeaderListSize: 0xffffffffffffffff, // "infinite", per spec. Use 2^64-1 instead.
  549. streams: make(map[uint32]*clientStream),
  550. singleUse: singleUse,
  551. wantSettingsAck: true,
  552. pings: make(map[[8]byte]chan struct{}),
  553. }
  554. if d := t.idleConnTimeout(); d != 0 {
  555. cc.idleTimeout = d
  556. cc.idleTimer = time.AfterFunc(d, cc.onIdleTimeout)
  557. }
  558. if VerboseLogs {
  559. t.vlogf("http2: Transport creating client conn %p to %v", cc, c.RemoteAddr())
  560. }
  561. cc.cond = sync.NewCond(&cc.mu)
  562. cc.flow.add(int32(initialWindowSize))
  563. // TODO: adjust this writer size to account for frame size +
  564. // MTU + crypto/tls record padding.
  565. cc.bw = bufio.NewWriter(stickyErrWriter{c, &cc.werr})
  566. cc.br = bufio.NewReader(c)
  567. cc.fr = NewFramer(cc.bw, cc.br)
  568. cc.fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil)
  569. cc.fr.MaxHeaderListSize = t.maxHeaderListSize()
  570. // TODO: SetMaxDynamicTableSize, SetMaxDynamicTableSizeLimit on
  571. // henc in response to SETTINGS frames?
  572. cc.henc = hpack.NewEncoder(&cc.hbuf)
  573. if t.AllowHTTP {
  574. cc.nextStreamID = 3
  575. }
  576. if cs, ok := c.(connectionStater); ok {
  577. state := cs.ConnectionState()
  578. cc.tlsState = &state
  579. }
  580. initialSettings := []Setting{
  581. {ID: SettingEnablePush, Val: 0},
  582. {ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow},
  583. }
  584. if max := t.maxHeaderListSize(); max != 0 {
  585. initialSettings = append(initialSettings, Setting{ID: SettingMaxHeaderListSize, Val: max})
  586. }
  587. cc.bw.Write(clientPreface)
  588. cc.fr.WriteSettings(initialSettings...)
  589. cc.fr.WriteWindowUpdate(0, transportDefaultConnFlow)
  590. cc.inflow.add(transportDefaultConnFlow + initialWindowSize)
  591. cc.bw.Flush()
  592. if cc.werr != nil {
  593. return nil, cc.werr
  594. }
  595. go cc.readLoop()
  596. return cc, nil
  597. }
  598. func (cc *ClientConn) setGoAway(f *GoAwayFrame) {
  599. cc.mu.Lock()
  600. defer cc.mu.Unlock()
  601. old := cc.goAway
  602. cc.goAway = f
  603. // Merge the previous and current GoAway error frames.
  604. if cc.goAwayDebug == "" {
  605. cc.goAwayDebug = string(f.DebugData())
  606. }
  607. if old != nil && old.ErrCode != ErrCodeNo {
  608. cc.goAway.ErrCode = old.ErrCode
  609. }
  610. last := f.LastStreamID
  611. for streamID, cs := range cc.streams {
  612. if streamID > last {
  613. select {
  614. case cs.resc <- resAndError{err: errClientConnGotGoAway}:
  615. default:
  616. }
  617. }
  618. }
  619. }
  620. // CanTakeNewRequest reports whether the connection can take a new request,
  621. // meaning it has not been closed or received or sent a GOAWAY.
  622. func (cc *ClientConn) CanTakeNewRequest() bool {
  623. cc.mu.Lock()
  624. defer cc.mu.Unlock()
  625. return cc.canTakeNewRequestLocked()
  626. }
  627. // clientConnIdleState describes the suitability of a client
  628. // connection to initiate a new RoundTrip request.
  629. type clientConnIdleState struct {
  630. canTakeNewRequest bool
  631. freshConn bool // whether it's unused by any previous request
  632. }
  633. func (cc *ClientConn) idleState() clientConnIdleState {
  634. cc.mu.Lock()
  635. defer cc.mu.Unlock()
  636. return cc.idleStateLocked()
  637. }
  638. func (cc *ClientConn) idleStateLocked() (st clientConnIdleState) {
  639. if cc.singleUse && cc.nextStreamID > 1 {
  640. return
  641. }
  642. var maxConcurrentOkay bool
  643. if cc.t.StrictMaxConcurrentStreams {
  644. // We'll tell the caller we can take a new request to
  645. // prevent the caller from dialing a new TCP
  646. // connection, but then we'll block later before
  647. // writing it.
  648. maxConcurrentOkay = true
  649. } else {
  650. maxConcurrentOkay = int64(len(cc.streams)+1) < int64(cc.maxConcurrentStreams)
  651. }
  652. st.canTakeNewRequest = cc.goAway == nil && !cc.closed && !cc.closing && maxConcurrentOkay &&
  653. int64(cc.nextStreamID)+2*int64(cc.pendingRequests) < math.MaxInt32
  654. st.freshConn = cc.nextStreamID == 1 && st.canTakeNewRequest
  655. return
  656. }
  657. func (cc *ClientConn) canTakeNewRequestLocked() bool {
  658. st := cc.idleStateLocked()
  659. return st.canTakeNewRequest
  660. }
  661. // onIdleTimeout is called from a time.AfterFunc goroutine. It will
  662. // only be called when we're idle, but because we're coming from a new
  663. // goroutine, there could be a new request coming in at the same time,
  664. // so this simply calls the synchronized closeIfIdle to shut down this
  665. // connection. The timer could just call closeIfIdle, but this is more
  666. // clear.
  667. func (cc *ClientConn) onIdleTimeout() {
  668. cc.closeIfIdle()
  669. }
  670. func (cc *ClientConn) closeIfIdle() {
  671. cc.mu.Lock()
  672. if len(cc.streams) > 0 {
  673. cc.mu.Unlock()
  674. return
  675. }
  676. cc.closed = true
  677. nextID := cc.nextStreamID
  678. // TODO: do clients send GOAWAY too? maybe? Just Close:
  679. cc.mu.Unlock()
  680. if VerboseLogs {
  681. cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, nextID-2)
  682. }
  683. cc.tconn.Close()
  684. }
  685. var shutdownEnterWaitStateHook = func() {}
  686. // Shutdown gracefully close the client connection, waiting for running streams to complete.
  687. func (cc *ClientConn) Shutdown(ctx context.Context) error {
  688. if err := cc.sendGoAway(); err != nil {
  689. return err
  690. }
  691. // Wait for all in-flight streams to complete or connection to close
  692. done := make(chan error, 1)
  693. cancelled := false // guarded by cc.mu
  694. go func() {
  695. cc.mu.Lock()
  696. defer cc.mu.Unlock()
  697. for {
  698. if len(cc.streams) == 0 || cc.closed {
  699. cc.closed = true
  700. done <- cc.tconn.Close()
  701. break
  702. }
  703. if cancelled {
  704. break
  705. }
  706. cc.cond.Wait()
  707. }
  708. }()
  709. shutdownEnterWaitStateHook()
  710. select {
  711. case err := <-done:
  712. return err
  713. case <-ctx.Done():
  714. cc.mu.Lock()
  715. // Free the goroutine above
  716. cancelled = true
  717. cc.cond.Broadcast()
  718. cc.mu.Unlock()
  719. return ctx.Err()
  720. }
  721. }
  722. func (cc *ClientConn) sendGoAway() error {
  723. cc.mu.Lock()
  724. defer cc.mu.Unlock()
  725. cc.wmu.Lock()
  726. defer cc.wmu.Unlock()
  727. if cc.closing {
  728. // GOAWAY sent already
  729. return nil
  730. }
  731. // Send a graceful shutdown frame to server
  732. maxStreamID := cc.nextStreamID
  733. if err := cc.fr.WriteGoAway(maxStreamID, ErrCodeNo, nil); err != nil {
  734. return err
  735. }
  736. if err := cc.bw.Flush(); err != nil {
  737. return err
  738. }
  739. // Prevent new requests
  740. cc.closing = true
  741. return nil
  742. }
  743. // Close closes the client connection immediately.
  744. //
  745. // In-flight requests are interrupted. For a graceful shutdown, use Shutdown instead.
  746. func (cc *ClientConn) Close() error {
  747. cc.mu.Lock()
  748. defer cc.cond.Broadcast()
  749. defer cc.mu.Unlock()
  750. err := errors.New("http2: client connection force closed via ClientConn.Close")
  751. for id, cs := range cc.streams {
  752. select {
  753. case cs.resc <- resAndError{err: err}:
  754. default:
  755. }
  756. cs.bufPipe.CloseWithError(err)
  757. delete(cc.streams, id)
  758. }
  759. cc.closed = true
  760. return cc.tconn.Close()
  761. }
  762. const maxAllocFrameSize = 512 << 10
  763. // frameBuffer returns a scratch buffer suitable for writing DATA frames.
  764. // They're capped at the min of the peer's max frame size or 512KB
  765. // (kinda arbitrarily), but definitely capped so we don't allocate 4GB
  766. // bufers.
  767. func (cc *ClientConn) frameScratchBuffer() []byte {
  768. cc.mu.Lock()
  769. size := cc.maxFrameSize
  770. if size > maxAllocFrameSize {
  771. size = maxAllocFrameSize
  772. }
  773. for i, buf := range cc.freeBuf {
  774. if len(buf) >= int(size) {
  775. cc.freeBuf[i] = nil
  776. cc.mu.Unlock()
  777. return buf[:size]
  778. }
  779. }
  780. cc.mu.Unlock()
  781. return make([]byte, size)
  782. }
  783. func (cc *ClientConn) putFrameScratchBuffer(buf []byte) {
  784. cc.mu.Lock()
  785. defer cc.mu.Unlock()
  786. const maxBufs = 4 // arbitrary; 4 concurrent requests per conn? investigate.
  787. if len(cc.freeBuf) < maxBufs {
  788. cc.freeBuf = append(cc.freeBuf, buf)
  789. return
  790. }
  791. for i, old := range cc.freeBuf {
  792. if old == nil {
  793. cc.freeBuf[i] = buf
  794. return
  795. }
  796. }
  797. // forget about it.
  798. }
  799. // errRequestCanceled is a copy of net/http's errRequestCanceled because it's not
  800. // exported. At least they'll be DeepEqual for h1-vs-h2 comparisons tests.
  801. var errRequestCanceled = errors.New("net/http: request canceled")
  802. func commaSeparatedTrailers(req *http.Request) (string, error) {
  803. keys := make([]string, 0, len(req.Trailer))
  804. for k := range req.Trailer {
  805. k = http.CanonicalHeaderKey(k)
  806. switch k {
  807. case "Transfer-Encoding", "Trailer", "Content-Length":
  808. return "", &badStringError{"invalid Trailer key", k}
  809. }
  810. keys = append(keys, k)
  811. }
  812. if len(keys) > 0 {
  813. sort.Strings(keys)
  814. return strings.Join(keys, ","), nil
  815. }
  816. return "", nil
  817. }
  818. func (cc *ClientConn) responseHeaderTimeout() time.Duration {
  819. if cc.t.t1 != nil {
  820. return cc.t.t1.ResponseHeaderTimeout
  821. }
  822. // No way to do this (yet?) with just an http2.Transport. Probably
  823. // no need. Request.Cancel this is the new way. We only need to support
  824. // this for compatibility with the old http.Transport fields when
  825. // we're doing transparent http2.
  826. return 0
  827. }
  828. // checkConnHeaders checks whether req has any invalid connection-level headers.
  829. // per RFC 7540 section 8.1.2.2: Connection-Specific Header Fields.
  830. // Certain headers are special-cased as okay but not transmitted later.
  831. func checkConnHeaders(req *http.Request) error {
  832. if v := req.Header.Get("Upgrade"); v != "" {
  833. return fmt.Errorf("http2: invalid Upgrade request header: %q", req.Header["Upgrade"])
  834. }
  835. if vv := req.Header["Transfer-Encoding"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "chunked") {
  836. return fmt.Errorf("http2: invalid Transfer-Encoding request header: %q", vv)
  837. }
  838. if vv := req.Header["Connection"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && !strings.EqualFold(vv[0], "close") && !strings.EqualFold(vv[0], "keep-alive")) {
  839. return fmt.Errorf("http2: invalid Connection request header: %q", vv)
  840. }
  841. return nil
  842. }
  843. // actualContentLength returns a sanitized version of
  844. // req.ContentLength, where 0 actually means zero (not unknown) and -1
  845. // means unknown.
  846. func actualContentLength(req *http.Request) int64 {
  847. if req.Body == nil || req.Body == http.NoBody {
  848. return 0
  849. }
  850. if req.ContentLength != 0 {
  851. return req.ContentLength
  852. }
  853. return -1
  854. }
  855. func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) {
  856. resp, _, err := cc.roundTrip(req)
  857. return resp, err
  858. }
  859. func (cc *ClientConn) roundTrip(req *http.Request) (res *http.Response, gotErrAfterReqBodyWrite bool, err error) {
  860. if err := checkConnHeaders(req); err != nil {
  861. return nil, false, err
  862. }
  863. if cc.idleTimer != nil {
  864. cc.idleTimer.Stop()
  865. }
  866. trailers, err := commaSeparatedTrailers(req)
  867. if err != nil {
  868. return nil, false, err
  869. }
  870. hasTrailers := trailers != ""
  871. cc.mu.Lock()
  872. if err := cc.awaitOpenSlotForRequest(req); err != nil {
  873. cc.mu.Unlock()
  874. return nil, false, err
  875. }
  876. body := req.Body
  877. contentLen := actualContentLength(req)
  878. hasBody := contentLen != 0
  879. // TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere?
  880. var requestedGzip bool
  881. if !cc.t.disableCompression() &&
  882. req.Header.Get("Accept-Encoding") == "" &&
  883. req.Header.Get("Range") == "" &&
  884. req.Method != "HEAD" {
  885. // Request gzip only, not deflate. Deflate is ambiguous and
  886. // not as universally supported anyway.
  887. // See: http://www.gzip.org/zlib/zlib_faq.html#faq38
  888. //
  889. // Note that we don't request this for HEAD requests,
  890. // due to a bug in nginx:
  891. // http://trac.nginx.org/nginx/ticket/358
  892. // https://golang.org/issue/5522
  893. //
  894. // We don't request gzip if the request is for a range, since
  895. // auto-decoding a portion of a gzipped document will just fail
  896. // anyway. See https://golang.org/issue/8923
  897. requestedGzip = true
  898. }
  899. // we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,} (DATA is
  900. // sent by writeRequestBody below, along with any Trailers,
  901. // again in form HEADERS{1}, CONTINUATION{0,})
  902. hdrs, err := cc.encodeHeaders(req, requestedGzip, trailers, contentLen)
  903. if err != nil {
  904. cc.mu.Unlock()
  905. return nil, false, err
  906. }
  907. cs := cc.newStream()
  908. cs.req = req
  909. cs.trace = httptrace.ContextClientTrace(req.Context())
  910. cs.requestedGzip = requestedGzip
  911. bodyWriter := cc.t.getBodyWriterState(cs, body)
  912. cs.on100 = bodyWriter.on100
  913. cc.wmu.Lock()
  914. endStream := !hasBody && !hasTrailers
  915. werr := cc.writeHeaders(cs.ID, endStream, int(cc.maxFrameSize), hdrs)
  916. cc.wmu.Unlock()
  917. traceWroteHeaders(cs.trace)
  918. cc.mu.Unlock()
  919. if werr != nil {
  920. if hasBody {
  921. req.Body.Close() // per RoundTripper contract
  922. bodyWriter.cancel()
  923. }
  924. cc.forgetStreamID(cs.ID)
  925. // Don't bother sending a RST_STREAM (our write already failed;
  926. // no need to keep writing)
  927. traceWroteRequest(cs.trace, werr)
  928. return nil, false, werr
  929. }
  930. var respHeaderTimer <-chan time.Time
  931. if hasBody {
  932. bodyWriter.scheduleBodyWrite()
  933. } else {
  934. traceWroteRequest(cs.trace, nil)
  935. if d := cc.responseHeaderTimeout(); d != 0 {
  936. timer := time.NewTimer(d)
  937. defer timer.Stop()
  938. respHeaderTimer = timer.C
  939. }
  940. }
  941. readLoopResCh := cs.resc
  942. bodyWritten := false
  943. ctx := req.Context()
  944. handleReadLoopResponse := func(re resAndError) (*http.Response, bool, error) {
  945. res := re.res
  946. if re.err != nil || res.StatusCode > 299 {
  947. // On error or status code 3xx, 4xx, 5xx, etc abort any
  948. // ongoing write, assuming that the server doesn't care
  949. // about our request body. If the server replied with 1xx or
  950. // 2xx, however, then assume the server DOES potentially
  951. // want our body (e.g. full-duplex streaming:
  952. // golang.org/issue/13444). If it turns out the server
  953. // doesn't, they'll RST_STREAM us soon enough. This is a
  954. // heuristic to avoid adding knobs to Transport. Hopefully
  955. // we can keep it.
  956. bodyWriter.cancel()
  957. cs.abortRequestBodyWrite(errStopReqBodyWrite)
  958. }
  959. if re.err != nil {
  960. cc.forgetStreamID(cs.ID)
  961. return nil, cs.getStartedWrite(), re.err
  962. }
  963. res.Request = req
  964. res.TLS = cc.tlsState
  965. return res, false, nil
  966. }
  967. for {
  968. select {
  969. case re := <-readLoopResCh:
  970. return handleReadLoopResponse(re)
  971. case <-respHeaderTimer:
  972. if !hasBody || bodyWritten {
  973. cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  974. } else {
  975. bodyWriter.cancel()
  976. cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
  977. }
  978. cc.forgetStreamID(cs.ID)
  979. return nil, cs.getStartedWrite(), errTimeout
  980. case <-ctx.Done():
  981. if !hasBody || bodyWritten {
  982. cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  983. } else {
  984. bodyWriter.cancel()
  985. cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
  986. }
  987. cc.forgetStreamID(cs.ID)
  988. return nil, cs.getStartedWrite(), ctx.Err()
  989. case <-req.Cancel:
  990. if !hasBody || bodyWritten {
  991. cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  992. } else {
  993. bodyWriter.cancel()
  994. cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
  995. }
  996. cc.forgetStreamID(cs.ID)
  997. return nil, cs.getStartedWrite(), errRequestCanceled
  998. case <-cs.peerReset:
  999. // processResetStream already removed the
  1000. // stream from the streams map; no need for
  1001. // forgetStreamID.
  1002. return nil, cs.getStartedWrite(), cs.resetErr
  1003. case err := <-bodyWriter.resc:
  1004. // Prefer the read loop's response, if available. Issue 16102.
  1005. select {
  1006. case re := <-readLoopResCh:
  1007. return handleReadLoopResponse(re)
  1008. default:
  1009. }
  1010. if err != nil {
  1011. cc.forgetStreamID(cs.ID)
  1012. return nil, cs.getStartedWrite(), err
  1013. }
  1014. bodyWritten = true
  1015. if d := cc.responseHeaderTimeout(); d != 0 {
  1016. timer := time.NewTimer(d)
  1017. defer timer.Stop()
  1018. respHeaderTimer = timer.C
  1019. }
  1020. }
  1021. }
  1022. }
  1023. // awaitOpenSlotForRequest waits until len(streams) < maxConcurrentStreams.
  1024. // Must hold cc.mu.
  1025. func (cc *ClientConn) awaitOpenSlotForRequest(req *http.Request) error {
  1026. var waitingForConn chan struct{}
  1027. var waitingForConnErr error // guarded by cc.mu
  1028. for {
  1029. cc.lastActive = time.Now()
  1030. if cc.closed || !cc.canTakeNewRequestLocked() {
  1031. if waitingForConn != nil {
  1032. close(waitingForConn)
  1033. }
  1034. return errClientConnUnusable
  1035. }
  1036. if int64(len(cc.streams))+1 <= int64(cc.maxConcurrentStreams) {
  1037. if waitingForConn != nil {
  1038. close(waitingForConn)
  1039. }
  1040. return nil
  1041. }
  1042. // Unfortunately, we cannot wait on a condition variable and channel at
  1043. // the same time, so instead, we spin up a goroutine to check if the
  1044. // request is canceled while we wait for a slot to open in the connection.
  1045. if waitingForConn == nil {
  1046. waitingForConn = make(chan struct{})
  1047. go func() {
  1048. if err := awaitRequestCancel(req, waitingForConn); err != nil {
  1049. cc.mu.Lock()
  1050. waitingForConnErr = err
  1051. cc.cond.Broadcast()
  1052. cc.mu.Unlock()
  1053. }
  1054. }()
  1055. }
  1056. cc.pendingRequests++
  1057. cc.cond.Wait()
  1058. cc.pendingRequests--
  1059. if waitingForConnErr != nil {
  1060. return waitingForConnErr
  1061. }
  1062. }
  1063. }
  1064. // requires cc.wmu be held
  1065. func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, maxFrameSize int, hdrs []byte) error {
  1066. first := true // first frame written (HEADERS is first, then CONTINUATION)
  1067. for len(hdrs) > 0 && cc.werr == nil {
  1068. chunk := hdrs
  1069. if len(chunk) > maxFrameSize {
  1070. chunk = chunk[:maxFrameSize]
  1071. }
  1072. hdrs = hdrs[len(chunk):]
  1073. endHeaders := len(hdrs) == 0
  1074. if first {
  1075. cc.fr.WriteHeaders(HeadersFrameParam{
  1076. StreamID: streamID,
  1077. BlockFragment: chunk,
  1078. EndStream: endStream,
  1079. EndHeaders: endHeaders,
  1080. })
  1081. first = false
  1082. } else {
  1083. cc.fr.WriteContinuation(streamID, endHeaders, chunk)
  1084. }
  1085. }
  1086. // TODO(bradfitz): this Flush could potentially block (as
  1087. // could the WriteHeaders call(s) above), which means they
  1088. // wouldn't respond to Request.Cancel being readable. That's
  1089. // rare, but this should probably be in a goroutine.
  1090. cc.bw.Flush()
  1091. return cc.werr
  1092. }
  1093. // internal error values; they don't escape to callers
  1094. var (
  1095. // abort request body write; don't send cancel
  1096. errStopReqBodyWrite = errors.New("http2: aborting request body write")
  1097. // abort request body write, but send stream reset of cancel.
  1098. errStopReqBodyWriteAndCancel = errors.New("http2: canceling request")
  1099. )
  1100. func (cs *clientStream) writeRequestBody(body io.Reader, bodyCloser io.Closer) (err error) {
  1101. cc := cs.cc
  1102. sentEnd := false // whether we sent the final DATA frame w/ END_STREAM
  1103. buf := cc.frameScratchBuffer()
  1104. defer cc.putFrameScratchBuffer(buf)
  1105. defer func() {
  1106. traceWroteRequest(cs.trace, err)
  1107. // TODO: write h12Compare test showing whether
  1108. // Request.Body is closed by the Transport,
  1109. // and in multiple cases: server replies <=299 and >299
  1110. // while still writing request body
  1111. cerr := bodyCloser.Close()
  1112. if err == nil {
  1113. err = cerr
  1114. }
  1115. }()
  1116. req := cs.req
  1117. hasTrailers := req.Trailer != nil
  1118. var sawEOF bool
  1119. for !sawEOF {
  1120. n, err := body.Read(buf)
  1121. if err == io.EOF {
  1122. sawEOF = true
  1123. err = nil
  1124. } else if err != nil {
  1125. cc.writeStreamReset(cs.ID, ErrCodeCancel, err)
  1126. return err
  1127. }
  1128. remain := buf[:n]
  1129. for len(remain) > 0 && err == nil {
  1130. var allowed int32
  1131. allowed, err = cs.awaitFlowControl(len(remain))
  1132. switch {
  1133. case err == errStopReqBodyWrite:
  1134. return err
  1135. case err == errStopReqBodyWriteAndCancel:
  1136. cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  1137. return err
  1138. case err != nil:
  1139. return err
  1140. }
  1141. cc.wmu.Lock()
  1142. data := remain[:allowed]
  1143. remain = remain[allowed:]
  1144. sentEnd = sawEOF && len(remain) == 0 && !hasTrailers
  1145. err = cc.fr.WriteData(cs.ID, sentEnd, data)
  1146. if err == nil {
  1147. // TODO(bradfitz): this flush is for latency, not bandwidth.
  1148. // Most requests won't need this. Make this opt-in or
  1149. // opt-out? Use some heuristic on the body type? Nagel-like
  1150. // timers? Based on 'n'? Only last chunk of this for loop,
  1151. // unless flow control tokens are low? For now, always.
  1152. // If we change this, see comment below.
  1153. err = cc.bw.Flush()
  1154. }
  1155. cc.wmu.Unlock()
  1156. }
  1157. if err != nil {
  1158. return err
  1159. }
  1160. }
  1161. if sentEnd {
  1162. // Already sent END_STREAM (which implies we have no
  1163. // trailers) and flushed, because currently all
  1164. // WriteData frames above get a flush. So we're done.
  1165. return nil
  1166. }
  1167. var trls []byte
  1168. if hasTrailers {
  1169. cc.mu.Lock()
  1170. trls, err = cc.encodeTrailers(req)
  1171. cc.mu.Unlock()
  1172. if err != nil {
  1173. cc.writeStreamReset(cs.ID, ErrCodeInternal, err)
  1174. cc.forgetStreamID(cs.ID)
  1175. return err
  1176. }
  1177. }
  1178. cc.mu.Lock()
  1179. maxFrameSize := int(cc.maxFrameSize)
  1180. cc.mu.Unlock()
  1181. cc.wmu.Lock()
  1182. defer cc.wmu.Unlock()
  1183. // Two ways to send END_STREAM: either with trailers, or
  1184. // with an empty DATA frame.
  1185. if len(trls) > 0 {
  1186. err = cc.writeHeaders(cs.ID, true, maxFrameSize, trls)
  1187. } else {
  1188. err = cc.fr.WriteData(cs.ID, true, nil)
  1189. }
  1190. if ferr := cc.bw.Flush(); ferr != nil && err == nil {
  1191. err = ferr
  1192. }
  1193. return err
  1194. }
  1195. // awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
  1196. // control tokens from the server.
  1197. // It returns either the non-zero number of tokens taken or an error
  1198. // if the stream is dead.
  1199. func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
  1200. cc := cs.cc
  1201. cc.mu.Lock()
  1202. defer cc.mu.Unlock()
  1203. for {
  1204. if cc.closed {
  1205. return 0, errClientConnClosed
  1206. }
  1207. if cs.stopReqBody != nil {
  1208. return 0, cs.stopReqBody
  1209. }
  1210. if err := cs.checkResetOrDone(); err != nil {
  1211. return 0, err
  1212. }
  1213. if a := cs.flow.available(); a > 0 {
  1214. take := a
  1215. if int(take) > maxBytes {
  1216. take = int32(maxBytes) // can't truncate int; take is int32
  1217. }
  1218. if take > int32(cc.maxFrameSize) {
  1219. take = int32(cc.maxFrameSize)
  1220. }
  1221. cs.flow.take(take)
  1222. return take, nil
  1223. }
  1224. cc.cond.Wait()
  1225. }
  1226. }
  1227. type badStringError struct {
  1228. what string
  1229. str string
  1230. }
  1231. func (e *badStringError) Error() string { return fmt.Sprintf("%s %q", e.what, e.str) }
  1232. // requires cc.mu be held.
  1233. func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) {
  1234. cc.hbuf.Reset()
  1235. host := req.Host
  1236. if host == "" {
  1237. host = req.URL.Host
  1238. }
  1239. host, err := httpguts.PunycodeHostPort(host)
  1240. if err != nil {
  1241. return nil, err
  1242. }
  1243. var path string
  1244. if req.Method != "CONNECT" {
  1245. path = req.URL.RequestURI()
  1246. if !validPseudoPath(path) {
  1247. orig := path
  1248. path = strings.TrimPrefix(path, req.URL.Scheme+"://"+host)
  1249. if !validPseudoPath(path) {
  1250. if req.URL.Opaque != "" {
  1251. return nil, fmt.Errorf("invalid request :path %q from URL.Opaque = %q", orig, req.URL.Opaque)
  1252. } else {
  1253. return nil, fmt.Errorf("invalid request :path %q", orig)
  1254. }
  1255. }
  1256. }
  1257. }
  1258. // Check for any invalid headers and return an error before we
  1259. // potentially pollute our hpack state. (We want to be able to
  1260. // continue to reuse the hpack encoder for future requests)
  1261. for k, vv := range req.Header {
  1262. if !httpguts.ValidHeaderFieldName(k) {
  1263. return nil, fmt.Errorf("invalid HTTP header name %q", k)
  1264. }
  1265. for _, v := range vv {
  1266. if !httpguts.ValidHeaderFieldValue(v) {
  1267. return nil, fmt.Errorf("invalid HTTP header value %q for header %q", v, k)
  1268. }
  1269. }
  1270. }
  1271. enumerateHeaders := func(f func(name, value string)) {
  1272. // 8.1.2.3 Request Pseudo-Header Fields
  1273. // The :path pseudo-header field includes the path and query parts of the
  1274. // target URI (the path-absolute production and optionally a '?' character
  1275. // followed by the query production (see Sections 3.3 and 3.4 of
  1276. // [RFC3986]).
  1277. f(":authority", host)
  1278. m := req.Method
  1279. if m == "" {
  1280. m = http.MethodGet
  1281. }
  1282. f(":method", m)
  1283. if req.Method != "CONNECT" {
  1284. f(":path", path)
  1285. f(":scheme", req.URL.Scheme)
  1286. }
  1287. if trailers != "" {
  1288. f("trailer", trailers)
  1289. }
  1290. var didUA bool
  1291. for k, vv := range req.Header {
  1292. if strings.EqualFold(k, "host") || strings.EqualFold(k, "content-length") {
  1293. // Host is :authority, already sent.
  1294. // Content-Length is automatic, set below.
  1295. continue
  1296. } else if strings.EqualFold(k, "connection") || strings.EqualFold(k, "proxy-connection") ||
  1297. strings.EqualFold(k, "transfer-encoding") || strings.EqualFold(k, "upgrade") ||
  1298. strings.EqualFold(k, "keep-alive") {
  1299. // Per 8.1.2.2 Connection-Specific Header
  1300. // Fields, don't send connection-specific
  1301. // fields. We have already checked if any
  1302. // are error-worthy so just ignore the rest.
  1303. continue
  1304. } else if strings.EqualFold(k, "user-agent") {
  1305. // Match Go's http1 behavior: at most one
  1306. // User-Agent. If set to nil or empty string,
  1307. // then omit it. Otherwise if not mentioned,
  1308. // include the default (below).
  1309. didUA = true
  1310. if len(vv) < 1 {
  1311. continue
  1312. }
  1313. vv = vv[:1]
  1314. if vv[0] == "" {
  1315. continue
  1316. }
  1317. }
  1318. for _, v := range vv {
  1319. f(k, v)
  1320. }
  1321. }
  1322. if shouldSendReqContentLength(req.Method, contentLength) {
  1323. f("content-length", strconv.FormatInt(contentLength, 10))
  1324. }
  1325. if addGzipHeader {
  1326. f("accept-encoding", "gzip")
  1327. }
  1328. if !didUA {
  1329. f("user-agent", defaultUserAgent)
  1330. }
  1331. }
  1332. // Do a first pass over the headers counting bytes to ensure
  1333. // we don't exceed cc.peerMaxHeaderListSize. This is done as a
  1334. // separate pass before encoding the headers to prevent
  1335. // modifying the hpack state.
  1336. hlSize := uint64(0)
  1337. enumerateHeaders(func(name, value string) {
  1338. hf := hpack.HeaderField{Name: name, Value: value}
  1339. hlSize += uint64(hf.Size())
  1340. })
  1341. if hlSize > cc.peerMaxHeaderListSize {
  1342. return nil, errRequestHeaderListSize
  1343. }
  1344. trace := httptrace.ContextClientTrace(req.Context())
  1345. traceHeaders := traceHasWroteHeaderField(trace)
  1346. // Header list size is ok. Write the headers.
  1347. enumerateHeaders(func(name, value string) {
  1348. name = strings.ToLower(name)
  1349. cc.writeHeader(name, value)
  1350. if traceHeaders {
  1351. traceWroteHeaderField(trace, name, value)
  1352. }
  1353. })
  1354. return cc.hbuf.Bytes(), nil
  1355. }
  1356. // shouldSendReqContentLength reports whether the http2.Transport should send
  1357. // a "content-length" request header. This logic is basically a copy of the net/http
  1358. // transferWriter.shouldSendContentLength.
  1359. // The contentLength is the corrected contentLength (so 0 means actually 0, not unknown).
  1360. // -1 means unknown.
  1361. func shouldSendReqContentLength(method string, contentLength int64) bool {
  1362. if contentLength > 0 {
  1363. return true
  1364. }
  1365. if contentLength < 0 {
  1366. return false
  1367. }
  1368. // For zero bodies, whether we send a content-length depends on the method.
  1369. // It also kinda doesn't matter for http2 either way, with END_STREAM.
  1370. switch method {
  1371. case "POST", "PUT", "PATCH":
  1372. return true
  1373. default:
  1374. return false
  1375. }
  1376. }
  1377. // requires cc.mu be held.
  1378. func (cc *ClientConn) encodeTrailers(req *http.Request) ([]byte, error) {
  1379. cc.hbuf.Reset()
  1380. hlSize := uint64(0)
  1381. for k, vv := range req.Trailer {
  1382. for _, v := range vv {
  1383. hf := hpack.HeaderField{Name: k, Value: v}
  1384. hlSize += uint64(hf.Size())
  1385. }
  1386. }
  1387. if hlSize > cc.peerMaxHeaderListSize {
  1388. return nil, errRequestHeaderListSize
  1389. }
  1390. for k, vv := range req.Trailer {
  1391. // Transfer-Encoding, etc.. have already been filtered at the
  1392. // start of RoundTrip
  1393. lowKey := strings.ToLower(k)
  1394. for _, v := range vv {
  1395. cc.writeHeader(lowKey, v)
  1396. }
  1397. }
  1398. return cc.hbuf.Bytes(), nil
  1399. }
  1400. func (cc *ClientConn) writeHeader(name, value string) {
  1401. if VerboseLogs {
  1402. log.Printf("http2: Transport encoding header %q = %q", name, value)
  1403. }
  1404. cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
  1405. }
  1406. type resAndError struct {
  1407. res *http.Response
  1408. err error
  1409. }
  1410. // requires cc.mu be held.
  1411. func (cc *ClientConn) newStream() *clientStream {
  1412. cs := &clientStream{
  1413. cc: cc,
  1414. ID: cc.nextStreamID,
  1415. resc: make(chan resAndError, 1),
  1416. peerReset: make(chan struct{}),
  1417. done: make(chan struct{}),
  1418. }
  1419. cs.flow.add(int32(cc.initialWindowSize))
  1420. cs.flow.setConnFlow(&cc.flow)
  1421. cs.inflow.add(transportDefaultStreamFlow)
  1422. cs.inflow.setConnFlow(&cc.inflow)
  1423. cc.nextStreamID += 2
  1424. cc.streams[cs.ID] = cs
  1425. return cs
  1426. }
  1427. func (cc *ClientConn) forgetStreamID(id uint32) {
  1428. cc.streamByID(id, true)
  1429. }
  1430. func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream {
  1431. cc.mu.Lock()
  1432. defer cc.mu.Unlock()
  1433. cs := cc.streams[id]
  1434. if andRemove && cs != nil && !cc.closed {
  1435. cc.lastActive = time.Now()
  1436. delete(cc.streams, id)
  1437. if len(cc.streams) == 0 && cc.idleTimer != nil {
  1438. cc.idleTimer.Reset(cc.idleTimeout)
  1439. }
  1440. close(cs.done)
  1441. // Wake up checkResetOrDone via clientStream.awaitFlowControl and
  1442. // wake up RoundTrip if there is a pending request.
  1443. cc.cond.Broadcast()
  1444. }
  1445. return cs
  1446. }
  1447. // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.
  1448. type clientConnReadLoop struct {
  1449. cc *ClientConn
  1450. closeWhenIdle bool
  1451. }
  1452. // readLoop runs in its own goroutine and reads and dispatches frames.
  1453. func (cc *ClientConn) readLoop() {
  1454. rl := &clientConnReadLoop{cc: cc}
  1455. defer rl.cleanup()
  1456. cc.readerErr = rl.run()
  1457. if ce, ok := cc.readerErr.(ConnectionError); ok {
  1458. cc.wmu.Lock()
  1459. cc.fr.WriteGoAway(0, ErrCode(ce), nil)
  1460. cc.wmu.Unlock()
  1461. }
  1462. }
  1463. // GoAwayError is returned by the Transport when the server closes the
  1464. // TCP connection after sending a GOAWAY frame.
  1465. type GoAwayError struct {
  1466. LastStreamID uint32
  1467. ErrCode ErrCode
  1468. DebugData string
  1469. }
  1470. func (e GoAwayError) Error() string {
  1471. return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q",
  1472. e.LastStreamID, e.ErrCode, e.DebugData)
  1473. }
  1474. func isEOFOrNetReadError(err error) bool {
  1475. if err == io.EOF {
  1476. return true
  1477. }
  1478. ne, ok := err.(*net.OpError)
  1479. return ok && ne.Op == "read"
  1480. }
  1481. func (rl *clientConnReadLoop) cleanup() {
  1482. cc := rl.cc
  1483. defer cc.tconn.Close()
  1484. defer cc.t.connPool().MarkDead(cc)
  1485. defer close(cc.readerDone)
  1486. if cc.idleTimer != nil {
  1487. cc.idleTimer.Stop()
  1488. }
  1489. // Close any response bodies if the server closes prematurely.
  1490. // TODO: also do this if we've written the headers but not
  1491. // gotten a response yet.
  1492. err := cc.readerErr
  1493. cc.mu.Lock()
  1494. if cc.goAway != nil && isEOFOrNetReadError(err) {
  1495. err = GoAwayError{
  1496. LastStreamID: cc.goAway.LastStreamID,
  1497. ErrCode: cc.goAway.ErrCode,
  1498. DebugData: cc.goAwayDebug,
  1499. }
  1500. } else if err == io.EOF {
  1501. err = io.ErrUnexpectedEOF
  1502. }
  1503. for _, cs := range cc.streams {
  1504. cs.bufPipe.CloseWithError(err) // no-op if already closed
  1505. select {
  1506. case cs.resc <- resAndError{err: err}:
  1507. default:
  1508. }
  1509. close(cs.done)
  1510. }
  1511. cc.closed = true
  1512. cc.cond.Broadcast()
  1513. cc.mu.Unlock()
  1514. }
  1515. func (rl *clientConnReadLoop) run() error {
  1516. cc := rl.cc
  1517. rl.closeWhenIdle = cc.t.disableKeepAlives() || cc.singleUse
  1518. gotReply := false // ever saw a HEADERS reply
  1519. gotSettings := false
  1520. for {
  1521. f, err := cc.fr.ReadFrame()
  1522. if err != nil {
  1523. cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err)
  1524. }
  1525. if se, ok := err.(StreamError); ok {
  1526. if cs := cc.streamByID(se.StreamID, false); cs != nil {
  1527. cs.cc.writeStreamReset(cs.ID, se.Code, err)
  1528. cs.cc.forgetStreamID(cs.ID)
  1529. if se.Cause == nil {
  1530. se.Cause = cc.fr.errDetail
  1531. }
  1532. rl.endStreamError(cs, se)
  1533. }
  1534. continue
  1535. } else if err != nil {
  1536. return err
  1537. }
  1538. if VerboseLogs {
  1539. cc.vlogf("http2: Transport received %s", summarizeFrame(f))
  1540. }
  1541. if !gotSettings {
  1542. if _, ok := f.(*SettingsFrame); !ok {
  1543. cc.logf("protocol error: received %T before a SETTINGS frame", f)
  1544. return ConnectionError(ErrCodeProtocol)

Large files files are truncated, but you can click here to view the full file