transport.go 76 KB

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