You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

2129 lines
58 KiB

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