transport.go 74 KB

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