transport.go 68 KB

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