transport.go 64 KB

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