transport.go 54 KB

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