transport.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  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/tls"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "io/ioutil"
  15. "log"
  16. "net"
  17. "net/http"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "golang.org/x/net/http2/hpack"
  22. )
  23. const (
  24. // transportDefaultConnFlow is how many connection-level flow control
  25. // tokens we give the server at start-up, past the default 64k.
  26. transportDefaultConnFlow = 1 << 30
  27. // transportDefaultStreamFlow is how many stream-level flow
  28. // control tokens we announce to the peer, and how many bytes
  29. // we buffer per stream.
  30. transportDefaultStreamFlow = 4 << 20
  31. // transportDefaultStreamMinRefresh is the minimum number of bytes we'll send
  32. // a stream-level WINDOW_UPDATE for at a time.
  33. transportDefaultStreamMinRefresh = 4 << 10
  34. )
  35. // Transport is an HTTP/2 Transport.
  36. //
  37. // A Transport internally caches connections to servers. It is safe
  38. // for concurrent use by multiple goroutines.
  39. type Transport struct {
  40. // DialTLS specifies an optional dial function for creating
  41. // TLS connections for requests.
  42. //
  43. // If DialTLS is nil, tls.Dial is used.
  44. //
  45. // If the returned net.Conn has a ConnectionState method like tls.Conn,
  46. // it will be used to set http.Response.TLS.
  47. DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error)
  48. // TLSClientConfig specifies the TLS configuration to use with
  49. // tls.Client. If nil, the default configuration is used.
  50. TLSClientConfig *tls.Config
  51. // ConnPool optionally specifies an alternate connection pool to use.
  52. // If nil, the default is used.
  53. ConnPool ClientConnPool
  54. // DisableCompression, if true, prevents the Transport from
  55. // requesting compression with an "Accept-Encoding: gzip"
  56. // request header when the Request contains no existing
  57. // Accept-Encoding value. If the Transport requests gzip on
  58. // its own and gets a gzipped response, it's transparently
  59. // decoded in the Response.Body. However, if the user
  60. // explicitly requested gzip it is not automatically
  61. // uncompressed.
  62. DisableCompression bool
  63. connPoolOnce sync.Once
  64. connPoolOrDef ClientConnPool // non-nil version of ConnPool
  65. }
  66. func (t *Transport) disableCompression() bool {
  67. if t.DisableCompression {
  68. return true
  69. }
  70. // TODO: also disable if this transport is somehow linked to an http1 Transport
  71. // and it's configured there?
  72. return false
  73. }
  74. var errTransportVersion = errors.New("http2: ConfigureTransport is only supported starting at Go 1.6")
  75. // ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2.
  76. // It requires Go 1.6 or later and returns an error if the net/http package is too old
  77. // or if t1 has already been HTTP/2-enabled.
  78. func ConfigureTransport(t1 *http.Transport) error {
  79. return configureTransport(t1) // in configure_transport.go (go1.6) or go15.go
  80. }
  81. func (t *Transport) connPool() ClientConnPool {
  82. t.connPoolOnce.Do(t.initConnPool)
  83. return t.connPoolOrDef
  84. }
  85. func (t *Transport) initConnPool() {
  86. if t.ConnPool != nil {
  87. t.connPoolOrDef = t.ConnPool
  88. } else {
  89. t.connPoolOrDef = &clientConnPool{t: t}
  90. }
  91. }
  92. // ClientConn is the state of a single HTTP/2 client connection to an
  93. // HTTP/2 server.
  94. type ClientConn struct {
  95. t *Transport
  96. tconn net.Conn // usually *tls.Conn, except specialized impls
  97. tlsState *tls.ConnectionState // nil only for specialized impls
  98. // readLoop goroutine fields:
  99. readerDone chan struct{} // closed on error
  100. readerErr error // set before readerDone is closed
  101. mu sync.Mutex // guards following
  102. cond *sync.Cond // hold mu; broadcast on flow/closed changes
  103. flow flow // our conn-level flow control quota (cs.flow is per stream)
  104. inflow flow // peer's conn-level flow control
  105. closed bool
  106. goAway *GoAwayFrame // if non-nil, the GoAwayFrame we received
  107. streams map[uint32]*clientStream // client-initiated
  108. nextStreamID uint32
  109. bw *bufio.Writer
  110. br *bufio.Reader
  111. fr *Framer
  112. // Settings from peer:
  113. maxFrameSize uint32
  114. maxConcurrentStreams uint32
  115. initialWindowSize uint32
  116. hbuf bytes.Buffer // HPACK encoder writes into this
  117. henc *hpack.Encoder
  118. freeBuf [][]byte
  119. wmu sync.Mutex // held while writing; acquire AFTER wmu if holding both
  120. werr error // first write error that has occurred
  121. }
  122. // clientStream is the state for a single HTTP/2 stream. One of these
  123. // is created for each Transport.RoundTrip call.
  124. type clientStream struct {
  125. cc *ClientConn
  126. req *http.Request
  127. ID uint32
  128. resc chan resAndError
  129. bufPipe pipe // buffered pipe with the flow-controlled response payload
  130. requestedGzip bool
  131. flow flow // guarded by cc.mu
  132. inflow flow // guarded by cc.mu
  133. bytesRemain int64 // -1 means unknown; owned by transportResponseBody.Read
  134. readErr error // sticky read error; owned by transportResponseBody.Read
  135. stopReqBody bool // stop writing req body; guarded by cc.mu
  136. peerReset chan struct{} // closed on peer reset
  137. resetErr error // populated before peerReset is closed
  138. }
  139. // checkReset reports any error sent in a RST_STREAM frame by the
  140. // server.
  141. func (cs *clientStream) checkReset() error {
  142. select {
  143. case <-cs.peerReset:
  144. return cs.resetErr
  145. default:
  146. return nil
  147. }
  148. }
  149. func (cs *clientStream) abortRequestBodyWrite() {
  150. cc := cs.cc
  151. cc.mu.Lock()
  152. cs.stopReqBody = true
  153. cc.cond.Broadcast()
  154. cc.mu.Unlock()
  155. }
  156. type stickyErrWriter struct {
  157. w io.Writer
  158. err *error
  159. }
  160. func (sew stickyErrWriter) Write(p []byte) (n int, err error) {
  161. if *sew.err != nil {
  162. return 0, *sew.err
  163. }
  164. n, err = sew.w.Write(p)
  165. *sew.err = err
  166. return
  167. }
  168. var ErrNoCachedConn = errors.New("http2: no cached connection was available")
  169. // RoundTripOpt are options for the Transport.RoundTripOpt method.
  170. type RoundTripOpt struct {
  171. // OnlyCachedConn controls whether RoundTripOpt may
  172. // create a new TCP connection. If set true and
  173. // no cached connection is available, RoundTripOpt
  174. // will return ErrNoCachedConn.
  175. OnlyCachedConn bool
  176. }
  177. func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
  178. return t.RoundTripOpt(req, RoundTripOpt{})
  179. }
  180. // authorityAddr returns a given authority (a host/IP, or host:port / ip:port)
  181. // and returns a host:port. The port 443 is added if needed.
  182. func authorityAddr(authority string) (addr string) {
  183. if _, _, err := net.SplitHostPort(authority); err == nil {
  184. return authority
  185. }
  186. return net.JoinHostPort(authority, "443")
  187. }
  188. // RoundTripOpt is like RoundTrip, but takes options.
  189. func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) {
  190. if req.URL.Scheme != "https" {
  191. return nil, errors.New("http2: unsupported scheme")
  192. }
  193. addr := authorityAddr(req.URL.Host)
  194. for {
  195. cc, err := t.connPool().GetClientConn(req, addr)
  196. if err != nil {
  197. return nil, err
  198. }
  199. res, err := cc.RoundTrip(req)
  200. if shouldRetryRequest(req, err) {
  201. continue
  202. }
  203. if err != nil {
  204. return nil, err
  205. }
  206. return res, nil
  207. }
  208. }
  209. // CloseIdleConnections closes any connections which were previously
  210. // connected from previous requests but are now sitting idle.
  211. // It does not interrupt any connections currently in use.
  212. func (t *Transport) CloseIdleConnections() {
  213. if cp, ok := t.connPool().(*clientConnPool); ok {
  214. cp.closeIdleConnections()
  215. }
  216. }
  217. var (
  218. errClientConnClosed = errors.New("http2: client conn is closed")
  219. errClientConnUnusable = errors.New("http2: client conn not usable")
  220. )
  221. func shouldRetryRequest(req *http.Request, err error) bool {
  222. // TODO: retry GET requests (no bodies) more aggressively, if shutdown
  223. // before response.
  224. return err == errClientConnUnusable
  225. }
  226. func (t *Transport) dialClientConn(addr string) (*ClientConn, error) {
  227. host, _, err := net.SplitHostPort(addr)
  228. if err != nil {
  229. return nil, err
  230. }
  231. tconn, err := t.dialTLS()("tcp", addr, t.newTLSConfig(host))
  232. if err != nil {
  233. return nil, err
  234. }
  235. return t.NewClientConn(tconn)
  236. }
  237. func (t *Transport) newTLSConfig(host string) *tls.Config {
  238. cfg := new(tls.Config)
  239. if t.TLSClientConfig != nil {
  240. *cfg = *t.TLSClientConfig
  241. }
  242. cfg.NextProtos = []string{NextProtoTLS} // TODO: don't override if already in list
  243. cfg.ServerName = host
  244. return cfg
  245. }
  246. func (t *Transport) dialTLS() func(string, string, *tls.Config) (net.Conn, error) {
  247. if t.DialTLS != nil {
  248. return t.DialTLS
  249. }
  250. return t.dialTLSDefault
  251. }
  252. func (t *Transport) dialTLSDefault(network, addr string, cfg *tls.Config) (net.Conn, error) {
  253. cn, err := tls.Dial(network, addr, cfg)
  254. if err != nil {
  255. return nil, err
  256. }
  257. if err := cn.Handshake(); err != nil {
  258. return nil, err
  259. }
  260. if !cfg.InsecureSkipVerify {
  261. if err := cn.VerifyHostname(cfg.ServerName); err != nil {
  262. return nil, err
  263. }
  264. }
  265. state := cn.ConnectionState()
  266. if p := state.NegotiatedProtocol; p != NextProtoTLS {
  267. return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, NextProtoTLS)
  268. }
  269. if !state.NegotiatedProtocolIsMutual {
  270. return nil, errors.New("http2: could not negotiate protocol mutually")
  271. }
  272. return cn, nil
  273. }
  274. func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) {
  275. if _, err := c.Write(clientPreface); err != nil {
  276. return nil, err
  277. }
  278. cc := &ClientConn{
  279. t: t,
  280. tconn: c,
  281. readerDone: make(chan struct{}),
  282. nextStreamID: 1,
  283. maxFrameSize: 16 << 10, // spec default
  284. initialWindowSize: 65535, // spec default
  285. maxConcurrentStreams: 1000, // "infinite", per spec. 1000 seems good enough.
  286. streams: make(map[uint32]*clientStream),
  287. }
  288. cc.cond = sync.NewCond(&cc.mu)
  289. cc.flow.add(int32(initialWindowSize))
  290. // TODO: adjust this writer size to account for frame size +
  291. // MTU + crypto/tls record padding.
  292. cc.bw = bufio.NewWriter(stickyErrWriter{c, &cc.werr})
  293. cc.br = bufio.NewReader(c)
  294. cc.fr = NewFramer(cc.bw, cc.br)
  295. cc.henc = hpack.NewEncoder(&cc.hbuf)
  296. type connectionStater interface {
  297. ConnectionState() tls.ConnectionState
  298. }
  299. if cs, ok := c.(connectionStater); ok {
  300. state := cs.ConnectionState()
  301. cc.tlsState = &state
  302. }
  303. cc.fr.WriteSettings(
  304. Setting{ID: SettingEnablePush, Val: 0},
  305. Setting{ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow},
  306. )
  307. cc.fr.WriteWindowUpdate(0, transportDefaultConnFlow)
  308. cc.inflow.add(transportDefaultConnFlow + initialWindowSize)
  309. cc.bw.Flush()
  310. if cc.werr != nil {
  311. return nil, cc.werr
  312. }
  313. // Read the obligatory SETTINGS frame
  314. f, err := cc.fr.ReadFrame()
  315. if err != nil {
  316. return nil, err
  317. }
  318. sf, ok := f.(*SettingsFrame)
  319. if !ok {
  320. return nil, fmt.Errorf("expected settings frame, got: %T", f)
  321. }
  322. cc.fr.WriteSettingsAck()
  323. cc.bw.Flush()
  324. sf.ForeachSetting(func(s Setting) error {
  325. switch s.ID {
  326. case SettingMaxFrameSize:
  327. cc.maxFrameSize = s.Val
  328. case SettingMaxConcurrentStreams:
  329. cc.maxConcurrentStreams = s.Val
  330. case SettingInitialWindowSize:
  331. cc.initialWindowSize = s.Val
  332. default:
  333. // TODO(bradfitz): handle more
  334. t.vlogf("Unhandled Setting: %v", s)
  335. }
  336. return nil
  337. })
  338. go cc.readLoop()
  339. return cc, nil
  340. }
  341. func (cc *ClientConn) setGoAway(f *GoAwayFrame) {
  342. cc.mu.Lock()
  343. defer cc.mu.Unlock()
  344. cc.goAway = f
  345. }
  346. func (cc *ClientConn) CanTakeNewRequest() bool {
  347. cc.mu.Lock()
  348. defer cc.mu.Unlock()
  349. return cc.canTakeNewRequestLocked()
  350. }
  351. func (cc *ClientConn) canTakeNewRequestLocked() bool {
  352. return cc.goAway == nil &&
  353. int64(len(cc.streams)+1) < int64(cc.maxConcurrentStreams) &&
  354. cc.nextStreamID < 2147483647
  355. }
  356. func (cc *ClientConn) closeIfIdle() {
  357. cc.mu.Lock()
  358. if len(cc.streams) > 0 {
  359. cc.mu.Unlock()
  360. return
  361. }
  362. cc.closed = true
  363. // TODO: do clients send GOAWAY too? maybe? Just Close:
  364. cc.mu.Unlock()
  365. cc.tconn.Close()
  366. }
  367. const maxAllocFrameSize = 512 << 10
  368. // frameBuffer returns a scratch buffer suitable for writing DATA frames.
  369. // They're capped at the min of the peer's max frame size or 512KB
  370. // (kinda arbitrarily), but definitely capped so we don't allocate 4GB
  371. // bufers.
  372. func (cc *ClientConn) frameScratchBuffer() []byte {
  373. cc.mu.Lock()
  374. size := cc.maxFrameSize
  375. if size > maxAllocFrameSize {
  376. size = maxAllocFrameSize
  377. }
  378. for i, buf := range cc.freeBuf {
  379. if len(buf) >= int(size) {
  380. cc.freeBuf[i] = nil
  381. cc.mu.Unlock()
  382. return buf[:size]
  383. }
  384. }
  385. cc.mu.Unlock()
  386. return make([]byte, size)
  387. }
  388. func (cc *ClientConn) putFrameScratchBuffer(buf []byte) {
  389. cc.mu.Lock()
  390. defer cc.mu.Unlock()
  391. const maxBufs = 4 // arbitrary; 4 concurrent requests per conn? investigate.
  392. if len(cc.freeBuf) < maxBufs {
  393. cc.freeBuf = append(cc.freeBuf, buf)
  394. return
  395. }
  396. for i, old := range cc.freeBuf {
  397. if old == nil {
  398. cc.freeBuf[i] = buf
  399. return
  400. }
  401. }
  402. // forget about it.
  403. }
  404. func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) {
  405. cc.mu.Lock()
  406. if cc.closed || !cc.canTakeNewRequestLocked() {
  407. cc.mu.Unlock()
  408. return nil, errClientConnUnusable
  409. }
  410. cs := cc.newStream()
  411. cs.req = req
  412. hasBody := req.Body != nil
  413. // TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere?
  414. if !cc.t.disableCompression() &&
  415. req.Header.Get("Accept-Encoding") == "" &&
  416. req.Header.Get("Range") == "" &&
  417. req.Method != "HEAD" {
  418. // Request gzip only, not deflate. Deflate is ambiguous and
  419. // not as universally supported anyway.
  420. // See: http://www.gzip.org/zlib/zlib_faq.html#faq38
  421. //
  422. // Note that we don't request this for HEAD requests,
  423. // due to a bug in nginx:
  424. // http://trac.nginx.org/nginx/ticket/358
  425. // https://golang.org/issue/5522
  426. //
  427. // We don't request gzip if the request is for a range, since
  428. // auto-decoding a portion of a gzipped document will just fail
  429. // anyway. See https://golang.org/issue/8923
  430. cs.requestedGzip = true
  431. }
  432. // we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,}
  433. hdrs := cc.encodeHeaders(req, cs.requestedGzip)
  434. first := true // first frame written (HEADERS is first, then CONTINUATION)
  435. cc.wmu.Lock()
  436. frameSize := int(cc.maxFrameSize)
  437. for len(hdrs) > 0 && cc.werr == nil {
  438. chunk := hdrs
  439. if len(chunk) > frameSize {
  440. chunk = chunk[:frameSize]
  441. }
  442. hdrs = hdrs[len(chunk):]
  443. endHeaders := len(hdrs) == 0
  444. if first {
  445. cc.fr.WriteHeaders(HeadersFrameParam{
  446. StreamID: cs.ID,
  447. BlockFragment: chunk,
  448. EndStream: !hasBody,
  449. EndHeaders: endHeaders,
  450. })
  451. first = false
  452. } else {
  453. cc.fr.WriteContinuation(cs.ID, endHeaders, chunk)
  454. }
  455. }
  456. cc.bw.Flush()
  457. werr := cc.werr
  458. cc.wmu.Unlock()
  459. cc.mu.Unlock()
  460. if werr != nil {
  461. return nil, werr
  462. }
  463. var bodyCopyErrc chan error // result of body copy
  464. if hasBody {
  465. bodyCopyErrc = make(chan error, 1)
  466. go func() {
  467. bodyCopyErrc <- cs.writeRequestBody(req.Body)
  468. }()
  469. }
  470. for {
  471. select {
  472. case re := <-cs.resc:
  473. res := re.res
  474. if re.err != nil || res.StatusCode > 299 {
  475. // On error or status code 3xx, 4xx, 5xx, etc abort any
  476. // ongoing write, assuming that the server doesn't care
  477. // about our request body. If the server replied with 1xx or
  478. // 2xx, however, then assume the server DOES potentially
  479. // want our body (e.g. full-duplex streaming:
  480. // golang.org/issue/13444). If it turns out the server
  481. // doesn't, they'll RST_STREAM us soon enough. This is a
  482. // heuristic to avoid adding knobs to Transport. Hopefully
  483. // we can keep it.
  484. cs.abortRequestBodyWrite()
  485. }
  486. if re.err != nil {
  487. return nil, re.err
  488. }
  489. res.Request = req
  490. res.TLS = cc.tlsState
  491. return res, nil
  492. case err := <-bodyCopyErrc:
  493. if err != nil {
  494. return nil, err
  495. }
  496. }
  497. }
  498. }
  499. // errAbortReqBodyWrite is an internal error value.
  500. // It doesn't escape to callers.
  501. var errAbortReqBodyWrite = errors.New("http2: aborting request body write")
  502. func (cs *clientStream) writeRequestBody(body io.ReadCloser) (err error) {
  503. cc := cs.cc
  504. sentEnd := false // whether we sent the final DATA frame w/ END_STREAM
  505. buf := cc.frameScratchBuffer()
  506. defer cc.putFrameScratchBuffer(buf)
  507. defer func() {
  508. // TODO: write h12Compare test showing whether
  509. // Request.Body is closed by the Transport,
  510. // and in multiple cases: server replies <=299 and >299
  511. // while still writing request body
  512. cerr := body.Close()
  513. if err == nil {
  514. err = cerr
  515. }
  516. }()
  517. var sawEOF bool
  518. for !sawEOF {
  519. n, err := body.Read(buf)
  520. if err == io.EOF {
  521. sawEOF = true
  522. err = nil
  523. } else if err != nil {
  524. return err
  525. }
  526. remain := buf[:n]
  527. for len(remain) > 0 && err == nil {
  528. var allowed int32
  529. allowed, err = cs.awaitFlowControl(len(remain))
  530. if err != nil {
  531. return err
  532. }
  533. cc.wmu.Lock()
  534. data := remain[:allowed]
  535. remain = remain[allowed:]
  536. sentEnd = sawEOF && len(remain) == 0
  537. err = cc.fr.WriteData(cs.ID, sentEnd, data)
  538. if err == nil {
  539. // TODO(bradfitz): this flush is for latency, not bandwidth.
  540. // Most requests won't need this. Make this opt-in or opt-out?
  541. // Use some heuristic on the body type? Nagel-like timers?
  542. // Based on 'n'? Only last chunk of this for loop, unless flow control
  543. // tokens are low? For now, always:
  544. err = cc.bw.Flush()
  545. }
  546. cc.wmu.Unlock()
  547. }
  548. if err != nil {
  549. return err
  550. }
  551. }
  552. cc.wmu.Lock()
  553. if !sentEnd {
  554. err = cc.fr.WriteData(cs.ID, true, nil)
  555. }
  556. if ferr := cc.bw.Flush(); ferr != nil && err == nil {
  557. err = ferr
  558. }
  559. cc.wmu.Unlock()
  560. return err
  561. }
  562. // awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
  563. // control tokens from the server.
  564. // It returns either the non-zero number of tokens taken or an error
  565. // if the stream is dead.
  566. func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
  567. cc := cs.cc
  568. cc.mu.Lock()
  569. defer cc.mu.Unlock()
  570. for {
  571. if cc.closed {
  572. return 0, errClientConnClosed
  573. }
  574. if cs.stopReqBody {
  575. return 0, errAbortReqBodyWrite
  576. }
  577. if err := cs.checkReset(); err != nil {
  578. return 0, err
  579. }
  580. if a := cs.flow.available(); a > 0 {
  581. take := a
  582. if int(take) > maxBytes {
  583. take = int32(maxBytes) // can't truncate int; take is int32
  584. }
  585. if take > int32(cc.maxFrameSize) {
  586. take = int32(cc.maxFrameSize)
  587. }
  588. cs.flow.take(take)
  589. return take, nil
  590. }
  591. cc.cond.Wait()
  592. }
  593. }
  594. // requires cc.mu be held.
  595. func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool) []byte {
  596. cc.hbuf.Reset()
  597. // TODO(bradfitz): figure out :authority-vs-Host stuff between http2 and Go
  598. host := req.Host
  599. if host == "" {
  600. host = req.URL.Host
  601. }
  602. // 8.1.2.3 Request Pseudo-Header Fields
  603. // The :path pseudo-header field includes the path and query parts of the
  604. // target URI (the path-absolute production and optionally a '?' character
  605. // followed by the query production (see Sections 3.3 and 3.4 of
  606. // [RFC3986]).
  607. cc.writeHeader(":authority", host) // probably not right for all sites
  608. cc.writeHeader(":method", req.Method)
  609. cc.writeHeader(":path", req.URL.RequestURI())
  610. cc.writeHeader(":scheme", "https")
  611. for k, vv := range req.Header {
  612. lowKey := strings.ToLower(k)
  613. if lowKey == "host" {
  614. continue
  615. }
  616. for _, v := range vv {
  617. cc.writeHeader(lowKey, v)
  618. }
  619. }
  620. if addGzipHeader {
  621. cc.writeHeader("accept-encoding", "gzip")
  622. }
  623. return cc.hbuf.Bytes()
  624. }
  625. func (cc *ClientConn) writeHeader(name, value string) {
  626. cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
  627. }
  628. type resAndError struct {
  629. res *http.Response
  630. err error
  631. }
  632. // requires cc.mu be held.
  633. func (cc *ClientConn) newStream() *clientStream {
  634. cs := &clientStream{
  635. cc: cc,
  636. ID: cc.nextStreamID,
  637. resc: make(chan resAndError, 1),
  638. peerReset: make(chan struct{}),
  639. }
  640. cs.flow.add(int32(cc.initialWindowSize))
  641. cs.flow.setConnFlow(&cc.flow)
  642. cs.inflow.add(transportDefaultStreamFlow)
  643. cs.inflow.setConnFlow(&cc.inflow)
  644. cc.nextStreamID += 2
  645. cc.streams[cs.ID] = cs
  646. return cs
  647. }
  648. func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream {
  649. cc.mu.Lock()
  650. defer cc.mu.Unlock()
  651. cs := cc.streams[id]
  652. if andRemove {
  653. delete(cc.streams, id)
  654. }
  655. return cs
  656. }
  657. // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.
  658. type clientConnReadLoop struct {
  659. cc *ClientConn
  660. activeRes map[uint32]*clientStream // keyed by streamID
  661. // continueStreamID is the stream ID we're waiting for
  662. // continuation frames for.
  663. continueStreamID uint32
  664. hdec *hpack.Decoder
  665. // Fields reset on each HEADERS:
  666. nextRes *http.Response
  667. sawRegHeader bool // saw non-pseudo header
  668. reqMalformed error // non-nil once known to be malformed
  669. }
  670. // readLoop runs in its own goroutine and reads and dispatches frames.
  671. func (cc *ClientConn) readLoop() {
  672. rl := &clientConnReadLoop{
  673. cc: cc,
  674. activeRes: make(map[uint32]*clientStream),
  675. }
  676. // TODO: figure out henc size
  677. rl.hdec = hpack.NewDecoder(initialHeaderTableSize, rl.onNewHeaderField)
  678. defer rl.cleanup()
  679. cc.readerErr = rl.run()
  680. if ce, ok := cc.readerErr.(ConnectionError); ok {
  681. cc.wmu.Lock()
  682. cc.fr.WriteGoAway(0, ErrCode(ce), nil)
  683. cc.wmu.Unlock()
  684. }
  685. }
  686. func (rl *clientConnReadLoop) cleanup() {
  687. cc := rl.cc
  688. defer cc.tconn.Close()
  689. defer cc.t.connPool().MarkDead(cc)
  690. defer close(cc.readerDone)
  691. // Close any response bodies if the server closes prematurely.
  692. // TODO: also do this if we've written the headers but not
  693. // gotten a response yet.
  694. err := cc.readerErr
  695. if err == io.EOF {
  696. err = io.ErrUnexpectedEOF
  697. }
  698. cc.mu.Lock()
  699. for _, cs := range rl.activeRes {
  700. cs.bufPipe.CloseWithError(err)
  701. }
  702. for _, cs := range cc.streams {
  703. select {
  704. case cs.resc <- resAndError{err: err}:
  705. default:
  706. }
  707. }
  708. cc.closed = true
  709. cc.cond.Broadcast()
  710. cc.mu.Unlock()
  711. }
  712. func (rl *clientConnReadLoop) run() error {
  713. cc := rl.cc
  714. for {
  715. f, err := cc.fr.ReadFrame()
  716. if se, ok := err.(StreamError); ok {
  717. // TODO: deal with stream errors from the framer.
  718. return se
  719. } else if err != nil {
  720. return err
  721. }
  722. cc.vlogf("Transport received %v: %#v", f.Header(), f)
  723. streamID := f.Header().StreamID
  724. _, isContinue := f.(*ContinuationFrame)
  725. if isContinue {
  726. if streamID != rl.continueStreamID {
  727. cc.logf("Protocol violation: got CONTINUATION with id %d; want %d", streamID, rl.continueStreamID)
  728. return ConnectionError(ErrCodeProtocol)
  729. }
  730. } else if rl.continueStreamID != 0 {
  731. // Continue frames need to be adjacent in the stream
  732. // and we were in the middle of headers.
  733. cc.logf("Protocol violation: got %T for stream %d, want CONTINUATION for %d", f, streamID, rl.continueStreamID)
  734. return ConnectionError(ErrCodeProtocol)
  735. }
  736. switch f := f.(type) {
  737. case *HeadersFrame:
  738. err = rl.processHeaders(f)
  739. case *ContinuationFrame:
  740. err = rl.processContinuation(f)
  741. case *DataFrame:
  742. err = rl.processData(f)
  743. case *GoAwayFrame:
  744. err = rl.processGoAway(f)
  745. case *RSTStreamFrame:
  746. err = rl.processResetStream(f)
  747. case *SettingsFrame:
  748. err = rl.processSettings(f)
  749. case *PushPromiseFrame:
  750. err = rl.processPushPromise(f)
  751. case *WindowUpdateFrame:
  752. err = rl.processWindowUpdate(f)
  753. case *PingFrame:
  754. err = rl.processPing(f)
  755. default:
  756. cc.logf("Transport: unhandled response frame type %T", f)
  757. }
  758. if err != nil {
  759. return err
  760. }
  761. }
  762. }
  763. func (rl *clientConnReadLoop) processHeaders(f *HeadersFrame) error {
  764. rl.sawRegHeader = false
  765. rl.reqMalformed = nil
  766. rl.nextRes = &http.Response{
  767. Proto: "HTTP/2.0",
  768. ProtoMajor: 2,
  769. Header: make(http.Header),
  770. }
  771. return rl.processHeaderBlockFragment(f.HeaderBlockFragment(), f.StreamID, f.HeadersEnded(), f.StreamEnded())
  772. }
  773. func (rl *clientConnReadLoop) processContinuation(f *ContinuationFrame) error {
  774. return rl.processHeaderBlockFragment(f.HeaderBlockFragment(), f.StreamID, f.HeadersEnded(), f.StreamEnded())
  775. }
  776. func (rl *clientConnReadLoop) processHeaderBlockFragment(frag []byte, streamID uint32, headersEnded, streamEnded bool) error {
  777. cc := rl.cc
  778. cs := cc.streamByID(streamID, streamEnded)
  779. if cs == nil {
  780. // We could return a ConnectionError(ErrCodeProtocol)
  781. // here, except that in the case of us canceling
  782. // client requests, we may also delete from the
  783. // streams map, in which case we forgot that we sent
  784. // this request. So, just ignore any responses for
  785. // now. They might've been in-flight before the
  786. // server got our RST_STREAM.
  787. return nil
  788. }
  789. _, err := rl.hdec.Write(frag)
  790. if err != nil {
  791. return err
  792. }
  793. if !headersEnded {
  794. rl.continueStreamID = cs.ID
  795. return nil
  796. }
  797. // HEADERS (or CONTINUATION) are now over.
  798. rl.continueStreamID = 0
  799. if rl.reqMalformed != nil {
  800. cs.resc <- resAndError{err: rl.reqMalformed}
  801. rl.cc.writeStreamReset(cs.ID, ErrCodeProtocol, rl.reqMalformed)
  802. return nil
  803. }
  804. res := rl.nextRes
  805. if !streamEnded || cs.req.Method == "HEAD" {
  806. res.ContentLength = -1
  807. if clens := res.Header["Content-Length"]; len(clens) == 1 {
  808. if clen64, err := strconv.ParseInt(clens[0], 10, 64); err == nil {
  809. res.ContentLength = clen64
  810. } else {
  811. // TODO: care? unlike http/1, it won't mess up our framing, so it's
  812. // more safe smuggling-wise to ignore.
  813. }
  814. } else if len(clens) > 1 {
  815. // TODO: care? unlike http/1, it won't mess up our framing, so it's
  816. // more safe smuggling-wise to ignore.
  817. }
  818. }
  819. if streamEnded {
  820. res.Body = noBody
  821. } else {
  822. buf := new(bytes.Buffer) // TODO(bradfitz): recycle this garbage
  823. cs.bufPipe = pipe{b: buf}
  824. cs.bytesRemain = res.ContentLength
  825. res.Body = transportResponseBody{cs}
  826. if cs.requestedGzip && res.Header.Get("Content-Encoding") == "gzip" {
  827. res.Header.Del("Content-Encoding")
  828. res.Header.Del("Content-Length")
  829. res.ContentLength = -1
  830. res.Body = &gzipReader{body: res.Body}
  831. }
  832. }
  833. rl.activeRes[cs.ID] = cs
  834. cs.resc <- resAndError{res: res}
  835. rl.nextRes = nil // unused now; will be reset next HEADERS frame
  836. return nil
  837. }
  838. // transportResponseBody is the concrete type of Transport.RoundTrip's
  839. // Response.Body. It is an io.ReadCloser. On Read, it reads from cs.body.
  840. // On Close it sends RST_STREAM if EOF wasn't already seen.
  841. type transportResponseBody struct {
  842. cs *clientStream
  843. }
  844. func (b transportResponseBody) Read(p []byte) (n int, err error) {
  845. cs := b.cs
  846. cc := cs.cc
  847. if cs.readErr != nil {
  848. return 0, cs.readErr
  849. }
  850. n, err = b.cs.bufPipe.Read(p)
  851. if cs.bytesRemain != -1 {
  852. if int64(n) > cs.bytesRemain {
  853. n = int(cs.bytesRemain)
  854. if err == nil {
  855. err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
  856. cc.writeStreamReset(cs.ID, ErrCodeProtocol, err)
  857. }
  858. cs.readErr = err
  859. return int(cs.bytesRemain), err
  860. }
  861. cs.bytesRemain -= int64(n)
  862. if err == io.EOF && cs.bytesRemain > 0 {
  863. err = io.ErrUnexpectedEOF
  864. cs.readErr = err
  865. return n, err
  866. }
  867. }
  868. if n == 0 {
  869. // No flow control tokens to send back.
  870. return
  871. }
  872. cc.mu.Lock()
  873. defer cc.mu.Unlock()
  874. var connAdd, streamAdd int32
  875. // Check the conn-level first, before the stream-level.
  876. if v := cc.inflow.available(); v < transportDefaultConnFlow/2 {
  877. connAdd = transportDefaultConnFlow - v
  878. cc.inflow.add(connAdd)
  879. }
  880. if err == nil { // No need to refresh if the stream is over or failed.
  881. if v := cs.inflow.available(); v < transportDefaultStreamFlow-transportDefaultStreamMinRefresh {
  882. streamAdd = transportDefaultStreamFlow - v
  883. cs.inflow.add(streamAdd)
  884. }
  885. }
  886. if connAdd != 0 || streamAdd != 0 {
  887. cc.wmu.Lock()
  888. defer cc.wmu.Unlock()
  889. if connAdd != 0 {
  890. cc.fr.WriteWindowUpdate(0, mustUint31(connAdd))
  891. }
  892. if streamAdd != 0 {
  893. cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd))
  894. }
  895. cc.bw.Flush()
  896. }
  897. return
  898. }
  899. func (b transportResponseBody) Close() error {
  900. if b.cs.bufPipe.Err() != io.EOF {
  901. // TODO: write test for this
  902. b.cs.cc.writeStreamReset(b.cs.ID, ErrCodeCancel, nil)
  903. }
  904. return nil
  905. }
  906. func (rl *clientConnReadLoop) processData(f *DataFrame) error {
  907. cc := rl.cc
  908. cs := cc.streamByID(f.StreamID, f.StreamEnded())
  909. if cs == nil {
  910. return nil
  911. }
  912. data := f.Data()
  913. if VerboseLogs {
  914. rl.cc.logf("DATA: %q", data)
  915. }
  916. // Check connection-level flow control.
  917. cc.mu.Lock()
  918. if cs.inflow.available() >= int32(len(data)) {
  919. cs.inflow.take(int32(len(data)))
  920. } else {
  921. cc.mu.Unlock()
  922. return ConnectionError(ErrCodeFlowControl)
  923. }
  924. cc.mu.Unlock()
  925. if _, err := cs.bufPipe.Write(data); err != nil {
  926. return err
  927. }
  928. if f.StreamEnded() {
  929. cs.bufPipe.CloseWithError(io.EOF)
  930. delete(rl.activeRes, cs.ID)
  931. }
  932. return nil
  933. }
  934. func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error {
  935. cc := rl.cc
  936. cc.t.connPool().MarkDead(cc)
  937. if f.ErrCode != 0 {
  938. // TODO: deal with GOAWAY more. particularly the error code
  939. cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
  940. }
  941. cc.setGoAway(f)
  942. return nil
  943. }
  944. func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error {
  945. cc := rl.cc
  946. cc.mu.Lock()
  947. defer cc.mu.Unlock()
  948. return f.ForeachSetting(func(s Setting) error {
  949. switch s.ID {
  950. case SettingMaxFrameSize:
  951. cc.maxFrameSize = s.Val
  952. case SettingMaxConcurrentStreams:
  953. cc.maxConcurrentStreams = s.Val
  954. case SettingInitialWindowSize:
  955. // TODO: error if this is too large.
  956. // TODO: adjust flow control of still-open
  957. // frames by the difference of the old initial
  958. // window size and this one.
  959. cc.initialWindowSize = s.Val
  960. default:
  961. // TODO(bradfitz): handle more settings?
  962. cc.vlogf("Unhandled Setting: %v", s)
  963. }
  964. return nil
  965. })
  966. }
  967. func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error {
  968. cc := rl.cc
  969. cs := cc.streamByID(f.StreamID, false)
  970. if f.StreamID != 0 && cs == nil {
  971. return nil
  972. }
  973. cc.mu.Lock()
  974. defer cc.mu.Unlock()
  975. fl := &cc.flow
  976. if cs != nil {
  977. fl = &cs.flow
  978. }
  979. if !fl.add(int32(f.Increment)) {
  980. return ConnectionError(ErrCodeFlowControl)
  981. }
  982. cc.cond.Broadcast()
  983. return nil
  984. }
  985. func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error {
  986. cs := rl.cc.streamByID(f.StreamID, true)
  987. if cs == nil {
  988. // TODO: return error if server tries to RST_STEAM an idle stream
  989. return nil
  990. }
  991. select {
  992. case <-cs.peerReset:
  993. // Already reset.
  994. // This is the only goroutine
  995. // which closes this, so there
  996. // isn't a race.
  997. default:
  998. err := StreamError{cs.ID, f.ErrCode}
  999. cs.resetErr = err
  1000. close(cs.peerReset)
  1001. cs.bufPipe.CloseWithError(err)
  1002. cs.cc.cond.Broadcast() // wake up checkReset via clientStream.awaitFlowControl
  1003. }
  1004. delete(rl.activeRes, cs.ID)
  1005. return nil
  1006. }
  1007. func (rl *clientConnReadLoop) processPing(f *PingFrame) error {
  1008. if f.IsAck() {
  1009. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  1010. // containing this flag."
  1011. return nil
  1012. }
  1013. cc := rl.cc
  1014. cc.wmu.Lock()
  1015. defer cc.wmu.Unlock()
  1016. if err := cc.fr.WritePing(true, f.Data); err != nil {
  1017. return err
  1018. }
  1019. return cc.bw.Flush()
  1020. }
  1021. func (rl *clientConnReadLoop) processPushPromise(f *PushPromiseFrame) error {
  1022. // We told the peer we don't want them.
  1023. // Spec says:
  1024. // "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH
  1025. // setting of the peer endpoint is set to 0. An endpoint that
  1026. // has set this setting and has received acknowledgement MUST
  1027. // treat the receipt of a PUSH_PROMISE frame as a connection
  1028. // error (Section 5.4.1) of type PROTOCOL_ERROR."
  1029. return ConnectionError(ErrCodeProtocol)
  1030. }
  1031. func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) {
  1032. // TODO: do something with err? send it as a debug frame to the peer?
  1033. // But that's only in GOAWAY. Invent a new frame type? Is there one already?
  1034. cc.wmu.Lock()
  1035. cc.fr.WriteRSTStream(streamID, code)
  1036. cc.wmu.Unlock()
  1037. }
  1038. // onNewHeaderField runs on the readLoop goroutine whenever a new
  1039. // hpack header field is decoded.
  1040. func (rl *clientConnReadLoop) onNewHeaderField(f hpack.HeaderField) {
  1041. cc := rl.cc
  1042. if VerboseLogs {
  1043. cc.logf("Header field: %+v", f)
  1044. }
  1045. isPseudo := strings.HasPrefix(f.Name, ":")
  1046. if isPseudo {
  1047. if rl.sawRegHeader {
  1048. rl.reqMalformed = errors.New("http2: invalid pseudo header after regular header")
  1049. return
  1050. }
  1051. switch f.Name {
  1052. case ":status":
  1053. code, err := strconv.Atoi(f.Value)
  1054. if err != nil {
  1055. rl.reqMalformed = errors.New("http2: invalid :status")
  1056. return
  1057. }
  1058. rl.nextRes.Status = f.Value + " " + http.StatusText(code)
  1059. rl.nextRes.StatusCode = code
  1060. default:
  1061. // "Endpoints MUST NOT generate pseudo-header
  1062. // fields other than those defined in this
  1063. // document."
  1064. rl.reqMalformed = fmt.Errorf("http2: unknown response pseudo header %q", f.Name)
  1065. }
  1066. } else {
  1067. rl.sawRegHeader = true
  1068. rl.nextRes.Header.Add(http.CanonicalHeaderKey(f.Name), f.Value)
  1069. }
  1070. }
  1071. func (cc *ClientConn) logf(format string, args ...interface{}) {
  1072. cc.t.logf(format, args...)
  1073. }
  1074. func (cc *ClientConn) vlogf(format string, args ...interface{}) {
  1075. cc.t.vlogf(format, args...)
  1076. }
  1077. func (t *Transport) vlogf(format string, args ...interface{}) {
  1078. if VerboseLogs {
  1079. t.logf(format, args...)
  1080. }
  1081. }
  1082. func (t *Transport) logf(format string, args ...interface{}) {
  1083. log.Printf(format, args...)
  1084. }
  1085. var noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
  1086. func strSliceContains(ss []string, s string) bool {
  1087. for _, v := range ss {
  1088. if v == s {
  1089. return true
  1090. }
  1091. }
  1092. return false
  1093. }
  1094. type erringRoundTripper struct{ err error }
  1095. func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err }
  1096. // gzipReader wraps a response body so it can lazily
  1097. // call gzip.NewReader on the first call to Read
  1098. type gzipReader struct {
  1099. body io.ReadCloser // underlying Response.Body
  1100. zr io.Reader // lazily-initialized gzip reader
  1101. }
  1102. func (gz *gzipReader) Read(p []byte) (n int, err error) {
  1103. if gz.zr == nil {
  1104. gz.zr, err = gzip.NewReader(gz.body)
  1105. if err != nil {
  1106. return 0, err
  1107. }
  1108. }
  1109. return gz.zr.Read(p)
  1110. }
  1111. func (gz *gzipReader) Close() error {
  1112. return gz.body.Close()
  1113. }