transport.go 38 KB

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