transport.go 34 KB

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