transport.go 50 KB

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