transport.go 56 KB

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