transport.go 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243
  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/fs"
  17. "log"
  18. "math"
  19. "math/bits"
  20. mathrand "math/rand"
  21. "net"
  22. "net/http"
  23. "net/http/httptrace"
  24. "net/textproto"
  25. "os"
  26. "sort"
  27. "strconv"
  28. "strings"
  29. "sync"
  30. "sync/atomic"
  31. "time"
  32. "golang.org/x/net/http/httpguts"
  33. "golang.org/x/net/http2/hpack"
  34. "golang.org/x/net/idna"
  35. )
  36. const (
  37. // transportDefaultConnFlow is how many connection-level flow control
  38. // tokens we give the server at start-up, past the default 64k.
  39. transportDefaultConnFlow = 1 << 30
  40. // transportDefaultStreamFlow is how many stream-level flow
  41. // control tokens we announce to the peer, and how many bytes
  42. // we buffer per stream.
  43. transportDefaultStreamFlow = 4 << 20
  44. defaultUserAgent = "Go-http-client/2.0"
  45. // initialMaxConcurrentStreams is a connections maxConcurrentStreams until
  46. // it's received servers initial SETTINGS frame, which corresponds with the
  47. // spec's minimum recommended value.
  48. initialMaxConcurrentStreams = 100
  49. // defaultMaxConcurrentStreams is a connections default maxConcurrentStreams
  50. // if the server doesn't include one in its initial SETTINGS frame.
  51. defaultMaxConcurrentStreams = 1000
  52. )
  53. // Transport is an HTTP/2 Transport.
  54. //
  55. // A Transport internally caches connections to servers. It is safe
  56. // for concurrent use by multiple goroutines.
  57. type Transport struct {
  58. // DialTLSContext specifies an optional dial function with context for
  59. // creating TLS connections for requests.
  60. //
  61. // If DialTLSContext and DialTLS is nil, tls.Dial is used.
  62. //
  63. // If the returned net.Conn has a ConnectionState method like tls.Conn,
  64. // it will be used to set http.Response.TLS.
  65. DialTLSContext func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error)
  66. // DialTLS specifies an optional dial function for creating
  67. // TLS connections for requests.
  68. //
  69. // If DialTLSContext and DialTLS is nil, tls.Dial is used.
  70. //
  71. // Deprecated: Use DialTLSContext instead, which allows the transport
  72. // to cancel dials as soon as they are no longer needed.
  73. // If both are set, DialTLSContext takes priority.
  74. DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error)
  75. // TLSClientConfig specifies the TLS configuration to use with
  76. // tls.Client. If nil, the default configuration is used.
  77. TLSClientConfig *tls.Config
  78. // ConnPool optionally specifies an alternate connection pool to use.
  79. // If nil, the default is used.
  80. ConnPool ClientConnPool
  81. // DisableCompression, if true, prevents the Transport from
  82. // requesting compression with an "Accept-Encoding: gzip"
  83. // request header when the Request contains no existing
  84. // Accept-Encoding value. If the Transport requests gzip on
  85. // its own and gets a gzipped response, it's transparently
  86. // decoded in the Response.Body. However, if the user
  87. // explicitly requested gzip it is not automatically
  88. // uncompressed.
  89. DisableCompression bool
  90. // AllowHTTP, if true, permits HTTP/2 requests using the insecure,
  91. // plain-text "http" scheme. Note that this does not enable h2c support.
  92. AllowHTTP bool
  93. // MaxHeaderListSize is the http2 SETTINGS_MAX_HEADER_LIST_SIZE to
  94. // send in the initial settings frame. It is how many bytes
  95. // of response headers are allowed. Unlike the http2 spec, zero here
  96. // means to use a default limit (currently 10MB). If you actually
  97. // want to advertise an unlimited value to the peer, Transport
  98. // interprets the highest possible value here (0xffffffff or 1<<32-1)
  99. // to mean no limit.
  100. MaxHeaderListSize uint32
  101. // MaxReadFrameSize is the http2 SETTINGS_MAX_FRAME_SIZE to send in the
  102. // initial settings frame. It is the size in bytes of the largest frame
  103. // payload that the sender is willing to receive. If 0, no setting is
  104. // sent, and the value is provided by the peer, which should be 16384
  105. // according to the spec:
  106. // https://datatracker.ietf.org/doc/html/rfc7540#section-6.5.2.
  107. // Values are bounded in the range 16k to 16M.
  108. MaxReadFrameSize uint32
  109. // MaxDecoderHeaderTableSize optionally specifies the http2
  110. // SETTINGS_HEADER_TABLE_SIZE to send in the initial settings frame. It
  111. // informs the remote endpoint of the maximum size of the header compression
  112. // table used to decode header blocks, in octets. If zero, the default value
  113. // of 4096 is used.
  114. MaxDecoderHeaderTableSize uint32
  115. // MaxEncoderHeaderTableSize optionally specifies an upper limit for the
  116. // header compression table used for encoding request headers. Received
  117. // SETTINGS_HEADER_TABLE_SIZE settings are capped at this limit. If zero,
  118. // the default value of 4096 is used.
  119. MaxEncoderHeaderTableSize uint32
  120. // StrictMaxConcurrentStreams controls whether the server's
  121. // SETTINGS_MAX_CONCURRENT_STREAMS should be respected
  122. // globally. If false, new TCP connections are created to the
  123. // server as needed to keep each under the per-connection
  124. // SETTINGS_MAX_CONCURRENT_STREAMS limit. If true, the
  125. // server's SETTINGS_MAX_CONCURRENT_STREAMS is interpreted as
  126. // a global limit and callers of RoundTrip block when needed,
  127. // waiting for their turn.
  128. StrictMaxConcurrentStreams bool
  129. // ReadIdleTimeout is the timeout after which a health check using ping
  130. // frame will be carried out if no frame is received on the connection.
  131. // Note that a ping response will is considered a received frame, so if
  132. // there is no other traffic on the connection, the health check will
  133. // be performed every ReadIdleTimeout interval.
  134. // If zero, no health check is performed.
  135. ReadIdleTimeout time.Duration
  136. // PingTimeout is the timeout after which the connection will be closed
  137. // if a response to Ping is not received.
  138. // Defaults to 15s.
  139. PingTimeout time.Duration
  140. // WriteByteTimeout is the timeout after which the connection will be
  141. // closed no data can be written to it. The timeout begins when data is
  142. // available to write, and is extended whenever any bytes are written.
  143. WriteByteTimeout time.Duration
  144. // CountError, if non-nil, is called on HTTP/2 transport errors.
  145. // It's intended to increment a metric for monitoring, such
  146. // as an expvar or Prometheus metric.
  147. // The errType consists of only ASCII word characters.
  148. CountError func(errType string)
  149. // t1, if non-nil, is the standard library Transport using
  150. // this transport. Its settings are used (but not its
  151. // RoundTrip method, etc).
  152. t1 *http.Transport
  153. connPoolOnce sync.Once
  154. connPoolOrDef ClientConnPool // non-nil version of ConnPool
  155. }
  156. func (t *Transport) maxHeaderListSize() uint32 {
  157. if t.MaxHeaderListSize == 0 {
  158. return 10 << 20
  159. }
  160. if t.MaxHeaderListSize == 0xffffffff {
  161. return 0
  162. }
  163. return t.MaxHeaderListSize
  164. }
  165. func (t *Transport) maxFrameReadSize() uint32 {
  166. if t.MaxReadFrameSize == 0 {
  167. return 0 // use the default provided by the peer
  168. }
  169. if t.MaxReadFrameSize < minMaxFrameSize {
  170. return minMaxFrameSize
  171. }
  172. if t.MaxReadFrameSize > maxFrameSize {
  173. return maxFrameSize
  174. }
  175. return t.MaxReadFrameSize
  176. }
  177. func (t *Transport) disableCompression() bool {
  178. return t.DisableCompression || (t.t1 != nil && t.t1.DisableCompression)
  179. }
  180. func (t *Transport) pingTimeout() time.Duration {
  181. if t.PingTimeout == 0 {
  182. return 15 * time.Second
  183. }
  184. return t.PingTimeout
  185. }
  186. // ConfigureTransport configures a net/http HTTP/1 Transport to use HTTP/2.
  187. // It returns an error if t1 has already been HTTP/2-enabled.
  188. //
  189. // Use ConfigureTransports instead to configure the HTTP/2 Transport.
  190. func ConfigureTransport(t1 *http.Transport) error {
  191. _, err := ConfigureTransports(t1)
  192. return err
  193. }
  194. // ConfigureTransports configures a net/http HTTP/1 Transport to use HTTP/2.
  195. // It returns a new HTTP/2 Transport for further configuration.
  196. // It returns an error if t1 has already been HTTP/2-enabled.
  197. func ConfigureTransports(t1 *http.Transport) (*Transport, error) {
  198. return configureTransports(t1)
  199. }
  200. func configureTransports(t1 *http.Transport) (*Transport, error) {
  201. connPool := new(clientConnPool)
  202. t2 := &Transport{
  203. ConnPool: noDialClientConnPool{connPool},
  204. t1: t1,
  205. }
  206. connPool.t = t2
  207. if err := registerHTTPSProtocol(t1, noDialH2RoundTripper{t2}); err != nil {
  208. return nil, err
  209. }
  210. if t1.TLSClientConfig == nil {
  211. t1.TLSClientConfig = new(tls.Config)
  212. }
  213. if !strSliceContains(t1.TLSClientConfig.NextProtos, "h2") {
  214. t1.TLSClientConfig.NextProtos = append([]string{"h2"}, t1.TLSClientConfig.NextProtos...)
  215. }
  216. if !strSliceContains(t1.TLSClientConfig.NextProtos, "http/1.1") {
  217. t1.TLSClientConfig.NextProtos = append(t1.TLSClientConfig.NextProtos, "http/1.1")
  218. }
  219. upgradeFn := func(authority string, c *tls.Conn) http.RoundTripper {
  220. addr := authorityAddr("https", authority)
  221. if used, err := connPool.addConnIfNeeded(addr, t2, c); err != nil {
  222. go c.Close()
  223. return erringRoundTripper{err}
  224. } else if !used {
  225. // Turns out we don't need this c.
  226. // For example, two goroutines made requests to the same host
  227. // at the same time, both kicking off TCP dials. (since protocol
  228. // was unknown)
  229. go c.Close()
  230. }
  231. return t2
  232. }
  233. if m := t1.TLSNextProto; len(m) == 0 {
  234. t1.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{
  235. "h2": upgradeFn,
  236. }
  237. } else {
  238. m["h2"] = upgradeFn
  239. }
  240. return t2, nil
  241. }
  242. func (t *Transport) connPool() ClientConnPool {
  243. t.connPoolOnce.Do(t.initConnPool)
  244. return t.connPoolOrDef
  245. }
  246. func (t *Transport) initConnPool() {
  247. if t.ConnPool != nil {
  248. t.connPoolOrDef = t.ConnPool
  249. } else {
  250. t.connPoolOrDef = &clientConnPool{t: t}
  251. }
  252. }
  253. // ClientConn is the state of a single HTTP/2 client connection to an
  254. // HTTP/2 server.
  255. type ClientConn struct {
  256. t *Transport
  257. tconn net.Conn // usually *tls.Conn, except specialized impls
  258. tlsState *tls.ConnectionState // nil only for specialized impls
  259. reused uint32 // whether conn is being reused; atomic
  260. singleUse bool // whether being used for a single http.Request
  261. getConnCalled bool // used by clientConnPool
  262. // readLoop goroutine fields:
  263. readerDone chan struct{} // closed on error
  264. readerErr error // set before readerDone is closed
  265. idleTimeout time.Duration // or 0 for never
  266. idleTimer *time.Timer
  267. mu sync.Mutex // guards following
  268. cond *sync.Cond // hold mu; broadcast on flow/closed changes
  269. flow outflow // our conn-level flow control quota (cs.outflow is per stream)
  270. inflow inflow // peer's conn-level flow control
  271. doNotReuse bool // whether conn is marked to not be reused for any future requests
  272. closing bool
  273. closed bool
  274. seenSettings bool // true if we've seen a settings frame, false otherwise
  275. wantSettingsAck bool // we sent a SETTINGS frame and haven't heard back
  276. goAway *GoAwayFrame // if non-nil, the GoAwayFrame we received
  277. goAwayDebug string // goAway frame's debug data, retained as a string
  278. streams map[uint32]*clientStream // client-initiated
  279. streamsReserved int // incr by ReserveNewRequest; decr on RoundTrip
  280. nextStreamID uint32
  281. pendingRequests int // requests blocked and waiting to be sent because len(streams) == maxConcurrentStreams
  282. pings map[[8]byte]chan struct{} // in flight ping data to notification channel
  283. br *bufio.Reader
  284. lastActive time.Time
  285. lastIdle time.Time // time last idle
  286. // Settings from peer: (also guarded by wmu)
  287. maxFrameSize uint32
  288. maxConcurrentStreams uint32
  289. peerMaxHeaderListSize uint64
  290. peerMaxHeaderTableSize uint32
  291. initialWindowSize uint32
  292. // reqHeaderMu is a 1-element semaphore channel controlling access to sending new requests.
  293. // Write to reqHeaderMu to lock it, read from it to unlock.
  294. // Lock reqmu BEFORE mu or wmu.
  295. reqHeaderMu chan struct{}
  296. // wmu is held while writing.
  297. // Acquire BEFORE mu when holding both, to avoid blocking mu on network writes.
  298. // Only acquire both at the same time when changing peer settings.
  299. wmu sync.Mutex
  300. bw *bufio.Writer
  301. fr *Framer
  302. werr error // first write error that has occurred
  303. hbuf bytes.Buffer // HPACK encoder writes into this
  304. henc *hpack.Encoder
  305. }
  306. // clientStream is the state for a single HTTP/2 stream. One of these
  307. // is created for each Transport.RoundTrip call.
  308. type clientStream struct {
  309. cc *ClientConn
  310. // Fields of Request that we may access even after the response body is closed.
  311. ctx context.Context
  312. reqCancel <-chan struct{}
  313. trace *httptrace.ClientTrace // or nil
  314. ID uint32
  315. bufPipe pipe // buffered pipe with the flow-controlled response payload
  316. requestedGzip bool
  317. isHead bool
  318. abortOnce sync.Once
  319. abort chan struct{} // closed to signal stream should end immediately
  320. abortErr error // set if abort is closed
  321. peerClosed chan struct{} // closed when the peer sends an END_STREAM flag
  322. donec chan struct{} // closed after the stream is in the closed state
  323. on100 chan struct{} // buffered; written to if a 100 is received
  324. respHeaderRecv chan struct{} // closed when headers are received
  325. res *http.Response // set if respHeaderRecv is closed
  326. flow outflow // guarded by cc.mu
  327. inflow inflow // guarded by cc.mu
  328. bytesRemain int64 // -1 means unknown; owned by transportResponseBody.Read
  329. readErr error // sticky read error; owned by transportResponseBody.Read
  330. reqBody io.ReadCloser
  331. reqBodyContentLength int64 // -1 means unknown
  332. reqBodyClosed chan struct{} // guarded by cc.mu; non-nil on Close, closed when done
  333. // owned by writeRequest:
  334. sentEndStream bool // sent an END_STREAM flag to the peer
  335. sentHeaders bool
  336. // owned by clientConnReadLoop:
  337. firstByte bool // got the first response byte
  338. pastHeaders bool // got first MetaHeadersFrame (actual headers)
  339. pastTrailers bool // got optional second MetaHeadersFrame (trailers)
  340. num1xx uint8 // number of 1xx responses seen
  341. readClosed bool // peer sent an END_STREAM flag
  342. readAborted bool // read loop reset the stream
  343. trailer http.Header // accumulated trailers
  344. resTrailer *http.Header // client's Response.Trailer
  345. }
  346. var got1xxFuncForTests func(int, textproto.MIMEHeader) error
  347. // get1xxTraceFunc returns the value of request's httptrace.ClientTrace.Got1xxResponse func,
  348. // if any. It returns nil if not set or if the Go version is too old.
  349. func (cs *clientStream) get1xxTraceFunc() func(int, textproto.MIMEHeader) error {
  350. if fn := got1xxFuncForTests; fn != nil {
  351. return fn
  352. }
  353. return traceGot1xxResponseFunc(cs.trace)
  354. }
  355. func (cs *clientStream) abortStream(err error) {
  356. cs.cc.mu.Lock()
  357. defer cs.cc.mu.Unlock()
  358. cs.abortStreamLocked(err)
  359. }
  360. func (cs *clientStream) abortStreamLocked(err error) {
  361. cs.abortOnce.Do(func() {
  362. cs.abortErr = err
  363. close(cs.abort)
  364. })
  365. if cs.reqBody != nil {
  366. cs.closeReqBodyLocked()
  367. }
  368. // TODO(dneil): Clean up tests where cs.cc.cond is nil.
  369. if cs.cc.cond != nil {
  370. // Wake up writeRequestBody if it is waiting on flow control.
  371. cs.cc.cond.Broadcast()
  372. }
  373. }
  374. func (cs *clientStream) abortRequestBodyWrite() {
  375. cc := cs.cc
  376. cc.mu.Lock()
  377. defer cc.mu.Unlock()
  378. if cs.reqBody != nil && cs.reqBodyClosed == nil {
  379. cs.closeReqBodyLocked()
  380. cc.cond.Broadcast()
  381. }
  382. }
  383. func (cs *clientStream) closeReqBodyLocked() {
  384. if cs.reqBodyClosed != nil {
  385. return
  386. }
  387. cs.reqBodyClosed = make(chan struct{})
  388. reqBodyClosed := cs.reqBodyClosed
  389. go func() {
  390. cs.reqBody.Close()
  391. close(reqBodyClosed)
  392. }()
  393. }
  394. type stickyErrWriter struct {
  395. conn net.Conn
  396. timeout time.Duration
  397. err *error
  398. }
  399. func (sew stickyErrWriter) Write(p []byte) (n int, err error) {
  400. if *sew.err != nil {
  401. return 0, *sew.err
  402. }
  403. for {
  404. if sew.timeout != 0 {
  405. sew.conn.SetWriteDeadline(time.Now().Add(sew.timeout))
  406. }
  407. nn, err := sew.conn.Write(p[n:])
  408. n += nn
  409. if n < len(p) && nn > 0 && errors.Is(err, os.ErrDeadlineExceeded) {
  410. // Keep extending the deadline so long as we're making progress.
  411. continue
  412. }
  413. if sew.timeout != 0 {
  414. sew.conn.SetWriteDeadline(time.Time{})
  415. }
  416. *sew.err = err
  417. return n, err
  418. }
  419. }
  420. // noCachedConnError is the concrete type of ErrNoCachedConn, which
  421. // needs to be detected by net/http regardless of whether it's its
  422. // bundled version (in h2_bundle.go with a rewritten type name) or
  423. // from a user's x/net/http2. As such, as it has a unique method name
  424. // (IsHTTP2NoCachedConnError) that net/http sniffs for via func
  425. // isNoCachedConnError.
  426. type noCachedConnError struct{}
  427. func (noCachedConnError) IsHTTP2NoCachedConnError() {}
  428. func (noCachedConnError) Error() string { return "http2: no cached connection was available" }
  429. // isNoCachedConnError reports whether err is of type noCachedConnError
  430. // or its equivalent renamed type in net/http2's h2_bundle.go. Both types
  431. // may coexist in the same running program.
  432. func isNoCachedConnError(err error) bool {
  433. _, ok := err.(interface{ IsHTTP2NoCachedConnError() })
  434. return ok
  435. }
  436. var ErrNoCachedConn error = noCachedConnError{}
  437. // RoundTripOpt are options for the Transport.RoundTripOpt method.
  438. type RoundTripOpt struct {
  439. // OnlyCachedConn controls whether RoundTripOpt may
  440. // create a new TCP connection. If set true and
  441. // no cached connection is available, RoundTripOpt
  442. // will return ErrNoCachedConn.
  443. OnlyCachedConn bool
  444. }
  445. func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
  446. return t.RoundTripOpt(req, RoundTripOpt{})
  447. }
  448. // authorityAddr returns a given authority (a host/IP, or host:port / ip:port)
  449. // and returns a host:port. The port 443 is added if needed.
  450. func authorityAddr(scheme string, authority string) (addr string) {
  451. host, port, err := net.SplitHostPort(authority)
  452. if err != nil { // authority didn't have a port
  453. host = authority
  454. port = ""
  455. }
  456. if port == "" { // authority's port was empty
  457. port = "443"
  458. if scheme == "http" {
  459. port = "80"
  460. }
  461. }
  462. if a, err := idna.ToASCII(host); err == nil {
  463. host = a
  464. }
  465. // IPv6 address literal, without a port:
  466. if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
  467. return host + ":" + port
  468. }
  469. return net.JoinHostPort(host, port)
  470. }
  471. var retryBackoffHook func(time.Duration) *time.Timer
  472. func backoffNewTimer(d time.Duration) *time.Timer {
  473. if retryBackoffHook != nil {
  474. return retryBackoffHook(d)
  475. }
  476. return time.NewTimer(d)
  477. }
  478. // RoundTripOpt is like RoundTrip, but takes options.
  479. func (t *Transport) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) {
  480. if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) {
  481. return nil, errors.New("http2: unsupported scheme")
  482. }
  483. addr := authorityAddr(req.URL.Scheme, req.URL.Host)
  484. for retry := 0; ; retry++ {
  485. cc, err := t.connPool().GetClientConn(req, addr)
  486. if err != nil {
  487. t.vlogf("http2: Transport failed to get client conn for %s: %v", addr, err)
  488. return nil, err
  489. }
  490. reused := !atomic.CompareAndSwapUint32(&cc.reused, 0, 1)
  491. traceGotConn(req, cc, reused)
  492. res, err := cc.RoundTrip(req)
  493. if err != nil && retry <= 6 {
  494. roundTripErr := err
  495. if req, err = shouldRetryRequest(req, err); err == nil {
  496. // After the first retry, do exponential backoff with 10% jitter.
  497. if retry == 0 {
  498. t.vlogf("RoundTrip retrying after failure: %v", roundTripErr)
  499. continue
  500. }
  501. backoff := float64(uint(1) << (uint(retry) - 1))
  502. backoff += backoff * (0.1 * mathrand.Float64())
  503. d := time.Second * time.Duration(backoff)
  504. timer := backoffNewTimer(d)
  505. select {
  506. case <-timer.C:
  507. t.vlogf("RoundTrip retrying after failure: %v", roundTripErr)
  508. continue
  509. case <-req.Context().Done():
  510. timer.Stop()
  511. err = req.Context().Err()
  512. }
  513. }
  514. }
  515. if err != nil {
  516. t.vlogf("RoundTrip failure: %v", err)
  517. return nil, err
  518. }
  519. return res, nil
  520. }
  521. }
  522. // CloseIdleConnections closes any connections which were previously
  523. // connected from previous requests but are now sitting idle.
  524. // It does not interrupt any connections currently in use.
  525. func (t *Transport) CloseIdleConnections() {
  526. if cp, ok := t.connPool().(clientConnPoolIdleCloser); ok {
  527. cp.closeIdleConnections()
  528. }
  529. }
  530. var (
  531. errClientConnClosed = errors.New("http2: client conn is closed")
  532. errClientConnUnusable = errors.New("http2: client conn not usable")
  533. errClientConnGotGoAway = errors.New("http2: Transport received Server's graceful shutdown GOAWAY")
  534. )
  535. // shouldRetryRequest is called by RoundTrip when a request fails to get
  536. // response headers. It is always called with a non-nil error.
  537. // It returns either a request to retry (either the same request, or a
  538. // modified clone), or an error if the request can't be replayed.
  539. func shouldRetryRequest(req *http.Request, err error) (*http.Request, error) {
  540. if !canRetryError(err) {
  541. return nil, err
  542. }
  543. // If the Body is nil (or http.NoBody), it's safe to reuse
  544. // this request and its Body.
  545. if req.Body == nil || req.Body == http.NoBody {
  546. return req, nil
  547. }
  548. // If the request body can be reset back to its original
  549. // state via the optional req.GetBody, do that.
  550. if req.GetBody != nil {
  551. body, err := req.GetBody()
  552. if err != nil {
  553. return nil, err
  554. }
  555. newReq := *req
  556. newReq.Body = body
  557. return &newReq, nil
  558. }
  559. // The Request.Body can't reset back to the beginning, but we
  560. // don't seem to have started to read from it yet, so reuse
  561. // the request directly.
  562. if err == errClientConnUnusable {
  563. return req, nil
  564. }
  565. return nil, fmt.Errorf("http2: Transport: cannot retry err [%v] after Request.Body was written; define Request.GetBody to avoid this error", err)
  566. }
  567. func canRetryError(err error) bool {
  568. if err == errClientConnUnusable || err == errClientConnGotGoAway {
  569. return true
  570. }
  571. if se, ok := err.(StreamError); ok {
  572. if se.Code == ErrCodeProtocol && se.Cause == errFromPeer {
  573. // See golang/go#47635, golang/go#42777
  574. return true
  575. }
  576. return se.Code == ErrCodeRefusedStream
  577. }
  578. return false
  579. }
  580. func (t *Transport) dialClientConn(ctx context.Context, addr string, singleUse bool) (*ClientConn, error) {
  581. host, _, err := net.SplitHostPort(addr)
  582. if err != nil {
  583. return nil, err
  584. }
  585. tconn, err := t.dialTLS(ctx, "tcp", addr, t.newTLSConfig(host))
  586. if err != nil {
  587. return nil, err
  588. }
  589. return t.newClientConn(tconn, singleUse)
  590. }
  591. func (t *Transport) newTLSConfig(host string) *tls.Config {
  592. cfg := new(tls.Config)
  593. if t.TLSClientConfig != nil {
  594. *cfg = *t.TLSClientConfig.Clone()
  595. }
  596. if !strSliceContains(cfg.NextProtos, NextProtoTLS) {
  597. cfg.NextProtos = append([]string{NextProtoTLS}, cfg.NextProtos...)
  598. }
  599. if cfg.ServerName == "" {
  600. cfg.ServerName = host
  601. }
  602. return cfg
  603. }
  604. func (t *Transport) dialTLS(ctx context.Context, network, addr string, tlsCfg *tls.Config) (net.Conn, error) {
  605. if t.DialTLSContext != nil {
  606. return t.DialTLSContext(ctx, network, addr, tlsCfg)
  607. } else if t.DialTLS != nil {
  608. return t.DialTLS(network, addr, tlsCfg)
  609. }
  610. tlsCn, err := t.dialTLSWithContext(ctx, network, addr, tlsCfg)
  611. if err != nil {
  612. return nil, err
  613. }
  614. state := tlsCn.ConnectionState()
  615. if p := state.NegotiatedProtocol; p != NextProtoTLS {
  616. return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, NextProtoTLS)
  617. }
  618. if !state.NegotiatedProtocolIsMutual {
  619. return nil, errors.New("http2: could not negotiate protocol mutually")
  620. }
  621. return tlsCn, nil
  622. }
  623. // disableKeepAlives reports whether connections should be closed as
  624. // soon as possible after handling the first request.
  625. func (t *Transport) disableKeepAlives() bool {
  626. return t.t1 != nil && t.t1.DisableKeepAlives
  627. }
  628. func (t *Transport) expectContinueTimeout() time.Duration {
  629. if t.t1 == nil {
  630. return 0
  631. }
  632. return t.t1.ExpectContinueTimeout
  633. }
  634. func (t *Transport) maxDecoderHeaderTableSize() uint32 {
  635. if v := t.MaxDecoderHeaderTableSize; v > 0 {
  636. return v
  637. }
  638. return initialHeaderTableSize
  639. }
  640. func (t *Transport) maxEncoderHeaderTableSize() uint32 {
  641. if v := t.MaxEncoderHeaderTableSize; v > 0 {
  642. return v
  643. }
  644. return initialHeaderTableSize
  645. }
  646. func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) {
  647. return t.newClientConn(c, t.disableKeepAlives())
  648. }
  649. func (t *Transport) newClientConn(c net.Conn, singleUse bool) (*ClientConn, error) {
  650. cc := &ClientConn{
  651. t: t,
  652. tconn: c,
  653. readerDone: make(chan struct{}),
  654. nextStreamID: 1,
  655. maxFrameSize: 16 << 10, // spec default
  656. initialWindowSize: 65535, // spec default
  657. maxConcurrentStreams: initialMaxConcurrentStreams, // "infinite", per spec. Use a smaller value until we have received server settings.
  658. peerMaxHeaderListSize: 0xffffffffffffffff, // "infinite", per spec. Use 2^64-1 instead.
  659. streams: make(map[uint32]*clientStream),
  660. singleUse: singleUse,
  661. wantSettingsAck: true,
  662. pings: make(map[[8]byte]chan struct{}),
  663. reqHeaderMu: make(chan struct{}, 1),
  664. }
  665. if d := t.idleConnTimeout(); d != 0 {
  666. cc.idleTimeout = d
  667. cc.idleTimer = time.AfterFunc(d, cc.onIdleTimeout)
  668. }
  669. if VerboseLogs {
  670. t.vlogf("http2: Transport creating client conn %p to %v", cc, c.RemoteAddr())
  671. }
  672. cc.cond = sync.NewCond(&cc.mu)
  673. cc.flow.add(int32(initialWindowSize))
  674. // TODO: adjust this writer size to account for frame size +
  675. // MTU + crypto/tls record padding.
  676. cc.bw = bufio.NewWriter(stickyErrWriter{
  677. conn: c,
  678. timeout: t.WriteByteTimeout,
  679. err: &cc.werr,
  680. })
  681. cc.br = bufio.NewReader(c)
  682. cc.fr = NewFramer(cc.bw, cc.br)
  683. if t.maxFrameReadSize() != 0 {
  684. cc.fr.SetMaxReadFrameSize(t.maxFrameReadSize())
  685. }
  686. if t.CountError != nil {
  687. cc.fr.countError = t.CountError
  688. }
  689. maxHeaderTableSize := t.maxDecoderHeaderTableSize()
  690. cc.fr.ReadMetaHeaders = hpack.NewDecoder(maxHeaderTableSize, nil)
  691. cc.fr.MaxHeaderListSize = t.maxHeaderListSize()
  692. cc.henc = hpack.NewEncoder(&cc.hbuf)
  693. cc.henc.SetMaxDynamicTableSizeLimit(t.maxEncoderHeaderTableSize())
  694. cc.peerMaxHeaderTableSize = initialHeaderTableSize
  695. if t.AllowHTTP {
  696. cc.nextStreamID = 3
  697. }
  698. if cs, ok := c.(connectionStater); ok {
  699. state := cs.ConnectionState()
  700. cc.tlsState = &state
  701. }
  702. initialSettings := []Setting{
  703. {ID: SettingEnablePush, Val: 0},
  704. {ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow},
  705. }
  706. if max := t.maxFrameReadSize(); max != 0 {
  707. initialSettings = append(initialSettings, Setting{ID: SettingMaxFrameSize, Val: max})
  708. }
  709. if max := t.maxHeaderListSize(); max != 0 {
  710. initialSettings = append(initialSettings, Setting{ID: SettingMaxHeaderListSize, Val: max})
  711. }
  712. if maxHeaderTableSize != initialHeaderTableSize {
  713. initialSettings = append(initialSettings, Setting{ID: SettingHeaderTableSize, Val: maxHeaderTableSize})
  714. }
  715. cc.bw.Write(clientPreface)
  716. cc.fr.WriteSettings(initialSettings...)
  717. cc.fr.WriteWindowUpdate(0, transportDefaultConnFlow)
  718. cc.inflow.init(transportDefaultConnFlow + initialWindowSize)
  719. cc.bw.Flush()
  720. if cc.werr != nil {
  721. cc.Close()
  722. return nil, cc.werr
  723. }
  724. go cc.readLoop()
  725. return cc, nil
  726. }
  727. func (cc *ClientConn) healthCheck() {
  728. pingTimeout := cc.t.pingTimeout()
  729. // We don't need to periodically ping in the health check, because the readLoop of ClientConn will
  730. // trigger the healthCheck again if there is no frame received.
  731. ctx, cancel := context.WithTimeout(context.Background(), pingTimeout)
  732. defer cancel()
  733. cc.vlogf("http2: Transport sending health check")
  734. err := cc.Ping(ctx)
  735. if err != nil {
  736. cc.vlogf("http2: Transport health check failure: %v", err)
  737. cc.closeForLostPing()
  738. } else {
  739. cc.vlogf("http2: Transport health check success")
  740. }
  741. }
  742. // SetDoNotReuse marks cc as not reusable for future HTTP requests.
  743. func (cc *ClientConn) SetDoNotReuse() {
  744. cc.mu.Lock()
  745. defer cc.mu.Unlock()
  746. cc.doNotReuse = true
  747. }
  748. func (cc *ClientConn) setGoAway(f *GoAwayFrame) {
  749. cc.mu.Lock()
  750. defer cc.mu.Unlock()
  751. old := cc.goAway
  752. cc.goAway = f
  753. // Merge the previous and current GoAway error frames.
  754. if cc.goAwayDebug == "" {
  755. cc.goAwayDebug = string(f.DebugData())
  756. }
  757. if old != nil && old.ErrCode != ErrCodeNo {
  758. cc.goAway.ErrCode = old.ErrCode
  759. }
  760. last := f.LastStreamID
  761. for streamID, cs := range cc.streams {
  762. if streamID > last {
  763. cs.abortStreamLocked(errClientConnGotGoAway)
  764. }
  765. }
  766. }
  767. // CanTakeNewRequest reports whether the connection can take a new request,
  768. // meaning it has not been closed or received or sent a GOAWAY.
  769. //
  770. // If the caller is going to immediately make a new request on this
  771. // connection, use ReserveNewRequest instead.
  772. func (cc *ClientConn) CanTakeNewRequest() bool {
  773. cc.mu.Lock()
  774. defer cc.mu.Unlock()
  775. return cc.canTakeNewRequestLocked()
  776. }
  777. // ReserveNewRequest is like CanTakeNewRequest but also reserves a
  778. // concurrent stream in cc. The reservation is decremented on the
  779. // next call to RoundTrip.
  780. func (cc *ClientConn) ReserveNewRequest() bool {
  781. cc.mu.Lock()
  782. defer cc.mu.Unlock()
  783. if st := cc.idleStateLocked(); !st.canTakeNewRequest {
  784. return false
  785. }
  786. cc.streamsReserved++
  787. return true
  788. }
  789. // ClientConnState describes the state of a ClientConn.
  790. type ClientConnState struct {
  791. // Closed is whether the connection is closed.
  792. Closed bool
  793. // Closing is whether the connection is in the process of
  794. // closing. It may be closing due to shutdown, being a
  795. // single-use connection, being marked as DoNotReuse, or
  796. // having received a GOAWAY frame.
  797. Closing bool
  798. // StreamsActive is how many streams are active.
  799. StreamsActive int
  800. // StreamsReserved is how many streams have been reserved via
  801. // ClientConn.ReserveNewRequest.
  802. StreamsReserved int
  803. // StreamsPending is how many requests have been sent in excess
  804. // of the peer's advertised MaxConcurrentStreams setting and
  805. // are waiting for other streams to complete.
  806. StreamsPending int
  807. // MaxConcurrentStreams is how many concurrent streams the
  808. // peer advertised as acceptable. Zero means no SETTINGS
  809. // frame has been received yet.
  810. MaxConcurrentStreams uint32
  811. // LastIdle, if non-zero, is when the connection last
  812. // transitioned to idle state.
  813. LastIdle time.Time
  814. }
  815. // State returns a snapshot of cc's state.
  816. func (cc *ClientConn) State() ClientConnState {
  817. cc.wmu.Lock()
  818. maxConcurrent := cc.maxConcurrentStreams
  819. if !cc.seenSettings {
  820. maxConcurrent = 0
  821. }
  822. cc.wmu.Unlock()
  823. cc.mu.Lock()
  824. defer cc.mu.Unlock()
  825. return ClientConnState{
  826. Closed: cc.closed,
  827. Closing: cc.closing || cc.singleUse || cc.doNotReuse || cc.goAway != nil,
  828. StreamsActive: len(cc.streams),
  829. StreamsReserved: cc.streamsReserved,
  830. StreamsPending: cc.pendingRequests,
  831. LastIdle: cc.lastIdle,
  832. MaxConcurrentStreams: maxConcurrent,
  833. }
  834. }
  835. // clientConnIdleState describes the suitability of a client
  836. // connection to initiate a new RoundTrip request.
  837. type clientConnIdleState struct {
  838. canTakeNewRequest bool
  839. }
  840. func (cc *ClientConn) idleState() clientConnIdleState {
  841. cc.mu.Lock()
  842. defer cc.mu.Unlock()
  843. return cc.idleStateLocked()
  844. }
  845. func (cc *ClientConn) idleStateLocked() (st clientConnIdleState) {
  846. if cc.singleUse && cc.nextStreamID > 1 {
  847. return
  848. }
  849. var maxConcurrentOkay bool
  850. if cc.t.StrictMaxConcurrentStreams {
  851. // We'll tell the caller we can take a new request to
  852. // prevent the caller from dialing a new TCP
  853. // connection, but then we'll block later before
  854. // writing it.
  855. maxConcurrentOkay = true
  856. } else {
  857. maxConcurrentOkay = int64(len(cc.streams)+cc.streamsReserved+1) <= int64(cc.maxConcurrentStreams)
  858. }
  859. st.canTakeNewRequest = cc.goAway == nil && !cc.closed && !cc.closing && maxConcurrentOkay &&
  860. !cc.doNotReuse &&
  861. int64(cc.nextStreamID)+2*int64(cc.pendingRequests) < math.MaxInt32 &&
  862. !cc.tooIdleLocked()
  863. return
  864. }
  865. func (cc *ClientConn) canTakeNewRequestLocked() bool {
  866. st := cc.idleStateLocked()
  867. return st.canTakeNewRequest
  868. }
  869. // tooIdleLocked reports whether this connection has been been sitting idle
  870. // for too much wall time.
  871. func (cc *ClientConn) tooIdleLocked() bool {
  872. // The Round(0) strips the monontonic clock reading so the
  873. // times are compared based on their wall time. We don't want
  874. // to reuse a connection that's been sitting idle during
  875. // VM/laptop suspend if monotonic time was also frozen.
  876. return cc.idleTimeout != 0 && !cc.lastIdle.IsZero() && time.Since(cc.lastIdle.Round(0)) > cc.idleTimeout
  877. }
  878. // onIdleTimeout is called from a time.AfterFunc goroutine. It will
  879. // only be called when we're idle, but because we're coming from a new
  880. // goroutine, there could be a new request coming in at the same time,
  881. // so this simply calls the synchronized closeIfIdle to shut down this
  882. // connection. The timer could just call closeIfIdle, but this is more
  883. // clear.
  884. func (cc *ClientConn) onIdleTimeout() {
  885. cc.closeIfIdle()
  886. }
  887. func (cc *ClientConn) closeConn() {
  888. t := time.AfterFunc(250*time.Millisecond, cc.forceCloseConn)
  889. defer t.Stop()
  890. cc.tconn.Close()
  891. }
  892. // A tls.Conn.Close can hang for a long time if the peer is unresponsive.
  893. // Try to shut it down more aggressively.
  894. func (cc *ClientConn) forceCloseConn() {
  895. tc, ok := cc.tconn.(*tls.Conn)
  896. if !ok {
  897. return
  898. }
  899. if nc := tc.NetConn(); nc != nil {
  900. nc.Close()
  901. }
  902. }
  903. func (cc *ClientConn) closeIfIdle() {
  904. cc.mu.Lock()
  905. if len(cc.streams) > 0 || cc.streamsReserved > 0 {
  906. cc.mu.Unlock()
  907. return
  908. }
  909. cc.closed = true
  910. nextID := cc.nextStreamID
  911. // TODO: do clients send GOAWAY too? maybe? Just Close:
  912. cc.mu.Unlock()
  913. if VerboseLogs {
  914. cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, nextID-2)
  915. }
  916. cc.closeConn()
  917. }
  918. func (cc *ClientConn) isDoNotReuseAndIdle() bool {
  919. cc.mu.Lock()
  920. defer cc.mu.Unlock()
  921. return cc.doNotReuse && len(cc.streams) == 0
  922. }
  923. var shutdownEnterWaitStateHook = func() {}
  924. // Shutdown gracefully closes the client connection, waiting for running streams to complete.
  925. func (cc *ClientConn) Shutdown(ctx context.Context) error {
  926. if err := cc.sendGoAway(); err != nil {
  927. return err
  928. }
  929. // Wait for all in-flight streams to complete or connection to close
  930. done := make(chan struct{})
  931. cancelled := false // guarded by cc.mu
  932. go func() {
  933. cc.mu.Lock()
  934. defer cc.mu.Unlock()
  935. for {
  936. if len(cc.streams) == 0 || cc.closed {
  937. cc.closed = true
  938. close(done)
  939. break
  940. }
  941. if cancelled {
  942. break
  943. }
  944. cc.cond.Wait()
  945. }
  946. }()
  947. shutdownEnterWaitStateHook()
  948. select {
  949. case <-done:
  950. cc.closeConn()
  951. return nil
  952. case <-ctx.Done():
  953. cc.mu.Lock()
  954. // Free the goroutine above
  955. cancelled = true
  956. cc.cond.Broadcast()
  957. cc.mu.Unlock()
  958. return ctx.Err()
  959. }
  960. }
  961. func (cc *ClientConn) sendGoAway() error {
  962. cc.mu.Lock()
  963. closing := cc.closing
  964. cc.closing = true
  965. maxStreamID := cc.nextStreamID
  966. cc.mu.Unlock()
  967. if closing {
  968. // GOAWAY sent already
  969. return nil
  970. }
  971. cc.wmu.Lock()
  972. defer cc.wmu.Unlock()
  973. // Send a graceful shutdown frame to server
  974. if err := cc.fr.WriteGoAway(maxStreamID, ErrCodeNo, nil); err != nil {
  975. return err
  976. }
  977. if err := cc.bw.Flush(); err != nil {
  978. return err
  979. }
  980. // Prevent new requests
  981. return nil
  982. }
  983. // closes the client connection immediately. In-flight requests are interrupted.
  984. // err is sent to streams.
  985. func (cc *ClientConn) closeForError(err error) {
  986. cc.mu.Lock()
  987. cc.closed = true
  988. for _, cs := range cc.streams {
  989. cs.abortStreamLocked(err)
  990. }
  991. cc.cond.Broadcast()
  992. cc.mu.Unlock()
  993. cc.closeConn()
  994. }
  995. // Close closes the client connection immediately.
  996. //
  997. // In-flight requests are interrupted. For a graceful shutdown, use Shutdown instead.
  998. func (cc *ClientConn) Close() error {
  999. err := errors.New("http2: client connection force closed via ClientConn.Close")
  1000. cc.closeForError(err)
  1001. return nil
  1002. }
  1003. // closes the client connection immediately. In-flight requests are interrupted.
  1004. func (cc *ClientConn) closeForLostPing() {
  1005. err := errors.New("http2: client connection lost")
  1006. if f := cc.t.CountError; f != nil {
  1007. f("conn_close_lost_ping")
  1008. }
  1009. cc.closeForError(err)
  1010. }
  1011. // errRequestCanceled is a copy of net/http's errRequestCanceled because it's not
  1012. // exported. At least they'll be DeepEqual for h1-vs-h2 comparisons tests.
  1013. var errRequestCanceled = errors.New("net/http: request canceled")
  1014. func commaSeparatedTrailers(req *http.Request) (string, error) {
  1015. keys := make([]string, 0, len(req.Trailer))
  1016. for k := range req.Trailer {
  1017. k = canonicalHeader(k)
  1018. switch k {
  1019. case "Transfer-Encoding", "Trailer", "Content-Length":
  1020. return "", fmt.Errorf("invalid Trailer key %q", k)
  1021. }
  1022. keys = append(keys, k)
  1023. }
  1024. if len(keys) > 0 {
  1025. sort.Strings(keys)
  1026. return strings.Join(keys, ","), nil
  1027. }
  1028. return "", nil
  1029. }
  1030. func (cc *ClientConn) responseHeaderTimeout() time.Duration {
  1031. if cc.t.t1 != nil {
  1032. return cc.t.t1.ResponseHeaderTimeout
  1033. }
  1034. // No way to do this (yet?) with just an http2.Transport. Probably
  1035. // no need. Request.Cancel this is the new way. We only need to support
  1036. // this for compatibility with the old http.Transport fields when
  1037. // we're doing transparent http2.
  1038. return 0
  1039. }
  1040. // checkConnHeaders checks whether req has any invalid connection-level headers.
  1041. // per RFC 7540 section 8.1.2.2: Connection-Specific Header Fields.
  1042. // Certain headers are special-cased as okay but not transmitted later.
  1043. func checkConnHeaders(req *http.Request) error {
  1044. if v := req.Header.Get("Upgrade"); v != "" {
  1045. return fmt.Errorf("http2: invalid Upgrade request header: %q", req.Header["Upgrade"])
  1046. }
  1047. if vv := req.Header["Transfer-Encoding"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "chunked") {
  1048. return fmt.Errorf("http2: invalid Transfer-Encoding request header: %q", vv)
  1049. }
  1050. if vv := req.Header["Connection"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && !asciiEqualFold(vv[0], "close") && !asciiEqualFold(vv[0], "keep-alive")) {
  1051. return fmt.Errorf("http2: invalid Connection request header: %q", vv)
  1052. }
  1053. return nil
  1054. }
  1055. // actualContentLength returns a sanitized version of
  1056. // req.ContentLength, where 0 actually means zero (not unknown) and -1
  1057. // means unknown.
  1058. func actualContentLength(req *http.Request) int64 {
  1059. if req.Body == nil || req.Body == http.NoBody {
  1060. return 0
  1061. }
  1062. if req.ContentLength != 0 {
  1063. return req.ContentLength
  1064. }
  1065. return -1
  1066. }
  1067. func (cc *ClientConn) decrStreamReservations() {
  1068. cc.mu.Lock()
  1069. defer cc.mu.Unlock()
  1070. cc.decrStreamReservationsLocked()
  1071. }
  1072. func (cc *ClientConn) decrStreamReservationsLocked() {
  1073. if cc.streamsReserved > 0 {
  1074. cc.streamsReserved--
  1075. }
  1076. }
  1077. func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) {
  1078. ctx := req.Context()
  1079. cs := &clientStream{
  1080. cc: cc,
  1081. ctx: ctx,
  1082. reqCancel: req.Cancel,
  1083. isHead: req.Method == "HEAD",
  1084. reqBody: req.Body,
  1085. reqBodyContentLength: actualContentLength(req),
  1086. trace: httptrace.ContextClientTrace(ctx),
  1087. peerClosed: make(chan struct{}),
  1088. abort: make(chan struct{}),
  1089. respHeaderRecv: make(chan struct{}),
  1090. donec: make(chan struct{}),
  1091. }
  1092. go cs.doRequest(req)
  1093. waitDone := func() error {
  1094. select {
  1095. case <-cs.donec:
  1096. return nil
  1097. case <-ctx.Done():
  1098. return ctx.Err()
  1099. case <-cs.reqCancel:
  1100. return errRequestCanceled
  1101. }
  1102. }
  1103. handleResponseHeaders := func() (*http.Response, error) {
  1104. res := cs.res
  1105. if res.StatusCode > 299 {
  1106. // On error or status code 3xx, 4xx, 5xx, etc abort any
  1107. // ongoing write, assuming that the server doesn't care
  1108. // about our request body. If the server replied with 1xx or
  1109. // 2xx, however, then assume the server DOES potentially
  1110. // want our body (e.g. full-duplex streaming:
  1111. // golang.org/issue/13444). If it turns out the server
  1112. // doesn't, they'll RST_STREAM us soon enough. This is a
  1113. // heuristic to avoid adding knobs to Transport. Hopefully
  1114. // we can keep it.
  1115. cs.abortRequestBodyWrite()
  1116. }
  1117. res.Request = req
  1118. res.TLS = cc.tlsState
  1119. if res.Body == noBody && actualContentLength(req) == 0 {
  1120. // If there isn't a request or response body still being
  1121. // written, then wait for the stream to be closed before
  1122. // RoundTrip returns.
  1123. if err := waitDone(); err != nil {
  1124. return nil, err
  1125. }
  1126. }
  1127. return res, nil
  1128. }
  1129. cancelRequest := func(cs *clientStream, err error) error {
  1130. cs.cc.mu.Lock()
  1131. bodyClosed := cs.reqBodyClosed
  1132. cs.cc.mu.Unlock()
  1133. // Wait for the request body to be closed.
  1134. //
  1135. // If nothing closed the body before now, abortStreamLocked
  1136. // will have started a goroutine to close it.
  1137. //
  1138. // Closing the body before returning avoids a race condition
  1139. // with net/http checking its readTrackingBody to see if the
  1140. // body was read from or closed. See golang/go#60041.
  1141. //
  1142. // The body is closed in a separate goroutine without the
  1143. // connection mutex held, but dropping the mutex before waiting
  1144. // will keep us from holding it indefinitely if the body
  1145. // close is slow for some reason.
  1146. if bodyClosed != nil {
  1147. <-bodyClosed
  1148. }
  1149. return err
  1150. }
  1151. for {
  1152. select {
  1153. case <-cs.respHeaderRecv:
  1154. return handleResponseHeaders()
  1155. case <-cs.abort:
  1156. select {
  1157. case <-cs.respHeaderRecv:
  1158. // If both cs.respHeaderRecv and cs.abort are signaling,
  1159. // pick respHeaderRecv. The server probably wrote the
  1160. // response and immediately reset the stream.
  1161. // golang.org/issue/49645
  1162. return handleResponseHeaders()
  1163. default:
  1164. waitDone()
  1165. return nil, cs.abortErr
  1166. }
  1167. case <-ctx.Done():
  1168. err := ctx.Err()
  1169. cs.abortStream(err)
  1170. return nil, cancelRequest(cs, err)
  1171. case <-cs.reqCancel:
  1172. cs.abortStream(errRequestCanceled)
  1173. return nil, cancelRequest(cs, errRequestCanceled)
  1174. }
  1175. }
  1176. }
  1177. // doRequest runs for the duration of the request lifetime.
  1178. //
  1179. // It sends the request and performs post-request cleanup (closing Request.Body, etc.).
  1180. func (cs *clientStream) doRequest(req *http.Request) {
  1181. err := cs.writeRequest(req)
  1182. cs.cleanupWriteRequest(err)
  1183. }
  1184. // writeRequest sends a request.
  1185. //
  1186. // It returns nil after the request is written, the response read,
  1187. // and the request stream is half-closed by the peer.
  1188. //
  1189. // It returns non-nil if the request ends otherwise.
  1190. // If the returned error is StreamError, the error Code may be used in resetting the stream.
  1191. func (cs *clientStream) writeRequest(req *http.Request) (err error) {
  1192. cc := cs.cc
  1193. ctx := cs.ctx
  1194. if err := checkConnHeaders(req); err != nil {
  1195. return err
  1196. }
  1197. // Acquire the new-request lock by writing to reqHeaderMu.
  1198. // This lock guards the critical section covering allocating a new stream ID
  1199. // (requires mu) and creating the stream (requires wmu).
  1200. if cc.reqHeaderMu == nil {
  1201. panic("RoundTrip on uninitialized ClientConn") // for tests
  1202. }
  1203. select {
  1204. case cc.reqHeaderMu <- struct{}{}:
  1205. case <-cs.reqCancel:
  1206. return errRequestCanceled
  1207. case <-ctx.Done():
  1208. return ctx.Err()
  1209. }
  1210. cc.mu.Lock()
  1211. if cc.idleTimer != nil {
  1212. cc.idleTimer.Stop()
  1213. }
  1214. cc.decrStreamReservationsLocked()
  1215. if err := cc.awaitOpenSlotForStreamLocked(cs); err != nil {
  1216. cc.mu.Unlock()
  1217. <-cc.reqHeaderMu
  1218. return err
  1219. }
  1220. cc.addStreamLocked(cs) // assigns stream ID
  1221. if isConnectionCloseRequest(req) {
  1222. cc.doNotReuse = true
  1223. }
  1224. cc.mu.Unlock()
  1225. // TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere?
  1226. if !cc.t.disableCompression() &&
  1227. req.Header.Get("Accept-Encoding") == "" &&
  1228. req.Header.Get("Range") == "" &&
  1229. !cs.isHead {
  1230. // Request gzip only, not deflate. Deflate is ambiguous and
  1231. // not as universally supported anyway.
  1232. // See: https://zlib.net/zlib_faq.html#faq39
  1233. //
  1234. // Note that we don't request this for HEAD requests,
  1235. // due to a bug in nginx:
  1236. // http://trac.nginx.org/nginx/ticket/358
  1237. // https://golang.org/issue/5522
  1238. //
  1239. // We don't request gzip if the request is for a range, since
  1240. // auto-decoding a portion of a gzipped document will just fail
  1241. // anyway. See https://golang.org/issue/8923
  1242. cs.requestedGzip = true
  1243. }
  1244. continueTimeout := cc.t.expectContinueTimeout()
  1245. if continueTimeout != 0 {
  1246. if !httpguts.HeaderValuesContainsToken(req.Header["Expect"], "100-continue") {
  1247. continueTimeout = 0
  1248. } else {
  1249. cs.on100 = make(chan struct{}, 1)
  1250. }
  1251. }
  1252. // Past this point (where we send request headers), it is possible for
  1253. // RoundTrip to return successfully. Since the RoundTrip contract permits
  1254. // the caller to "mutate or reuse" the Request after closing the Response's Body,
  1255. // we must take care when referencing the Request from here on.
  1256. err = cs.encodeAndWriteHeaders(req)
  1257. <-cc.reqHeaderMu
  1258. if err != nil {
  1259. return err
  1260. }
  1261. hasBody := cs.reqBodyContentLength != 0
  1262. if !hasBody {
  1263. cs.sentEndStream = true
  1264. } else {
  1265. if continueTimeout != 0 {
  1266. traceWait100Continue(cs.trace)
  1267. timer := time.NewTimer(continueTimeout)
  1268. select {
  1269. case <-timer.C:
  1270. err = nil
  1271. case <-cs.on100:
  1272. err = nil
  1273. case <-cs.abort:
  1274. err = cs.abortErr
  1275. case <-ctx.Done():
  1276. err = ctx.Err()
  1277. case <-cs.reqCancel:
  1278. err = errRequestCanceled
  1279. }
  1280. timer.Stop()
  1281. if err != nil {
  1282. traceWroteRequest(cs.trace, err)
  1283. return err
  1284. }
  1285. }
  1286. if err = cs.writeRequestBody(req); err != nil {
  1287. if err != errStopReqBodyWrite {
  1288. traceWroteRequest(cs.trace, err)
  1289. return err
  1290. }
  1291. } else {
  1292. cs.sentEndStream = true
  1293. }
  1294. }
  1295. traceWroteRequest(cs.trace, err)
  1296. var respHeaderTimer <-chan time.Time
  1297. var respHeaderRecv chan struct{}
  1298. if d := cc.responseHeaderTimeout(); d != 0 {
  1299. timer := time.NewTimer(d)
  1300. defer timer.Stop()
  1301. respHeaderTimer = timer.C
  1302. respHeaderRecv = cs.respHeaderRecv
  1303. }
  1304. // Wait until the peer half-closes its end of the stream,
  1305. // or until the request is aborted (via context, error, or otherwise),
  1306. // whichever comes first.
  1307. for {
  1308. select {
  1309. case <-cs.peerClosed:
  1310. return nil
  1311. case <-respHeaderTimer:
  1312. return errTimeout
  1313. case <-respHeaderRecv:
  1314. respHeaderRecv = nil
  1315. respHeaderTimer = nil // keep waiting for END_STREAM
  1316. case <-cs.abort:
  1317. return cs.abortErr
  1318. case <-ctx.Done():
  1319. return ctx.Err()
  1320. case <-cs.reqCancel:
  1321. return errRequestCanceled
  1322. }
  1323. }
  1324. }
  1325. func (cs *clientStream) encodeAndWriteHeaders(req *http.Request) error {
  1326. cc := cs.cc
  1327. ctx := cs.ctx
  1328. cc.wmu.Lock()
  1329. defer cc.wmu.Unlock()
  1330. // If the request was canceled while waiting for cc.mu, just quit.
  1331. select {
  1332. case <-cs.abort:
  1333. return cs.abortErr
  1334. case <-ctx.Done():
  1335. return ctx.Err()
  1336. case <-cs.reqCancel:
  1337. return errRequestCanceled
  1338. default:
  1339. }
  1340. // Encode headers.
  1341. //
  1342. // we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,} (DATA is
  1343. // sent by writeRequestBody below, along with any Trailers,
  1344. // again in form HEADERS{1}, CONTINUATION{0,})
  1345. trailers, err := commaSeparatedTrailers(req)
  1346. if err != nil {
  1347. return err
  1348. }
  1349. hasTrailers := trailers != ""
  1350. contentLen := actualContentLength(req)
  1351. hasBody := contentLen != 0
  1352. hdrs, err := cc.encodeHeaders(req, cs.requestedGzip, trailers, contentLen)
  1353. if err != nil {
  1354. return err
  1355. }
  1356. // Write the request.
  1357. endStream := !hasBody && !hasTrailers
  1358. cs.sentHeaders = true
  1359. err = cc.writeHeaders(cs.ID, endStream, int(cc.maxFrameSize), hdrs)
  1360. traceWroteHeaders(cs.trace)
  1361. return err
  1362. }
  1363. // cleanupWriteRequest performs post-request tasks.
  1364. //
  1365. // If err (the result of writeRequest) is non-nil and the stream is not closed,
  1366. // cleanupWriteRequest will send a reset to the peer.
  1367. func (cs *clientStream) cleanupWriteRequest(err error) {
  1368. cc := cs.cc
  1369. if cs.ID == 0 {
  1370. // We were canceled before creating the stream, so return our reservation.
  1371. cc.decrStreamReservations()
  1372. }
  1373. // TODO: write h12Compare test showing whether
  1374. // Request.Body is closed by the Transport,
  1375. // and in multiple cases: server replies <=299 and >299
  1376. // while still writing request body
  1377. cc.mu.Lock()
  1378. mustCloseBody := false
  1379. if cs.reqBody != nil && cs.reqBodyClosed == nil {
  1380. mustCloseBody = true
  1381. cs.reqBodyClosed = make(chan struct{})
  1382. }
  1383. bodyClosed := cs.reqBodyClosed
  1384. cc.mu.Unlock()
  1385. if mustCloseBody {
  1386. cs.reqBody.Close()
  1387. close(bodyClosed)
  1388. }
  1389. if bodyClosed != nil {
  1390. <-bodyClosed
  1391. }
  1392. if err != nil && cs.sentEndStream {
  1393. // If the connection is closed immediately after the response is read,
  1394. // we may be aborted before finishing up here. If the stream was closed
  1395. // cleanly on both sides, there is no error.
  1396. select {
  1397. case <-cs.peerClosed:
  1398. err = nil
  1399. default:
  1400. }
  1401. }
  1402. if err != nil {
  1403. cs.abortStream(err) // possibly redundant, but harmless
  1404. if cs.sentHeaders {
  1405. if se, ok := err.(StreamError); ok {
  1406. if se.Cause != errFromPeer {
  1407. cc.writeStreamReset(cs.ID, se.Code, err)
  1408. }
  1409. } else {
  1410. cc.writeStreamReset(cs.ID, ErrCodeCancel, err)
  1411. }
  1412. }
  1413. cs.bufPipe.CloseWithError(err) // no-op if already closed
  1414. } else {
  1415. if cs.sentHeaders && !cs.sentEndStream {
  1416. cc.writeStreamReset(cs.ID, ErrCodeNo, nil)
  1417. }
  1418. cs.bufPipe.CloseWithError(errRequestCanceled)
  1419. }
  1420. if cs.ID != 0 {
  1421. cc.forgetStreamID(cs.ID)
  1422. }
  1423. cc.wmu.Lock()
  1424. werr := cc.werr
  1425. cc.wmu.Unlock()
  1426. if werr != nil {
  1427. cc.Close()
  1428. }
  1429. close(cs.donec)
  1430. }
  1431. // awaitOpenSlotForStreamLocked waits until len(streams) < maxConcurrentStreams.
  1432. // Must hold cc.mu.
  1433. func (cc *ClientConn) awaitOpenSlotForStreamLocked(cs *clientStream) error {
  1434. for {
  1435. cc.lastActive = time.Now()
  1436. if cc.closed || !cc.canTakeNewRequestLocked() {
  1437. return errClientConnUnusable
  1438. }
  1439. cc.lastIdle = time.Time{}
  1440. if int64(len(cc.streams)) < int64(cc.maxConcurrentStreams) {
  1441. return nil
  1442. }
  1443. cc.pendingRequests++
  1444. cc.cond.Wait()
  1445. cc.pendingRequests--
  1446. select {
  1447. case <-cs.abort:
  1448. return cs.abortErr
  1449. default:
  1450. }
  1451. }
  1452. }
  1453. // requires cc.wmu be held
  1454. func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, maxFrameSize int, hdrs []byte) error {
  1455. first := true // first frame written (HEADERS is first, then CONTINUATION)
  1456. for len(hdrs) > 0 && cc.werr == nil {
  1457. chunk := hdrs
  1458. if len(chunk) > maxFrameSize {
  1459. chunk = chunk[:maxFrameSize]
  1460. }
  1461. hdrs = hdrs[len(chunk):]
  1462. endHeaders := len(hdrs) == 0
  1463. if first {
  1464. cc.fr.WriteHeaders(HeadersFrameParam{
  1465. StreamID: streamID,
  1466. BlockFragment: chunk,
  1467. EndStream: endStream,
  1468. EndHeaders: endHeaders,
  1469. })
  1470. first = false
  1471. } else {
  1472. cc.fr.WriteContinuation(streamID, endHeaders, chunk)
  1473. }
  1474. }
  1475. cc.bw.Flush()
  1476. return cc.werr
  1477. }
  1478. // internal error values; they don't escape to callers
  1479. var (
  1480. // abort request body write; don't send cancel
  1481. errStopReqBodyWrite = errors.New("http2: aborting request body write")
  1482. // abort request body write, but send stream reset of cancel.
  1483. errStopReqBodyWriteAndCancel = errors.New("http2: canceling request")
  1484. errReqBodyTooLong = errors.New("http2: request body larger than specified content length")
  1485. )
  1486. // frameScratchBufferLen returns the length of a buffer to use for
  1487. // outgoing request bodies to read/write to/from.
  1488. //
  1489. // It returns max(1, min(peer's advertised max frame size,
  1490. // Request.ContentLength+1, 512KB)).
  1491. func (cs *clientStream) frameScratchBufferLen(maxFrameSize int) int {
  1492. const max = 512 << 10
  1493. n := int64(maxFrameSize)
  1494. if n > max {
  1495. n = max
  1496. }
  1497. if cl := cs.reqBodyContentLength; cl != -1 && cl+1 < n {
  1498. // Add an extra byte past the declared content-length to
  1499. // give the caller's Request.Body io.Reader a chance to
  1500. // give us more bytes than they declared, so we can catch it
  1501. // early.
  1502. n = cl + 1
  1503. }
  1504. if n < 1 {
  1505. return 1
  1506. }
  1507. return int(n) // doesn't truncate; max is 512K
  1508. }
  1509. // Seven bufPools manage different frame sizes. This helps to avoid scenarios where long-running
  1510. // streaming requests using small frame sizes occupy large buffers initially allocated for prior
  1511. // requests needing big buffers. The size ranges are as follows:
  1512. // {0 KB, 16 KB], {16 KB, 32 KB], {32 KB, 64 KB], {64 KB, 128 KB], {128 KB, 256 KB],
  1513. // {256 KB, 512 KB], {512 KB, infinity}
  1514. // In practice, the maximum scratch buffer size should not exceed 512 KB due to
  1515. // frameScratchBufferLen(maxFrameSize), thus the "infinity pool" should never be used.
  1516. // It exists mainly as a safety measure, for potential future increases in max buffer size.
  1517. var bufPools [7]sync.Pool // of *[]byte
  1518. func bufPoolIndex(size int) int {
  1519. if size <= 16384 {
  1520. return 0
  1521. }
  1522. size -= 1
  1523. bits := bits.Len(uint(size))
  1524. index := bits - 14
  1525. if index >= len(bufPools) {
  1526. return len(bufPools) - 1
  1527. }
  1528. return index
  1529. }
  1530. func (cs *clientStream) writeRequestBody(req *http.Request) (err error) {
  1531. cc := cs.cc
  1532. body := cs.reqBody
  1533. sentEnd := false // whether we sent the final DATA frame w/ END_STREAM
  1534. hasTrailers := req.Trailer != nil
  1535. remainLen := cs.reqBodyContentLength
  1536. hasContentLen := remainLen != -1
  1537. cc.mu.Lock()
  1538. maxFrameSize := int(cc.maxFrameSize)
  1539. cc.mu.Unlock()
  1540. // Scratch buffer for reading into & writing from.
  1541. scratchLen := cs.frameScratchBufferLen(maxFrameSize)
  1542. var buf []byte
  1543. index := bufPoolIndex(scratchLen)
  1544. if bp, ok := bufPools[index].Get().(*[]byte); ok && len(*bp) >= scratchLen {
  1545. defer bufPools[index].Put(bp)
  1546. buf = *bp
  1547. } else {
  1548. buf = make([]byte, scratchLen)
  1549. defer bufPools[index].Put(&buf)
  1550. }
  1551. var sawEOF bool
  1552. for !sawEOF {
  1553. n, err := body.Read(buf)
  1554. if hasContentLen {
  1555. remainLen -= int64(n)
  1556. if remainLen == 0 && err == nil {
  1557. // The request body's Content-Length was predeclared and
  1558. // we just finished reading it all, but the underlying io.Reader
  1559. // returned the final chunk with a nil error (which is one of
  1560. // the two valid things a Reader can do at EOF). Because we'd prefer
  1561. // to send the END_STREAM bit early, double-check that we're actually
  1562. // at EOF. Subsequent reads should return (0, EOF) at this point.
  1563. // If either value is different, we return an error in one of two ways below.
  1564. var scratch [1]byte
  1565. var n1 int
  1566. n1, err = body.Read(scratch[:])
  1567. remainLen -= int64(n1)
  1568. }
  1569. if remainLen < 0 {
  1570. err = errReqBodyTooLong
  1571. return err
  1572. }
  1573. }
  1574. if err != nil {
  1575. cc.mu.Lock()
  1576. bodyClosed := cs.reqBodyClosed != nil
  1577. cc.mu.Unlock()
  1578. switch {
  1579. case bodyClosed:
  1580. return errStopReqBodyWrite
  1581. case err == io.EOF:
  1582. sawEOF = true
  1583. err = nil
  1584. default:
  1585. return err
  1586. }
  1587. }
  1588. remain := buf[:n]
  1589. for len(remain) > 0 && err == nil {
  1590. var allowed int32
  1591. allowed, err = cs.awaitFlowControl(len(remain))
  1592. if err != nil {
  1593. return err
  1594. }
  1595. cc.wmu.Lock()
  1596. data := remain[:allowed]
  1597. remain = remain[allowed:]
  1598. sentEnd = sawEOF && len(remain) == 0 && !hasTrailers
  1599. err = cc.fr.WriteData(cs.ID, sentEnd, data)
  1600. if err == nil {
  1601. // TODO(bradfitz): this flush is for latency, not bandwidth.
  1602. // Most requests won't need this. Make this opt-in or
  1603. // opt-out? Use some heuristic on the body type? Nagel-like
  1604. // timers? Based on 'n'? Only last chunk of this for loop,
  1605. // unless flow control tokens are low? For now, always.
  1606. // If we change this, see comment below.
  1607. err = cc.bw.Flush()
  1608. }
  1609. cc.wmu.Unlock()
  1610. }
  1611. if err != nil {
  1612. return err
  1613. }
  1614. }
  1615. if sentEnd {
  1616. // Already sent END_STREAM (which implies we have no
  1617. // trailers) and flushed, because currently all
  1618. // WriteData frames above get a flush. So we're done.
  1619. return nil
  1620. }
  1621. // Since the RoundTrip contract permits the caller to "mutate or reuse"
  1622. // a request after the Response's Body is closed, verify that this hasn't
  1623. // happened before accessing the trailers.
  1624. cc.mu.Lock()
  1625. trailer := req.Trailer
  1626. err = cs.abortErr
  1627. cc.mu.Unlock()
  1628. if err != nil {
  1629. return err
  1630. }
  1631. cc.wmu.Lock()
  1632. defer cc.wmu.Unlock()
  1633. var trls []byte
  1634. if len(trailer) > 0 {
  1635. trls, err = cc.encodeTrailers(trailer)
  1636. if err != nil {
  1637. return err
  1638. }
  1639. }
  1640. // Two ways to send END_STREAM: either with trailers, or
  1641. // with an empty DATA frame.
  1642. if len(trls) > 0 {
  1643. err = cc.writeHeaders(cs.ID, true, maxFrameSize, trls)
  1644. } else {
  1645. err = cc.fr.WriteData(cs.ID, true, nil)
  1646. }
  1647. if ferr := cc.bw.Flush(); ferr != nil && err == nil {
  1648. err = ferr
  1649. }
  1650. return err
  1651. }
  1652. // awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
  1653. // control tokens from the server.
  1654. // It returns either the non-zero number of tokens taken or an error
  1655. // if the stream is dead.
  1656. func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
  1657. cc := cs.cc
  1658. ctx := cs.ctx
  1659. cc.mu.Lock()
  1660. defer cc.mu.Unlock()
  1661. for {
  1662. if cc.closed {
  1663. return 0, errClientConnClosed
  1664. }
  1665. if cs.reqBodyClosed != nil {
  1666. return 0, errStopReqBodyWrite
  1667. }
  1668. select {
  1669. case <-cs.abort:
  1670. return 0, cs.abortErr
  1671. case <-ctx.Done():
  1672. return 0, ctx.Err()
  1673. case <-cs.reqCancel:
  1674. return 0, errRequestCanceled
  1675. default:
  1676. }
  1677. if a := cs.flow.available(); a > 0 {
  1678. take := a
  1679. if int(take) > maxBytes {
  1680. take = int32(maxBytes) // can't truncate int; take is int32
  1681. }
  1682. if take > int32(cc.maxFrameSize) {
  1683. take = int32(cc.maxFrameSize)
  1684. }
  1685. cs.flow.take(take)
  1686. return take, nil
  1687. }
  1688. cc.cond.Wait()
  1689. }
  1690. }
  1691. var errNilRequestURL = errors.New("http2: Request.URI is nil")
  1692. // requires cc.wmu be held.
  1693. func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) {
  1694. cc.hbuf.Reset()
  1695. if req.URL == nil {
  1696. return nil, errNilRequestURL
  1697. }
  1698. host := req.Host
  1699. if host == "" {
  1700. host = req.URL.Host
  1701. }
  1702. host, err := httpguts.PunycodeHostPort(host)
  1703. if err != nil {
  1704. return nil, err
  1705. }
  1706. if !httpguts.ValidHostHeader(host) {
  1707. return nil, errors.New("http2: invalid Host header")
  1708. }
  1709. var path string
  1710. if req.Method != "CONNECT" {
  1711. path = req.URL.RequestURI()
  1712. if !validPseudoPath(path) {
  1713. orig := path
  1714. path = strings.TrimPrefix(path, req.URL.Scheme+"://"+host)
  1715. if !validPseudoPath(path) {
  1716. if req.URL.Opaque != "" {
  1717. return nil, fmt.Errorf("invalid request :path %q from URL.Opaque = %q", orig, req.URL.Opaque)
  1718. } else {
  1719. return nil, fmt.Errorf("invalid request :path %q", orig)
  1720. }
  1721. }
  1722. }
  1723. }
  1724. // Check for any invalid headers and return an error before we
  1725. // potentially pollute our hpack state. (We want to be able to
  1726. // continue to reuse the hpack encoder for future requests)
  1727. for k, vv := range req.Header {
  1728. if !httpguts.ValidHeaderFieldName(k) {
  1729. return nil, fmt.Errorf("invalid HTTP header name %q", k)
  1730. }
  1731. for _, v := range vv {
  1732. if !httpguts.ValidHeaderFieldValue(v) {
  1733. // Don't include the value in the error, because it may be sensitive.
  1734. return nil, fmt.Errorf("invalid HTTP header value for header %q", k)
  1735. }
  1736. }
  1737. }
  1738. enumerateHeaders := func(f func(name, value string)) {
  1739. // 8.1.2.3 Request Pseudo-Header Fields
  1740. // The :path pseudo-header field includes the path and query parts of the
  1741. // target URI (the path-absolute production and optionally a '?' character
  1742. // followed by the query production, see Sections 3.3 and 3.4 of
  1743. // [RFC3986]).
  1744. f(":authority", host)
  1745. m := req.Method
  1746. if m == "" {
  1747. m = http.MethodGet
  1748. }
  1749. f(":method", m)
  1750. if req.Method != "CONNECT" {
  1751. f(":path", path)
  1752. f(":scheme", req.URL.Scheme)
  1753. }
  1754. if trailers != "" {
  1755. f("trailer", trailers)
  1756. }
  1757. var didUA bool
  1758. for k, vv := range req.Header {
  1759. if asciiEqualFold(k, "host") || asciiEqualFold(k, "content-length") {
  1760. // Host is :authority, already sent.
  1761. // Content-Length is automatic, set below.
  1762. continue
  1763. } else if asciiEqualFold(k, "connection") ||
  1764. asciiEqualFold(k, "proxy-connection") ||
  1765. asciiEqualFold(k, "transfer-encoding") ||
  1766. asciiEqualFold(k, "upgrade") ||
  1767. asciiEqualFold(k, "keep-alive") {
  1768. // Per 8.1.2.2 Connection-Specific Header
  1769. // Fields, don't send connection-specific
  1770. // fields. We have already checked if any
  1771. // are error-worthy so just ignore the rest.
  1772. continue
  1773. } else if asciiEqualFold(k, "user-agent") {
  1774. // Match Go's http1 behavior: at most one
  1775. // User-Agent. If set to nil or empty string,
  1776. // then omit it. Otherwise if not mentioned,
  1777. // include the default (below).
  1778. didUA = true
  1779. if len(vv) < 1 {
  1780. continue
  1781. }
  1782. vv = vv[:1]
  1783. if vv[0] == "" {
  1784. continue
  1785. }
  1786. } else if asciiEqualFold(k, "cookie") {
  1787. // Per 8.1.2.5 To allow for better compression efficiency, the
  1788. // Cookie header field MAY be split into separate header fields,
  1789. // each with one or more cookie-pairs.
  1790. for _, v := range vv {
  1791. for {
  1792. p := strings.IndexByte(v, ';')
  1793. if p < 0 {
  1794. break
  1795. }
  1796. f("cookie", v[:p])
  1797. p++
  1798. // strip space after semicolon if any.
  1799. for p+1 <= len(v) && v[p] == ' ' {
  1800. p++
  1801. }
  1802. v = v[p:]
  1803. }
  1804. if len(v) > 0 {
  1805. f("cookie", v)
  1806. }
  1807. }
  1808. continue
  1809. }
  1810. for _, v := range vv {
  1811. f(k, v)
  1812. }
  1813. }
  1814. if shouldSendReqContentLength(req.Method, contentLength) {
  1815. f("content-length", strconv.FormatInt(contentLength, 10))
  1816. }
  1817. if addGzipHeader {
  1818. f("accept-encoding", "gzip")
  1819. }
  1820. if !didUA {
  1821. f("user-agent", defaultUserAgent)
  1822. }
  1823. }
  1824. // Do a first pass over the headers counting bytes to ensure
  1825. // we don't exceed cc.peerMaxHeaderListSize. This is done as a
  1826. // separate pass before encoding the headers to prevent
  1827. // modifying the hpack state.
  1828. hlSize := uint64(0)
  1829. enumerateHeaders(func(name, value string) {
  1830. hf := hpack.HeaderField{Name: name, Value: value}
  1831. hlSize += uint64(hf.Size())
  1832. })
  1833. if hlSize > cc.peerMaxHeaderListSize {
  1834. return nil, errRequestHeaderListSize
  1835. }
  1836. trace := httptrace.ContextClientTrace(req.Context())
  1837. traceHeaders := traceHasWroteHeaderField(trace)
  1838. // Header list size is ok. Write the headers.
  1839. enumerateHeaders(func(name, value string) {
  1840. name, ascii := lowerHeader(name)
  1841. if !ascii {
  1842. // Skip writing invalid headers. Per RFC 7540, Section 8.1.2, header
  1843. // field names have to be ASCII characters (just as in HTTP/1.x).
  1844. return
  1845. }
  1846. cc.writeHeader(name, value)
  1847. if traceHeaders {
  1848. traceWroteHeaderField(trace, name, value)
  1849. }
  1850. })
  1851. return cc.hbuf.Bytes(), nil
  1852. }
  1853. // shouldSendReqContentLength reports whether the http2.Transport should send
  1854. // a "content-length" request header. This logic is basically a copy of the net/http
  1855. // transferWriter.shouldSendContentLength.
  1856. // The contentLength is the corrected contentLength (so 0 means actually 0, not unknown).
  1857. // -1 means unknown.
  1858. func shouldSendReqContentLength(method string, contentLength int64) bool {
  1859. if contentLength > 0 {
  1860. return true
  1861. }
  1862. if contentLength < 0 {
  1863. return false
  1864. }
  1865. // For zero bodies, whether we send a content-length depends on the method.
  1866. // It also kinda doesn't matter for http2 either way, with END_STREAM.
  1867. switch method {
  1868. case "POST", "PUT", "PATCH":
  1869. return true
  1870. default:
  1871. return false
  1872. }
  1873. }
  1874. // requires cc.wmu be held.
  1875. func (cc *ClientConn) encodeTrailers(trailer http.Header) ([]byte, error) {
  1876. cc.hbuf.Reset()
  1877. hlSize := uint64(0)
  1878. for k, vv := range trailer {
  1879. for _, v := range vv {
  1880. hf := hpack.HeaderField{Name: k, Value: v}
  1881. hlSize += uint64(hf.Size())
  1882. }
  1883. }
  1884. if hlSize > cc.peerMaxHeaderListSize {
  1885. return nil, errRequestHeaderListSize
  1886. }
  1887. for k, vv := range trailer {
  1888. lowKey, ascii := lowerHeader(k)
  1889. if !ascii {
  1890. // Skip writing invalid headers. Per RFC 7540, Section 8.1.2, header
  1891. // field names have to be ASCII characters (just as in HTTP/1.x).
  1892. continue
  1893. }
  1894. // Transfer-Encoding, etc.. have already been filtered at the
  1895. // start of RoundTrip
  1896. for _, v := range vv {
  1897. cc.writeHeader(lowKey, v)
  1898. }
  1899. }
  1900. return cc.hbuf.Bytes(), nil
  1901. }
  1902. func (cc *ClientConn) writeHeader(name, value string) {
  1903. if VerboseLogs {
  1904. log.Printf("http2: Transport encoding header %q = %q", name, value)
  1905. }
  1906. cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
  1907. }
  1908. type resAndError struct {
  1909. _ incomparable
  1910. res *http.Response
  1911. err error
  1912. }
  1913. // requires cc.mu be held.
  1914. func (cc *ClientConn) addStreamLocked(cs *clientStream) {
  1915. cs.flow.add(int32(cc.initialWindowSize))
  1916. cs.flow.setConnFlow(&cc.flow)
  1917. cs.inflow.init(transportDefaultStreamFlow)
  1918. cs.ID = cc.nextStreamID
  1919. cc.nextStreamID += 2
  1920. cc.streams[cs.ID] = cs
  1921. if cs.ID == 0 {
  1922. panic("assigned stream ID 0")
  1923. }
  1924. }
  1925. func (cc *ClientConn) forgetStreamID(id uint32) {
  1926. cc.mu.Lock()
  1927. slen := len(cc.streams)
  1928. delete(cc.streams, id)
  1929. if len(cc.streams) != slen-1 {
  1930. panic("forgetting unknown stream id")
  1931. }
  1932. cc.lastActive = time.Now()
  1933. if len(cc.streams) == 0 && cc.idleTimer != nil {
  1934. cc.idleTimer.Reset(cc.idleTimeout)
  1935. cc.lastIdle = time.Now()
  1936. }
  1937. // Wake up writeRequestBody via clientStream.awaitFlowControl and
  1938. // wake up RoundTrip if there is a pending request.
  1939. cc.cond.Broadcast()
  1940. closeOnIdle := cc.singleUse || cc.doNotReuse || cc.t.disableKeepAlives() || cc.goAway != nil
  1941. if closeOnIdle && cc.streamsReserved == 0 && len(cc.streams) == 0 {
  1942. if VerboseLogs {
  1943. cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, cc.nextStreamID-2)
  1944. }
  1945. cc.closed = true
  1946. defer cc.closeConn()
  1947. }
  1948. cc.mu.Unlock()
  1949. }
  1950. // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.
  1951. type clientConnReadLoop struct {
  1952. _ incomparable
  1953. cc *ClientConn
  1954. }
  1955. // readLoop runs in its own goroutine and reads and dispatches frames.
  1956. func (cc *ClientConn) readLoop() {
  1957. rl := &clientConnReadLoop{cc: cc}
  1958. defer rl.cleanup()
  1959. cc.readerErr = rl.run()
  1960. if ce, ok := cc.readerErr.(ConnectionError); ok {
  1961. cc.wmu.Lock()
  1962. cc.fr.WriteGoAway(0, ErrCode(ce), nil)
  1963. cc.wmu.Unlock()
  1964. }
  1965. }
  1966. // GoAwayError is returned by the Transport when the server closes the
  1967. // TCP connection after sending a GOAWAY frame.
  1968. type GoAwayError struct {
  1969. LastStreamID uint32
  1970. ErrCode ErrCode
  1971. DebugData string
  1972. }
  1973. func (e GoAwayError) Error() string {
  1974. return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q",
  1975. e.LastStreamID, e.ErrCode, e.DebugData)
  1976. }
  1977. func isEOFOrNetReadError(err error) bool {
  1978. if err == io.EOF {
  1979. return true
  1980. }
  1981. ne, ok := err.(*net.OpError)
  1982. return ok && ne.Op == "read"
  1983. }
  1984. func (rl *clientConnReadLoop) cleanup() {
  1985. cc := rl.cc
  1986. cc.t.connPool().MarkDead(cc)
  1987. defer cc.closeConn()
  1988. defer close(cc.readerDone)
  1989. if cc.idleTimer != nil {
  1990. cc.idleTimer.Stop()
  1991. }
  1992. // Close any response bodies if the server closes prematurely.
  1993. // TODO: also do this if we've written the headers but not
  1994. // gotten a response yet.
  1995. err := cc.readerErr
  1996. cc.mu.Lock()
  1997. if cc.goAway != nil && isEOFOrNetReadError(err) {
  1998. err = GoAwayError{
  1999. LastStreamID: cc.goAway.LastStreamID,
  2000. ErrCode: cc.goAway.ErrCode,
  2001. DebugData: cc.goAwayDebug,
  2002. }
  2003. } else if err == io.EOF {
  2004. err = io.ErrUnexpectedEOF
  2005. }
  2006. cc.closed = true
  2007. for _, cs := range cc.streams {
  2008. select {
  2009. case <-cs.peerClosed:
  2010. // The server closed the stream before closing the conn,
  2011. // so no need to interrupt it.
  2012. default:
  2013. cs.abortStreamLocked(err)
  2014. }
  2015. }
  2016. cc.cond.Broadcast()
  2017. cc.mu.Unlock()
  2018. }
  2019. // countReadFrameError calls Transport.CountError with a string
  2020. // representing err.
  2021. func (cc *ClientConn) countReadFrameError(err error) {
  2022. f := cc.t.CountError
  2023. if f == nil || err == nil {
  2024. return
  2025. }
  2026. if ce, ok := err.(ConnectionError); ok {
  2027. errCode := ErrCode(ce)
  2028. f(fmt.Sprintf("read_frame_conn_error_%s", errCode.stringToken()))
  2029. return
  2030. }
  2031. if errors.Is(err, io.EOF) {
  2032. f("read_frame_eof")
  2033. return
  2034. }
  2035. if errors.Is(err, io.ErrUnexpectedEOF) {
  2036. f("read_frame_unexpected_eof")
  2037. return
  2038. }
  2039. if errors.Is(err, ErrFrameTooLarge) {
  2040. f("read_frame_too_large")
  2041. return
  2042. }
  2043. f("read_frame_other")
  2044. }
  2045. func (rl *clientConnReadLoop) run() error {
  2046. cc := rl.cc
  2047. gotSettings := false
  2048. readIdleTimeout := cc.t.ReadIdleTimeout
  2049. var t *time.Timer
  2050. if readIdleTimeout != 0 {
  2051. t = time.AfterFunc(readIdleTimeout, cc.healthCheck)
  2052. defer t.Stop()
  2053. }
  2054. for {
  2055. f, err := cc.fr.ReadFrame()
  2056. if t != nil {
  2057. t.Reset(readIdleTimeout)
  2058. }
  2059. if err != nil {
  2060. cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err)
  2061. }
  2062. if se, ok := err.(StreamError); ok {
  2063. if cs := rl.streamByID(se.StreamID); cs != nil {
  2064. if se.Cause == nil {
  2065. se.Cause = cc.fr.errDetail
  2066. }
  2067. rl.endStreamError(cs, se)
  2068. }
  2069. continue
  2070. } else if err != nil {
  2071. cc.countReadFrameError(err)
  2072. return err
  2073. }
  2074. if VerboseLogs {
  2075. cc.vlogf("http2: Transport received %s", summarizeFrame(f))
  2076. }
  2077. if !gotSettings {
  2078. if _, ok := f.(*SettingsFrame); !ok {
  2079. cc.logf("protocol error: received %T before a SETTINGS frame", f)
  2080. return ConnectionError(ErrCodeProtocol)
  2081. }
  2082. gotSettings = true
  2083. }
  2084. switch f := f.(type) {
  2085. case *MetaHeadersFrame:
  2086. err = rl.processHeaders(f)
  2087. case *DataFrame:
  2088. err = rl.processData(f)
  2089. case *GoAwayFrame:
  2090. err = rl.processGoAway(f)
  2091. case *RSTStreamFrame:
  2092. err = rl.processResetStream(f)
  2093. case *SettingsFrame:
  2094. err = rl.processSettings(f)
  2095. case *PushPromiseFrame:
  2096. err = rl.processPushPromise(f)
  2097. case *WindowUpdateFrame:
  2098. err = rl.processWindowUpdate(f)
  2099. case *PingFrame:
  2100. err = rl.processPing(f)
  2101. default:
  2102. cc.logf("Transport: unhandled response frame type %T", f)
  2103. }
  2104. if err != nil {
  2105. if VerboseLogs {
  2106. cc.vlogf("http2: Transport conn %p received error from processing frame %v: %v", cc, summarizeFrame(f), err)
  2107. }
  2108. return err
  2109. }
  2110. }
  2111. }
  2112. func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error {
  2113. cs := rl.streamByID(f.StreamID)
  2114. if cs == nil {
  2115. // We'd get here if we canceled a request while the
  2116. // server had its response still in flight. So if this
  2117. // was just something we canceled, ignore it.
  2118. return nil
  2119. }
  2120. if cs.readClosed {
  2121. rl.endStreamError(cs, StreamError{
  2122. StreamID: f.StreamID,
  2123. Code: ErrCodeProtocol,
  2124. Cause: errors.New("protocol error: headers after END_STREAM"),
  2125. })
  2126. return nil
  2127. }
  2128. if !cs.firstByte {
  2129. if cs.trace != nil {
  2130. // TODO(bradfitz): move first response byte earlier,
  2131. // when we first read the 9 byte header, not waiting
  2132. // until all the HEADERS+CONTINUATION frames have been
  2133. // merged. This works for now.
  2134. traceFirstResponseByte(cs.trace)
  2135. }
  2136. cs.firstByte = true
  2137. }
  2138. if !cs.pastHeaders {
  2139. cs.pastHeaders = true
  2140. } else {
  2141. return rl.processTrailers(cs, f)
  2142. }
  2143. res, err := rl.handleResponse(cs, f)
  2144. if err != nil {
  2145. if _, ok := err.(ConnectionError); ok {
  2146. return err
  2147. }
  2148. // Any other error type is a stream error.
  2149. rl.endStreamError(cs, StreamError{
  2150. StreamID: f.StreamID,
  2151. Code: ErrCodeProtocol,
  2152. Cause: err,
  2153. })
  2154. return nil // return nil from process* funcs to keep conn alive
  2155. }
  2156. if res == nil {
  2157. // (nil, nil) special case. See handleResponse docs.
  2158. return nil
  2159. }
  2160. cs.resTrailer = &res.Trailer
  2161. cs.res = res
  2162. close(cs.respHeaderRecv)
  2163. if f.StreamEnded() {
  2164. rl.endStream(cs)
  2165. }
  2166. return nil
  2167. }
  2168. // may return error types nil, or ConnectionError. Any other error value
  2169. // is a StreamError of type ErrCodeProtocol. The returned error in that case
  2170. // is the detail.
  2171. //
  2172. // As a special case, handleResponse may return (nil, nil) to skip the
  2173. // frame (currently only used for 1xx responses).
  2174. func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFrame) (*http.Response, error) {
  2175. if f.Truncated {
  2176. return nil, errResponseHeaderListSize
  2177. }
  2178. status := f.PseudoValue("status")
  2179. if status == "" {
  2180. return nil, errors.New("malformed response from server: missing status pseudo header")
  2181. }
  2182. statusCode, err := strconv.Atoi(status)
  2183. if err != nil {
  2184. return nil, errors.New("malformed response from server: malformed non-numeric status pseudo header")
  2185. }
  2186. regularFields := f.RegularFields()
  2187. strs := make([]string, len(regularFields))
  2188. header := make(http.Header, len(regularFields))
  2189. res := &http.Response{
  2190. Proto: "HTTP/2.0",
  2191. ProtoMajor: 2,
  2192. Header: header,
  2193. StatusCode: statusCode,
  2194. Status: status + " " + http.StatusText(statusCode),
  2195. }
  2196. for _, hf := range regularFields {
  2197. key := canonicalHeader(hf.Name)
  2198. if key == "Trailer" {
  2199. t := res.Trailer
  2200. if t == nil {
  2201. t = make(http.Header)
  2202. res.Trailer = t
  2203. }
  2204. foreachHeaderElement(hf.Value, func(v string) {
  2205. t[canonicalHeader(v)] = nil
  2206. })
  2207. } else {
  2208. vv := header[key]
  2209. if vv == nil && len(strs) > 0 {
  2210. // More than likely this will be a single-element key.
  2211. // Most headers aren't multi-valued.
  2212. // Set the capacity on strs[0] to 1, so any future append
  2213. // won't extend the slice into the other strings.
  2214. vv, strs = strs[:1:1], strs[1:]
  2215. vv[0] = hf.Value
  2216. header[key] = vv
  2217. } else {
  2218. header[key] = append(vv, hf.Value)
  2219. }
  2220. }
  2221. }
  2222. if statusCode >= 100 && statusCode <= 199 {
  2223. if f.StreamEnded() {
  2224. return nil, errors.New("1xx informational response with END_STREAM flag")
  2225. }
  2226. cs.num1xx++
  2227. const max1xxResponses = 5 // arbitrary bound on number of informational responses, same as net/http
  2228. if cs.num1xx > max1xxResponses {
  2229. return nil, errors.New("http2: too many 1xx informational responses")
  2230. }
  2231. if fn := cs.get1xxTraceFunc(); fn != nil {
  2232. if err := fn(statusCode, textproto.MIMEHeader(header)); err != nil {
  2233. return nil, err
  2234. }
  2235. }
  2236. if statusCode == 100 {
  2237. traceGot100Continue(cs.trace)
  2238. select {
  2239. case cs.on100 <- struct{}{}:
  2240. default:
  2241. }
  2242. }
  2243. cs.pastHeaders = false // do it all again
  2244. return nil, nil
  2245. }
  2246. res.ContentLength = -1
  2247. if clens := res.Header["Content-Length"]; len(clens) == 1 {
  2248. if cl, err := strconv.ParseUint(clens[0], 10, 63); err == nil {
  2249. res.ContentLength = int64(cl)
  2250. } else {
  2251. // TODO: care? unlike http/1, it won't mess up our framing, so it's
  2252. // more safe smuggling-wise to ignore.
  2253. }
  2254. } else if len(clens) > 1 {
  2255. // TODO: care? unlike http/1, it won't mess up our framing, so it's
  2256. // more safe smuggling-wise to ignore.
  2257. } else if f.StreamEnded() && !cs.isHead {
  2258. res.ContentLength = 0
  2259. }
  2260. if cs.isHead {
  2261. res.Body = noBody
  2262. return res, nil
  2263. }
  2264. if f.StreamEnded() {
  2265. if res.ContentLength > 0 {
  2266. res.Body = missingBody{}
  2267. } else {
  2268. res.Body = noBody
  2269. }
  2270. return res, nil
  2271. }
  2272. cs.bufPipe.setBuffer(&dataBuffer{expected: res.ContentLength})
  2273. cs.bytesRemain = res.ContentLength
  2274. res.Body = transportResponseBody{cs}
  2275. if cs.requestedGzip && asciiEqualFold(res.Header.Get("Content-Encoding"), "gzip") {
  2276. res.Header.Del("Content-Encoding")
  2277. res.Header.Del("Content-Length")
  2278. res.ContentLength = -1
  2279. res.Body = &gzipReader{body: res.Body}
  2280. res.Uncompressed = true
  2281. }
  2282. return res, nil
  2283. }
  2284. func (rl *clientConnReadLoop) processTrailers(cs *clientStream, f *MetaHeadersFrame) error {
  2285. if cs.pastTrailers {
  2286. // Too many HEADERS frames for this stream.
  2287. return ConnectionError(ErrCodeProtocol)
  2288. }
  2289. cs.pastTrailers = true
  2290. if !f.StreamEnded() {
  2291. // We expect that any headers for trailers also
  2292. // has END_STREAM.
  2293. return ConnectionError(ErrCodeProtocol)
  2294. }
  2295. if len(f.PseudoFields()) > 0 {
  2296. // No pseudo header fields are defined for trailers.
  2297. // TODO: ConnectionError might be overly harsh? Check.
  2298. return ConnectionError(ErrCodeProtocol)
  2299. }
  2300. trailer := make(http.Header)
  2301. for _, hf := range f.RegularFields() {
  2302. key := canonicalHeader(hf.Name)
  2303. trailer[key] = append(trailer[key], hf.Value)
  2304. }
  2305. cs.trailer = trailer
  2306. rl.endStream(cs)
  2307. return nil
  2308. }
  2309. // transportResponseBody is the concrete type of Transport.RoundTrip's
  2310. // Response.Body. It is an io.ReadCloser.
  2311. type transportResponseBody struct {
  2312. cs *clientStream
  2313. }
  2314. func (b transportResponseBody) Read(p []byte) (n int, err error) {
  2315. cs := b.cs
  2316. cc := cs.cc
  2317. if cs.readErr != nil {
  2318. return 0, cs.readErr
  2319. }
  2320. n, err = b.cs.bufPipe.Read(p)
  2321. if cs.bytesRemain != -1 {
  2322. if int64(n) > cs.bytesRemain {
  2323. n = int(cs.bytesRemain)
  2324. if err == nil {
  2325. err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
  2326. cs.abortStream(err)
  2327. }
  2328. cs.readErr = err
  2329. return int(cs.bytesRemain), err
  2330. }
  2331. cs.bytesRemain -= int64(n)
  2332. if err == io.EOF && cs.bytesRemain > 0 {
  2333. err = io.ErrUnexpectedEOF
  2334. cs.readErr = err
  2335. return n, err
  2336. }
  2337. }
  2338. if n == 0 {
  2339. // No flow control tokens to send back.
  2340. return
  2341. }
  2342. cc.mu.Lock()
  2343. connAdd := cc.inflow.add(n)
  2344. var streamAdd int32
  2345. if err == nil { // No need to refresh if the stream is over or failed.
  2346. streamAdd = cs.inflow.add(n)
  2347. }
  2348. cc.mu.Unlock()
  2349. if connAdd != 0 || streamAdd != 0 {
  2350. cc.wmu.Lock()
  2351. defer cc.wmu.Unlock()
  2352. if connAdd != 0 {
  2353. cc.fr.WriteWindowUpdate(0, mustUint31(connAdd))
  2354. }
  2355. if streamAdd != 0 {
  2356. cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd))
  2357. }
  2358. cc.bw.Flush()
  2359. }
  2360. return
  2361. }
  2362. var errClosedResponseBody = errors.New("http2: response body closed")
  2363. func (b transportResponseBody) Close() error {
  2364. cs := b.cs
  2365. cc := cs.cc
  2366. cs.bufPipe.BreakWithError(errClosedResponseBody)
  2367. cs.abortStream(errClosedResponseBody)
  2368. unread := cs.bufPipe.Len()
  2369. if unread > 0 {
  2370. cc.mu.Lock()
  2371. // Return connection-level flow control.
  2372. connAdd := cc.inflow.add(unread)
  2373. cc.mu.Unlock()
  2374. // TODO(dneil): Acquiring this mutex can block indefinitely.
  2375. // Move flow control return to a goroutine?
  2376. cc.wmu.Lock()
  2377. // Return connection-level flow control.
  2378. if connAdd > 0 {
  2379. cc.fr.WriteWindowUpdate(0, uint32(connAdd))
  2380. }
  2381. cc.bw.Flush()
  2382. cc.wmu.Unlock()
  2383. }
  2384. select {
  2385. case <-cs.donec:
  2386. case <-cs.ctx.Done():
  2387. // See golang/go#49366: The net/http package can cancel the
  2388. // request context after the response body is fully read.
  2389. // Don't treat this as an error.
  2390. return nil
  2391. case <-cs.reqCancel:
  2392. return errRequestCanceled
  2393. }
  2394. return nil
  2395. }
  2396. func (rl *clientConnReadLoop) processData(f *DataFrame) error {
  2397. cc := rl.cc
  2398. cs := rl.streamByID(f.StreamID)
  2399. data := f.Data()
  2400. if cs == nil {
  2401. cc.mu.Lock()
  2402. neverSent := cc.nextStreamID
  2403. cc.mu.Unlock()
  2404. if f.StreamID >= neverSent {
  2405. // We never asked for this.
  2406. cc.logf("http2: Transport received unsolicited DATA frame; closing connection")
  2407. return ConnectionError(ErrCodeProtocol)
  2408. }
  2409. // We probably did ask for this, but canceled. Just ignore it.
  2410. // TODO: be stricter here? only silently ignore things which
  2411. // we canceled, but not things which were closed normally
  2412. // by the peer? Tough without accumulating too much state.
  2413. // But at least return their flow control:
  2414. if f.Length > 0 {
  2415. cc.mu.Lock()
  2416. ok := cc.inflow.take(f.Length)
  2417. connAdd := cc.inflow.add(int(f.Length))
  2418. cc.mu.Unlock()
  2419. if !ok {
  2420. return ConnectionError(ErrCodeFlowControl)
  2421. }
  2422. if connAdd > 0 {
  2423. cc.wmu.Lock()
  2424. cc.fr.WriteWindowUpdate(0, uint32(connAdd))
  2425. cc.bw.Flush()
  2426. cc.wmu.Unlock()
  2427. }
  2428. }
  2429. return nil
  2430. }
  2431. if cs.readClosed {
  2432. cc.logf("protocol error: received DATA after END_STREAM")
  2433. rl.endStreamError(cs, StreamError{
  2434. StreamID: f.StreamID,
  2435. Code: ErrCodeProtocol,
  2436. })
  2437. return nil
  2438. }
  2439. if !cs.firstByte {
  2440. cc.logf("protocol error: received DATA before a HEADERS frame")
  2441. rl.endStreamError(cs, StreamError{
  2442. StreamID: f.StreamID,
  2443. Code: ErrCodeProtocol,
  2444. })
  2445. return nil
  2446. }
  2447. if f.Length > 0 {
  2448. if cs.isHead && len(data) > 0 {
  2449. cc.logf("protocol error: received DATA on a HEAD request")
  2450. rl.endStreamError(cs, StreamError{
  2451. StreamID: f.StreamID,
  2452. Code: ErrCodeProtocol,
  2453. })
  2454. return nil
  2455. }
  2456. // Check connection-level flow control.
  2457. cc.mu.Lock()
  2458. if !takeInflows(&cc.inflow, &cs.inflow, f.Length) {
  2459. cc.mu.Unlock()
  2460. return ConnectionError(ErrCodeFlowControl)
  2461. }
  2462. // Return any padded flow control now, since we won't
  2463. // refund it later on body reads.
  2464. var refund int
  2465. if pad := int(f.Length) - len(data); pad > 0 {
  2466. refund += pad
  2467. }
  2468. didReset := false
  2469. var err error
  2470. if len(data) > 0 {
  2471. if _, err = cs.bufPipe.Write(data); err != nil {
  2472. // Return len(data) now if the stream is already closed,
  2473. // since data will never be read.
  2474. didReset = true
  2475. refund += len(data)
  2476. }
  2477. }
  2478. sendConn := cc.inflow.add(refund)
  2479. var sendStream int32
  2480. if !didReset {
  2481. sendStream = cs.inflow.add(refund)
  2482. }
  2483. cc.mu.Unlock()
  2484. if sendConn > 0 || sendStream > 0 {
  2485. cc.wmu.Lock()
  2486. if sendConn > 0 {
  2487. cc.fr.WriteWindowUpdate(0, uint32(sendConn))
  2488. }
  2489. if sendStream > 0 {
  2490. cc.fr.WriteWindowUpdate(cs.ID, uint32(sendStream))
  2491. }
  2492. cc.bw.Flush()
  2493. cc.wmu.Unlock()
  2494. }
  2495. if err != nil {
  2496. rl.endStreamError(cs, err)
  2497. return nil
  2498. }
  2499. }
  2500. if f.StreamEnded() {
  2501. rl.endStream(cs)
  2502. }
  2503. return nil
  2504. }
  2505. func (rl *clientConnReadLoop) endStream(cs *clientStream) {
  2506. // TODO: check that any declared content-length matches, like
  2507. // server.go's (*stream).endStream method.
  2508. if !cs.readClosed {
  2509. cs.readClosed = true
  2510. // Close cs.bufPipe and cs.peerClosed with cc.mu held to avoid a
  2511. // race condition: The caller can read io.EOF from Response.Body
  2512. // and close the body before we close cs.peerClosed, causing
  2513. // cleanupWriteRequest to send a RST_STREAM.
  2514. rl.cc.mu.Lock()
  2515. defer rl.cc.mu.Unlock()
  2516. cs.bufPipe.closeWithErrorAndCode(io.EOF, cs.copyTrailers)
  2517. close(cs.peerClosed)
  2518. }
  2519. }
  2520. func (rl *clientConnReadLoop) endStreamError(cs *clientStream, err error) {
  2521. cs.readAborted = true
  2522. cs.abortStream(err)
  2523. }
  2524. func (rl *clientConnReadLoop) streamByID(id uint32) *clientStream {
  2525. rl.cc.mu.Lock()
  2526. defer rl.cc.mu.Unlock()
  2527. cs := rl.cc.streams[id]
  2528. if cs != nil && !cs.readAborted {
  2529. return cs
  2530. }
  2531. return nil
  2532. }
  2533. func (cs *clientStream) copyTrailers() {
  2534. for k, vv := range cs.trailer {
  2535. t := cs.resTrailer
  2536. if *t == nil {
  2537. *t = make(http.Header)
  2538. }
  2539. (*t)[k] = vv
  2540. }
  2541. }
  2542. func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error {
  2543. cc := rl.cc
  2544. cc.t.connPool().MarkDead(cc)
  2545. if f.ErrCode != 0 {
  2546. // TODO: deal with GOAWAY more. particularly the error code
  2547. cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
  2548. if fn := cc.t.CountError; fn != nil {
  2549. fn("recv_goaway_" + f.ErrCode.stringToken())
  2550. }
  2551. }
  2552. cc.setGoAway(f)
  2553. return nil
  2554. }
  2555. func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error {
  2556. cc := rl.cc
  2557. // Locking both mu and wmu here allows frame encoding to read settings with only wmu held.
  2558. // Acquiring wmu when f.IsAck() is unnecessary, but convenient and mostly harmless.
  2559. cc.wmu.Lock()
  2560. defer cc.wmu.Unlock()
  2561. if err := rl.processSettingsNoWrite(f); err != nil {
  2562. return err
  2563. }
  2564. if !f.IsAck() {
  2565. cc.fr.WriteSettingsAck()
  2566. cc.bw.Flush()
  2567. }
  2568. return nil
  2569. }
  2570. func (rl *clientConnReadLoop) processSettingsNoWrite(f *SettingsFrame) error {
  2571. cc := rl.cc
  2572. cc.mu.Lock()
  2573. defer cc.mu.Unlock()
  2574. if f.IsAck() {
  2575. if cc.wantSettingsAck {
  2576. cc.wantSettingsAck = false
  2577. return nil
  2578. }
  2579. return ConnectionError(ErrCodeProtocol)
  2580. }
  2581. var seenMaxConcurrentStreams bool
  2582. err := f.ForeachSetting(func(s Setting) error {
  2583. switch s.ID {
  2584. case SettingMaxFrameSize:
  2585. cc.maxFrameSize = s.Val
  2586. case SettingMaxConcurrentStreams:
  2587. cc.maxConcurrentStreams = s.Val
  2588. seenMaxConcurrentStreams = true
  2589. case SettingMaxHeaderListSize:
  2590. cc.peerMaxHeaderListSize = uint64(s.Val)
  2591. case SettingInitialWindowSize:
  2592. // Values above the maximum flow-control
  2593. // window size of 2^31-1 MUST be treated as a
  2594. // connection error (Section 5.4.1) of type
  2595. // FLOW_CONTROL_ERROR.
  2596. if s.Val > math.MaxInt32 {
  2597. return ConnectionError(ErrCodeFlowControl)
  2598. }
  2599. // Adjust flow control of currently-open
  2600. // frames by the difference of the old initial
  2601. // window size and this one.
  2602. delta := int32(s.Val) - int32(cc.initialWindowSize)
  2603. for _, cs := range cc.streams {
  2604. cs.flow.add(delta)
  2605. }
  2606. cc.cond.Broadcast()
  2607. cc.initialWindowSize = s.Val
  2608. case SettingHeaderTableSize:
  2609. cc.henc.SetMaxDynamicTableSize(s.Val)
  2610. cc.peerMaxHeaderTableSize = s.Val
  2611. default:
  2612. cc.vlogf("Unhandled Setting: %v", s)
  2613. }
  2614. return nil
  2615. })
  2616. if err != nil {
  2617. return err
  2618. }
  2619. if !cc.seenSettings {
  2620. if !seenMaxConcurrentStreams {
  2621. // This was the servers initial SETTINGS frame and it
  2622. // didn't contain a MAX_CONCURRENT_STREAMS field so
  2623. // increase the number of concurrent streams this
  2624. // connection can establish to our default.
  2625. cc.maxConcurrentStreams = defaultMaxConcurrentStreams
  2626. }
  2627. cc.seenSettings = true
  2628. }
  2629. return nil
  2630. }
  2631. func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error {
  2632. cc := rl.cc
  2633. cs := rl.streamByID(f.StreamID)
  2634. if f.StreamID != 0 && cs == nil {
  2635. return nil
  2636. }
  2637. cc.mu.Lock()
  2638. defer cc.mu.Unlock()
  2639. fl := &cc.flow
  2640. if cs != nil {
  2641. fl = &cs.flow
  2642. }
  2643. if !fl.add(int32(f.Increment)) {
  2644. // For stream, the sender sends RST_STREAM with an error code of FLOW_CONTROL_ERROR
  2645. if cs != nil {
  2646. rl.endStreamError(cs, StreamError{
  2647. StreamID: f.StreamID,
  2648. Code: ErrCodeFlowControl,
  2649. })
  2650. return nil
  2651. }
  2652. return ConnectionError(ErrCodeFlowControl)
  2653. }
  2654. cc.cond.Broadcast()
  2655. return nil
  2656. }
  2657. func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error {
  2658. cs := rl.streamByID(f.StreamID)
  2659. if cs == nil {
  2660. // TODO: return error if server tries to RST_STREAM an idle stream
  2661. return nil
  2662. }
  2663. serr := streamError(cs.ID, f.ErrCode)
  2664. serr.Cause = errFromPeer
  2665. if f.ErrCode == ErrCodeProtocol {
  2666. rl.cc.SetDoNotReuse()
  2667. }
  2668. if fn := cs.cc.t.CountError; fn != nil {
  2669. fn("recv_rststream_" + f.ErrCode.stringToken())
  2670. }
  2671. cs.abortStream(serr)
  2672. cs.bufPipe.CloseWithError(serr)
  2673. return nil
  2674. }
  2675. // Ping sends a PING frame to the server and waits for the ack.
  2676. func (cc *ClientConn) Ping(ctx context.Context) error {
  2677. c := make(chan struct{})
  2678. // Generate a random payload
  2679. var p [8]byte
  2680. for {
  2681. if _, err := rand.Read(p[:]); err != nil {
  2682. return err
  2683. }
  2684. cc.mu.Lock()
  2685. // check for dup before insert
  2686. if _, found := cc.pings[p]; !found {
  2687. cc.pings[p] = c
  2688. cc.mu.Unlock()
  2689. break
  2690. }
  2691. cc.mu.Unlock()
  2692. }
  2693. errc := make(chan error, 1)
  2694. go func() {
  2695. cc.wmu.Lock()
  2696. defer cc.wmu.Unlock()
  2697. if err := cc.fr.WritePing(false, p); err != nil {
  2698. errc <- err
  2699. return
  2700. }
  2701. if err := cc.bw.Flush(); err != nil {
  2702. errc <- err
  2703. return
  2704. }
  2705. }()
  2706. select {
  2707. case <-c:
  2708. return nil
  2709. case err := <-errc:
  2710. return err
  2711. case <-ctx.Done():
  2712. return ctx.Err()
  2713. case <-cc.readerDone:
  2714. // connection closed
  2715. return cc.readerErr
  2716. }
  2717. }
  2718. func (rl *clientConnReadLoop) processPing(f *PingFrame) error {
  2719. if f.IsAck() {
  2720. cc := rl.cc
  2721. cc.mu.Lock()
  2722. defer cc.mu.Unlock()
  2723. // If ack, notify listener if any
  2724. if c, ok := cc.pings[f.Data]; ok {
  2725. close(c)
  2726. delete(cc.pings, f.Data)
  2727. }
  2728. return nil
  2729. }
  2730. cc := rl.cc
  2731. cc.wmu.Lock()
  2732. defer cc.wmu.Unlock()
  2733. if err := cc.fr.WritePing(true, f.Data); err != nil {
  2734. return err
  2735. }
  2736. return cc.bw.Flush()
  2737. }
  2738. func (rl *clientConnReadLoop) processPushPromise(f *PushPromiseFrame) error {
  2739. // We told the peer we don't want them.
  2740. // Spec says:
  2741. // "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH
  2742. // setting of the peer endpoint is set to 0. An endpoint that
  2743. // has set this setting and has received acknowledgement MUST
  2744. // treat the receipt of a PUSH_PROMISE frame as a connection
  2745. // error (Section 5.4.1) of type PROTOCOL_ERROR."
  2746. return ConnectionError(ErrCodeProtocol)
  2747. }
  2748. func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) {
  2749. // TODO: map err to more interesting error codes, once the
  2750. // HTTP community comes up with some. But currently for
  2751. // RST_STREAM there's no equivalent to GOAWAY frame's debug
  2752. // data, and the error codes are all pretty vague ("cancel").
  2753. cc.wmu.Lock()
  2754. cc.fr.WriteRSTStream(streamID, code)
  2755. cc.bw.Flush()
  2756. cc.wmu.Unlock()
  2757. }
  2758. var (
  2759. errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
  2760. errRequestHeaderListSize = errors.New("http2: request header list larger than peer's advertised limit")
  2761. )
  2762. func (cc *ClientConn) logf(format string, args ...interface{}) {
  2763. cc.t.logf(format, args...)
  2764. }
  2765. func (cc *ClientConn) vlogf(format string, args ...interface{}) {
  2766. cc.t.vlogf(format, args...)
  2767. }
  2768. func (t *Transport) vlogf(format string, args ...interface{}) {
  2769. if VerboseLogs {
  2770. t.logf(format, args...)
  2771. }
  2772. }
  2773. func (t *Transport) logf(format string, args ...interface{}) {
  2774. log.Printf(format, args...)
  2775. }
  2776. var noBody io.ReadCloser = noBodyReader{}
  2777. type noBodyReader struct{}
  2778. func (noBodyReader) Close() error { return nil }
  2779. func (noBodyReader) Read([]byte) (int, error) { return 0, io.EOF }
  2780. type missingBody struct{}
  2781. func (missingBody) Close() error { return nil }
  2782. func (missingBody) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF }
  2783. func strSliceContains(ss []string, s string) bool {
  2784. for _, v := range ss {
  2785. if v == s {
  2786. return true
  2787. }
  2788. }
  2789. return false
  2790. }
  2791. type erringRoundTripper struct{ err error }
  2792. func (rt erringRoundTripper) RoundTripErr() error { return rt.err }
  2793. func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err }
  2794. // gzipReader wraps a response body so it can lazily
  2795. // call gzip.NewReader on the first call to Read
  2796. type gzipReader struct {
  2797. _ incomparable
  2798. body io.ReadCloser // underlying Response.Body
  2799. zr *gzip.Reader // lazily-initialized gzip reader
  2800. zerr error // sticky error
  2801. }
  2802. func (gz *gzipReader) Read(p []byte) (n int, err error) {
  2803. if gz.zerr != nil {
  2804. return 0, gz.zerr
  2805. }
  2806. if gz.zr == nil {
  2807. gz.zr, err = gzip.NewReader(gz.body)
  2808. if err != nil {
  2809. gz.zerr = err
  2810. return 0, err
  2811. }
  2812. }
  2813. return gz.zr.Read(p)
  2814. }
  2815. func (gz *gzipReader) Close() error {
  2816. if err := gz.body.Close(); err != nil {
  2817. return err
  2818. }
  2819. gz.zerr = fs.ErrClosed
  2820. return nil
  2821. }
  2822. type errorReader struct{ err error }
  2823. func (r errorReader) Read(p []byte) (int, error) { return 0, r.err }
  2824. // isConnectionCloseRequest reports whether req should use its own
  2825. // connection for a single request and then close the connection.
  2826. func isConnectionCloseRequest(req *http.Request) bool {
  2827. return req.Close || httpguts.HeaderValuesContainsToken(req.Header["Connection"], "close")
  2828. }
  2829. // registerHTTPSProtocol calls Transport.RegisterProtocol but
  2830. // converting panics into errors.
  2831. func registerHTTPSProtocol(t *http.Transport, rt noDialH2RoundTripper) (err error) {
  2832. defer func() {
  2833. if e := recover(); e != nil {
  2834. err = fmt.Errorf("%v", e)
  2835. }
  2836. }()
  2837. t.RegisterProtocol("https", rt)
  2838. return nil
  2839. }
  2840. // noDialH2RoundTripper is a RoundTripper which only tries to complete the request
  2841. // if there's already has a cached connection to the host.
  2842. // (The field is exported so it can be accessed via reflect from net/http; tested
  2843. // by TestNoDialH2RoundTripperType)
  2844. type noDialH2RoundTripper struct{ *Transport }
  2845. func (rt noDialH2RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
  2846. res, err := rt.Transport.RoundTrip(req)
  2847. if isNoCachedConnError(err) {
  2848. return nil, http.ErrSkipAltProtocol
  2849. }
  2850. return res, err
  2851. }
  2852. func (t *Transport) idleConnTimeout() time.Duration {
  2853. if t.t1 != nil {
  2854. return t.t1.IdleConnTimeout
  2855. }
  2856. return 0
  2857. }
  2858. func traceGetConn(req *http.Request, hostPort string) {
  2859. trace := httptrace.ContextClientTrace(req.Context())
  2860. if trace == nil || trace.GetConn == nil {
  2861. return
  2862. }
  2863. trace.GetConn(hostPort)
  2864. }
  2865. func traceGotConn(req *http.Request, cc *ClientConn, reused bool) {
  2866. trace := httptrace.ContextClientTrace(req.Context())
  2867. if trace == nil || trace.GotConn == nil {
  2868. return
  2869. }
  2870. ci := httptrace.GotConnInfo{Conn: cc.tconn}
  2871. ci.Reused = reused
  2872. cc.mu.Lock()
  2873. ci.WasIdle = len(cc.streams) == 0 && reused
  2874. if ci.WasIdle && !cc.lastActive.IsZero() {
  2875. ci.IdleTime = time.Since(cc.lastActive)
  2876. }
  2877. cc.mu.Unlock()
  2878. trace.GotConn(ci)
  2879. }
  2880. func traceWroteHeaders(trace *httptrace.ClientTrace) {
  2881. if trace != nil && trace.WroteHeaders != nil {
  2882. trace.WroteHeaders()
  2883. }
  2884. }
  2885. func traceGot100Continue(trace *httptrace.ClientTrace) {
  2886. if trace != nil && trace.Got100Continue != nil {
  2887. trace.Got100Continue()
  2888. }
  2889. }
  2890. func traceWait100Continue(trace *httptrace.ClientTrace) {
  2891. if trace != nil && trace.Wait100Continue != nil {
  2892. trace.Wait100Continue()
  2893. }
  2894. }
  2895. func traceWroteRequest(trace *httptrace.ClientTrace, err error) {
  2896. if trace != nil && trace.WroteRequest != nil {
  2897. trace.WroteRequest(httptrace.WroteRequestInfo{Err: err})
  2898. }
  2899. }
  2900. func traceFirstResponseByte(trace *httptrace.ClientTrace) {
  2901. if trace != nil && trace.GotFirstResponseByte != nil {
  2902. trace.GotFirstResponseByte()
  2903. }
  2904. }
  2905. func traceHasWroteHeaderField(trace *httptrace.ClientTrace) bool {
  2906. return trace != nil && trace.WroteHeaderField != nil
  2907. }
  2908. func traceWroteHeaderField(trace *httptrace.ClientTrace, k, v string) {
  2909. if trace != nil && trace.WroteHeaderField != nil {
  2910. trace.WroteHeaderField(k, []string{v})
  2911. }
  2912. }
  2913. func traceGot1xxResponseFunc(trace *httptrace.ClientTrace) func(int, textproto.MIMEHeader) error {
  2914. if trace != nil {
  2915. return trace.Got1xxResponse
  2916. }
  2917. return nil
  2918. }
  2919. // dialTLSWithContext uses tls.Dialer, added in Go 1.15, to open a TLS
  2920. // connection.
  2921. func (t *Transport) dialTLSWithContext(ctx context.Context, network, addr string, cfg *tls.Config) (*tls.Conn, error) {
  2922. dialer := &tls.Dialer{
  2923. Config: cfg,
  2924. }
  2925. cn, err := dialer.DialContext(ctx, network, addr)
  2926. if err != nil {
  2927. return nil, err
  2928. }
  2929. tlsCn := cn.(*tls.Conn) // DialContext comment promises this will always succeed
  2930. return tlsCn, nil
  2931. }