transport.go 46 KB

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