transport.go 56 KB

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