transport.go 45 KB

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