transport.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  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 err := <-bodyCopyErrc:
  520. if err != nil {
  521. return nil, err
  522. }
  523. }
  524. }
  525. }
  526. // errAbortReqBodyWrite is an internal error value.
  527. // It doesn't escape to callers.
  528. var errAbortReqBodyWrite = errors.New("http2: aborting request body write")
  529. func (cs *clientStream) writeRequestBody(body io.ReadCloser) (err error) {
  530. cc := cs.cc
  531. sentEnd := false // whether we sent the final DATA frame w/ END_STREAM
  532. buf := cc.frameScratchBuffer()
  533. defer cc.putFrameScratchBuffer(buf)
  534. defer func() {
  535. // TODO: write h12Compare test showing whether
  536. // Request.Body is closed by the Transport,
  537. // and in multiple cases: server replies <=299 and >299
  538. // while still writing request body
  539. cerr := body.Close()
  540. if err == nil {
  541. err = cerr
  542. }
  543. }()
  544. var sawEOF bool
  545. for !sawEOF {
  546. n, err := body.Read(buf)
  547. if err == io.EOF {
  548. sawEOF = true
  549. err = nil
  550. } else if err != nil {
  551. return err
  552. }
  553. remain := buf[:n]
  554. for len(remain) > 0 && err == nil {
  555. var allowed int32
  556. allowed, err = cs.awaitFlowControl(len(remain))
  557. if err != nil {
  558. return err
  559. }
  560. cc.wmu.Lock()
  561. data := remain[:allowed]
  562. remain = remain[allowed:]
  563. sentEnd = sawEOF && len(remain) == 0
  564. err = cc.fr.WriteData(cs.ID, sentEnd, data)
  565. if err == nil {
  566. // TODO(bradfitz): this flush is for latency, not bandwidth.
  567. // Most requests won't need this. Make this opt-in or opt-out?
  568. // Use some heuristic on the body type? Nagel-like timers?
  569. // Based on 'n'? Only last chunk of this for loop, unless flow control
  570. // tokens are low? For now, always:
  571. err = cc.bw.Flush()
  572. }
  573. cc.wmu.Unlock()
  574. }
  575. if err != nil {
  576. return err
  577. }
  578. }
  579. cc.wmu.Lock()
  580. if !sentEnd {
  581. err = cc.fr.WriteData(cs.ID, true, nil)
  582. }
  583. if ferr := cc.bw.Flush(); ferr != nil && err == nil {
  584. err = ferr
  585. }
  586. cc.wmu.Unlock()
  587. return err
  588. }
  589. // awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
  590. // control tokens from the server.
  591. // It returns either the non-zero number of tokens taken or an error
  592. // if the stream is dead.
  593. func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
  594. cc := cs.cc
  595. cc.mu.Lock()
  596. defer cc.mu.Unlock()
  597. for {
  598. if cc.closed {
  599. return 0, errClientConnClosed
  600. }
  601. if cs.stopReqBody {
  602. return 0, errAbortReqBodyWrite
  603. }
  604. if err := cs.checkReset(); err != nil {
  605. return 0, err
  606. }
  607. if a := cs.flow.available(); a > 0 {
  608. take := a
  609. if int(take) > maxBytes {
  610. take = int32(maxBytes) // can't truncate int; take is int32
  611. }
  612. if take > int32(cc.maxFrameSize) {
  613. take = int32(cc.maxFrameSize)
  614. }
  615. cs.flow.take(take)
  616. return take, nil
  617. }
  618. cc.cond.Wait()
  619. }
  620. }
  621. // requires cc.mu be held.
  622. func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool) []byte {
  623. cc.hbuf.Reset()
  624. // TODO(bradfitz): figure out :authority-vs-Host stuff between http2 and Go
  625. host := req.Host
  626. if host == "" {
  627. host = req.URL.Host
  628. }
  629. // 8.1.2.3 Request Pseudo-Header Fields
  630. // The :path pseudo-header field includes the path and query parts of the
  631. // target URI (the path-absolute production and optionally a '?' character
  632. // followed by the query production (see Sections 3.3 and 3.4 of
  633. // [RFC3986]).
  634. cc.writeHeader(":authority", host) // probably not right for all sites
  635. cc.writeHeader(":method", req.Method)
  636. cc.writeHeader(":path", req.URL.RequestURI())
  637. cc.writeHeader(":scheme", "https")
  638. for k, vv := range req.Header {
  639. lowKey := strings.ToLower(k)
  640. if lowKey == "host" {
  641. continue
  642. }
  643. for _, v := range vv {
  644. cc.writeHeader(lowKey, v)
  645. }
  646. }
  647. if addGzipHeader {
  648. cc.writeHeader("accept-encoding", "gzip")
  649. }
  650. return cc.hbuf.Bytes()
  651. }
  652. func (cc *ClientConn) writeHeader(name, value string) {
  653. cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
  654. }
  655. type resAndError struct {
  656. res *http.Response
  657. err error
  658. }
  659. // requires cc.mu be held.
  660. func (cc *ClientConn) newStream() *clientStream {
  661. cs := &clientStream{
  662. cc: cc,
  663. ID: cc.nextStreamID,
  664. resc: make(chan resAndError, 1),
  665. peerReset: make(chan struct{}),
  666. }
  667. cs.flow.add(int32(cc.initialWindowSize))
  668. cs.flow.setConnFlow(&cc.flow)
  669. cs.inflow.add(transportDefaultStreamFlow)
  670. cs.inflow.setConnFlow(&cc.inflow)
  671. cc.nextStreamID += 2
  672. cc.streams[cs.ID] = cs
  673. return cs
  674. }
  675. func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream {
  676. cc.mu.Lock()
  677. defer cc.mu.Unlock()
  678. cs := cc.streams[id]
  679. if andRemove {
  680. delete(cc.streams, id)
  681. }
  682. return cs
  683. }
  684. // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.
  685. type clientConnReadLoop struct {
  686. cc *ClientConn
  687. activeRes map[uint32]*clientStream // keyed by streamID
  688. // continueStreamID is the stream ID we're waiting for
  689. // continuation frames for.
  690. continueStreamID uint32
  691. hdec *hpack.Decoder
  692. // Fields reset on each HEADERS:
  693. nextRes *http.Response
  694. sawRegHeader bool // saw non-pseudo header
  695. reqMalformed error // non-nil once known to be malformed
  696. }
  697. // readLoop runs in its own goroutine and reads and dispatches frames.
  698. func (cc *ClientConn) readLoop() {
  699. rl := &clientConnReadLoop{
  700. cc: cc,
  701. activeRes: make(map[uint32]*clientStream),
  702. }
  703. // TODO: figure out henc size
  704. rl.hdec = hpack.NewDecoder(initialHeaderTableSize, rl.onNewHeaderField)
  705. defer rl.cleanup()
  706. cc.readerErr = rl.run()
  707. if ce, ok := cc.readerErr.(ConnectionError); ok {
  708. cc.wmu.Lock()
  709. cc.fr.WriteGoAway(0, ErrCode(ce), nil)
  710. cc.wmu.Unlock()
  711. }
  712. }
  713. func (rl *clientConnReadLoop) cleanup() {
  714. cc := rl.cc
  715. defer cc.tconn.Close()
  716. defer cc.t.connPool().MarkDead(cc)
  717. defer close(cc.readerDone)
  718. // Close any response bodies if the server closes prematurely.
  719. // TODO: also do this if we've written the headers but not
  720. // gotten a response yet.
  721. err := cc.readerErr
  722. if err == io.EOF {
  723. err = io.ErrUnexpectedEOF
  724. }
  725. cc.mu.Lock()
  726. for _, cs := range rl.activeRes {
  727. cs.bufPipe.CloseWithError(err)
  728. }
  729. for _, cs := range cc.streams {
  730. select {
  731. case cs.resc <- resAndError{err: err}:
  732. default:
  733. }
  734. }
  735. cc.closed = true
  736. cc.cond.Broadcast()
  737. cc.mu.Unlock()
  738. }
  739. func (rl *clientConnReadLoop) run() error {
  740. cc := rl.cc
  741. for {
  742. f, err := cc.fr.ReadFrame()
  743. if err != nil {
  744. cc.vlogf("Transport readFrame error: (%T) %v", err, err)
  745. }
  746. if se, ok := err.(StreamError); ok {
  747. // TODO: deal with stream errors from the framer.
  748. return se
  749. } else if err != nil {
  750. return err
  751. }
  752. cc.vlogf("Transport received %v: %#v", f.Header(), f)
  753. streamID := f.Header().StreamID
  754. _, isContinue := f.(*ContinuationFrame)
  755. if isContinue {
  756. if streamID != rl.continueStreamID {
  757. cc.logf("Protocol violation: got CONTINUATION with id %d; want %d", streamID, rl.continueStreamID)
  758. return ConnectionError(ErrCodeProtocol)
  759. }
  760. } else if rl.continueStreamID != 0 {
  761. // Continue frames need to be adjacent in the stream
  762. // and we were in the middle of headers.
  763. cc.logf("Protocol violation: got %T for stream %d, want CONTINUATION for %d", f, streamID, rl.continueStreamID)
  764. return ConnectionError(ErrCodeProtocol)
  765. }
  766. switch f := f.(type) {
  767. case *HeadersFrame:
  768. err = rl.processHeaders(f)
  769. case *ContinuationFrame:
  770. err = rl.processContinuation(f)
  771. case *DataFrame:
  772. err = rl.processData(f)
  773. case *GoAwayFrame:
  774. err = rl.processGoAway(f)
  775. case *RSTStreamFrame:
  776. err = rl.processResetStream(f)
  777. case *SettingsFrame:
  778. err = rl.processSettings(f)
  779. case *PushPromiseFrame:
  780. err = rl.processPushPromise(f)
  781. case *WindowUpdateFrame:
  782. err = rl.processWindowUpdate(f)
  783. case *PingFrame:
  784. err = rl.processPing(f)
  785. default:
  786. cc.logf("Transport: unhandled response frame type %T", f)
  787. }
  788. if err != nil {
  789. return err
  790. }
  791. }
  792. }
  793. func (rl *clientConnReadLoop) processHeaders(f *HeadersFrame) error {
  794. rl.sawRegHeader = false
  795. rl.reqMalformed = nil
  796. rl.nextRes = &http.Response{
  797. Proto: "HTTP/2.0",
  798. ProtoMajor: 2,
  799. Header: make(http.Header),
  800. }
  801. return rl.processHeaderBlockFragment(f.HeaderBlockFragment(), f.StreamID, f.HeadersEnded(), f.StreamEnded())
  802. }
  803. func (rl *clientConnReadLoop) processContinuation(f *ContinuationFrame) error {
  804. return rl.processHeaderBlockFragment(f.HeaderBlockFragment(), f.StreamID, f.HeadersEnded(), f.StreamEnded())
  805. }
  806. func (rl *clientConnReadLoop) processHeaderBlockFragment(frag []byte, streamID uint32, headersEnded, streamEnded bool) error {
  807. cc := rl.cc
  808. cs := cc.streamByID(streamID, streamEnded)
  809. if cs == nil {
  810. // We could return a ConnectionError(ErrCodeProtocol)
  811. // here, except that in the case of us canceling
  812. // client requests, we may also delete from the
  813. // streams map, in which case we forgot that we sent
  814. // this request. So, just ignore any responses for
  815. // now. They might've been in-flight before the
  816. // server got our RST_STREAM.
  817. return nil
  818. }
  819. _, err := rl.hdec.Write(frag)
  820. if err != nil {
  821. return err
  822. }
  823. if !headersEnded {
  824. rl.continueStreamID = cs.ID
  825. return nil
  826. }
  827. // HEADERS (or CONTINUATION) are now over.
  828. rl.continueStreamID = 0
  829. if rl.reqMalformed != nil {
  830. cs.resc <- resAndError{err: rl.reqMalformed}
  831. rl.cc.writeStreamReset(cs.ID, ErrCodeProtocol, rl.reqMalformed)
  832. return nil
  833. }
  834. res := rl.nextRes
  835. if !streamEnded || cs.req.Method == "HEAD" {
  836. res.ContentLength = -1
  837. if clens := res.Header["Content-Length"]; len(clens) == 1 {
  838. if clen64, err := strconv.ParseInt(clens[0], 10, 64); err == nil {
  839. res.ContentLength = clen64
  840. } else {
  841. // TODO: care? unlike http/1, it won't mess up our framing, so it's
  842. // more safe smuggling-wise to ignore.
  843. }
  844. } else if len(clens) > 1 {
  845. // TODO: care? unlike http/1, it won't mess up our framing, so it's
  846. // more safe smuggling-wise to ignore.
  847. }
  848. }
  849. if streamEnded {
  850. res.Body = noBody
  851. } else {
  852. buf := new(bytes.Buffer) // TODO(bradfitz): recycle this garbage
  853. cs.bufPipe = pipe{b: buf}
  854. cs.bytesRemain = res.ContentLength
  855. res.Body = transportResponseBody{cs}
  856. go cs.awaitRequestCancel(requestCancel(cs.req))
  857. if cs.requestedGzip && res.Header.Get("Content-Encoding") == "gzip" {
  858. res.Header.Del("Content-Encoding")
  859. res.Header.Del("Content-Length")
  860. res.ContentLength = -1
  861. res.Body = &gzipReader{body: res.Body}
  862. }
  863. }
  864. rl.activeRes[cs.ID] = cs
  865. cs.resc <- resAndError{res: res}
  866. rl.nextRes = nil // unused now; will be reset next HEADERS frame
  867. return nil
  868. }
  869. // transportResponseBody is the concrete type of Transport.RoundTrip's
  870. // Response.Body. It is an io.ReadCloser. On Read, it reads from cs.body.
  871. // On Close it sends RST_STREAM if EOF wasn't already seen.
  872. type transportResponseBody struct {
  873. cs *clientStream
  874. }
  875. func (b transportResponseBody) Read(p []byte) (n int, err error) {
  876. cs := b.cs
  877. cc := cs.cc
  878. if cs.readErr != nil {
  879. return 0, cs.readErr
  880. }
  881. n, err = b.cs.bufPipe.Read(p)
  882. if cs.bytesRemain != -1 {
  883. if int64(n) > cs.bytesRemain {
  884. n = int(cs.bytesRemain)
  885. if err == nil {
  886. err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
  887. cc.writeStreamReset(cs.ID, ErrCodeProtocol, err)
  888. }
  889. cs.readErr = err
  890. return int(cs.bytesRemain), err
  891. }
  892. cs.bytesRemain -= int64(n)
  893. if err == io.EOF && cs.bytesRemain > 0 {
  894. err = io.ErrUnexpectedEOF
  895. cs.readErr = err
  896. return n, err
  897. }
  898. }
  899. if n == 0 {
  900. // No flow control tokens to send back.
  901. return
  902. }
  903. cc.mu.Lock()
  904. defer cc.mu.Unlock()
  905. var connAdd, streamAdd int32
  906. // Check the conn-level first, before the stream-level.
  907. if v := cc.inflow.available(); v < transportDefaultConnFlow/2 {
  908. connAdd = transportDefaultConnFlow - v
  909. cc.inflow.add(connAdd)
  910. }
  911. if err == nil { // No need to refresh if the stream is over or failed.
  912. if v := cs.inflow.available(); v < transportDefaultStreamFlow-transportDefaultStreamMinRefresh {
  913. streamAdd = transportDefaultStreamFlow - v
  914. cs.inflow.add(streamAdd)
  915. }
  916. }
  917. if connAdd != 0 || streamAdd != 0 {
  918. cc.wmu.Lock()
  919. defer cc.wmu.Unlock()
  920. if connAdd != 0 {
  921. cc.fr.WriteWindowUpdate(0, mustUint31(connAdd))
  922. }
  923. if streamAdd != 0 {
  924. cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd))
  925. }
  926. cc.bw.Flush()
  927. }
  928. return
  929. }
  930. func (b transportResponseBody) Close() error {
  931. if b.cs.bufPipe.Err() != io.EOF {
  932. // TODO: write test for this
  933. b.cs.cc.writeStreamReset(b.cs.ID, ErrCodeCancel, nil)
  934. }
  935. return nil
  936. }
  937. func (rl *clientConnReadLoop) processData(f *DataFrame) error {
  938. cc := rl.cc
  939. cs := cc.streamByID(f.StreamID, f.StreamEnded())
  940. if cs == nil {
  941. return nil
  942. }
  943. data := f.Data()
  944. if VerboseLogs {
  945. rl.cc.logf("DATA: %q", data)
  946. }
  947. // Check connection-level flow control.
  948. cc.mu.Lock()
  949. if cs.inflow.available() >= int32(len(data)) {
  950. cs.inflow.take(int32(len(data)))
  951. } else {
  952. cc.mu.Unlock()
  953. return ConnectionError(ErrCodeFlowControl)
  954. }
  955. cc.mu.Unlock()
  956. if _, err := cs.bufPipe.Write(data); err != nil {
  957. return err
  958. }
  959. if f.StreamEnded() {
  960. cs.bufPipe.CloseWithError(io.EOF)
  961. delete(rl.activeRes, cs.ID)
  962. }
  963. return nil
  964. }
  965. func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error {
  966. cc := rl.cc
  967. cc.t.connPool().MarkDead(cc)
  968. if f.ErrCode != 0 {
  969. // TODO: deal with GOAWAY more. particularly the error code
  970. cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
  971. }
  972. cc.setGoAway(f)
  973. return nil
  974. }
  975. func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error {
  976. cc := rl.cc
  977. cc.mu.Lock()
  978. defer cc.mu.Unlock()
  979. return f.ForeachSetting(func(s Setting) error {
  980. switch s.ID {
  981. case SettingMaxFrameSize:
  982. cc.maxFrameSize = s.Val
  983. case SettingMaxConcurrentStreams:
  984. cc.maxConcurrentStreams = s.Val
  985. case SettingInitialWindowSize:
  986. // TODO: error if this is too large.
  987. // TODO: adjust flow control of still-open
  988. // frames by the difference of the old initial
  989. // window size and this one.
  990. cc.initialWindowSize = s.Val
  991. default:
  992. // TODO(bradfitz): handle more settings?
  993. cc.vlogf("Unhandled Setting: %v", s)
  994. }
  995. return nil
  996. })
  997. }
  998. func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error {
  999. cc := rl.cc
  1000. cs := cc.streamByID(f.StreamID, false)
  1001. if f.StreamID != 0 && cs == nil {
  1002. return nil
  1003. }
  1004. cc.mu.Lock()
  1005. defer cc.mu.Unlock()
  1006. fl := &cc.flow
  1007. if cs != nil {
  1008. fl = &cs.flow
  1009. }
  1010. if !fl.add(int32(f.Increment)) {
  1011. return ConnectionError(ErrCodeFlowControl)
  1012. }
  1013. cc.cond.Broadcast()
  1014. return nil
  1015. }
  1016. func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error {
  1017. cs := rl.cc.streamByID(f.StreamID, true)
  1018. if cs == nil {
  1019. // TODO: return error if server tries to RST_STEAM an idle stream
  1020. return nil
  1021. }
  1022. select {
  1023. case <-cs.peerReset:
  1024. // Already reset.
  1025. // This is the only goroutine
  1026. // which closes this, so there
  1027. // isn't a race.
  1028. default:
  1029. err := StreamError{cs.ID, f.ErrCode}
  1030. cs.resetErr = err
  1031. close(cs.peerReset)
  1032. cs.bufPipe.CloseWithError(err)
  1033. cs.cc.cond.Broadcast() // wake up checkReset via clientStream.awaitFlowControl
  1034. }
  1035. delete(rl.activeRes, cs.ID)
  1036. return nil
  1037. }
  1038. func (rl *clientConnReadLoop) processPing(f *PingFrame) error {
  1039. if f.IsAck() {
  1040. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  1041. // containing this flag."
  1042. return nil
  1043. }
  1044. cc := rl.cc
  1045. cc.wmu.Lock()
  1046. defer cc.wmu.Unlock()
  1047. if err := cc.fr.WritePing(true, f.Data); err != nil {
  1048. return err
  1049. }
  1050. return cc.bw.Flush()
  1051. }
  1052. func (rl *clientConnReadLoop) processPushPromise(f *PushPromiseFrame) error {
  1053. // We told the peer we don't want them.
  1054. // Spec says:
  1055. // "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH
  1056. // setting of the peer endpoint is set to 0. An endpoint that
  1057. // has set this setting and has received acknowledgement MUST
  1058. // treat the receipt of a PUSH_PROMISE frame as a connection
  1059. // error (Section 5.4.1) of type PROTOCOL_ERROR."
  1060. return ConnectionError(ErrCodeProtocol)
  1061. }
  1062. func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) {
  1063. // TODO: do something with err? send it as a debug frame to the peer?
  1064. // But that's only in GOAWAY. Invent a new frame type? Is there one already?
  1065. cc.wmu.Lock()
  1066. cc.fr.WriteRSTStream(streamID, code)
  1067. cc.wmu.Unlock()
  1068. }
  1069. // onNewHeaderField runs on the readLoop goroutine whenever a new
  1070. // hpack header field is decoded.
  1071. func (rl *clientConnReadLoop) onNewHeaderField(f hpack.HeaderField) {
  1072. cc := rl.cc
  1073. if VerboseLogs {
  1074. cc.logf("Header field: %+v", f)
  1075. }
  1076. isPseudo := strings.HasPrefix(f.Name, ":")
  1077. if isPseudo {
  1078. if rl.sawRegHeader {
  1079. rl.reqMalformed = errors.New("http2: invalid pseudo header after regular header")
  1080. return
  1081. }
  1082. switch f.Name {
  1083. case ":status":
  1084. code, err := strconv.Atoi(f.Value)
  1085. if err != nil {
  1086. rl.reqMalformed = errors.New("http2: invalid :status")
  1087. return
  1088. }
  1089. rl.nextRes.Status = f.Value + " " + http.StatusText(code)
  1090. rl.nextRes.StatusCode = code
  1091. default:
  1092. // "Endpoints MUST NOT generate pseudo-header
  1093. // fields other than those defined in this
  1094. // document."
  1095. rl.reqMalformed = fmt.Errorf("http2: unknown response pseudo header %q", f.Name)
  1096. }
  1097. } else {
  1098. rl.sawRegHeader = true
  1099. rl.nextRes.Header.Add(http.CanonicalHeaderKey(f.Name), f.Value)
  1100. }
  1101. }
  1102. func (cc *ClientConn) logf(format string, args ...interface{}) {
  1103. cc.t.logf(format, args...)
  1104. }
  1105. func (cc *ClientConn) vlogf(format string, args ...interface{}) {
  1106. cc.t.vlogf(format, args...)
  1107. }
  1108. func (t *Transport) vlogf(format string, args ...interface{}) {
  1109. if VerboseLogs {
  1110. t.logf(format, args...)
  1111. }
  1112. }
  1113. func (t *Transport) logf(format string, args ...interface{}) {
  1114. log.Printf(format, args...)
  1115. }
  1116. var noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
  1117. func strSliceContains(ss []string, s string) bool {
  1118. for _, v := range ss {
  1119. if v == s {
  1120. return true
  1121. }
  1122. }
  1123. return false
  1124. }
  1125. type erringRoundTripper struct{ err error }
  1126. func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err }
  1127. // gzipReader wraps a response body so it can lazily
  1128. // call gzip.NewReader on the first call to Read
  1129. type gzipReader struct {
  1130. body io.ReadCloser // underlying Response.Body
  1131. zr io.Reader // lazily-initialized gzip reader
  1132. }
  1133. func (gz *gzipReader) Read(p []byte) (n int, err error) {
  1134. if gz.zr == nil {
  1135. gz.zr, err = gzip.NewReader(gz.body)
  1136. if err != nil {
  1137. return 0, err
  1138. }
  1139. }
  1140. return gz.zr.Read(p)
  1141. }
  1142. func (gz *gzipReader) Close() error {
  1143. return gz.body.Close()
  1144. }