transport.go 36 KB

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