transport.go 46 KB

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