transport.go 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666
  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. Setting{ID: SettingEnablePush, Val: 0},
  366. Setting{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":
  848. // Per 8.1.2.2 Connection-Specific Header
  849. // Fields, don't send connection-specific
  850. // fields. We deal with these earlier in
  851. // RoundTrip, deciding whether they're
  852. // error-worthy, but we don't want to mutate
  853. // the user's *Request so at this point, just
  854. // skip over them at this point.
  855. continue
  856. case "user-agent":
  857. // Match Go's http1 behavior: at most one
  858. // User-Agent. If set to nil or empty string,
  859. // then omit it. Otherwise if not mentioned,
  860. // include the default (below).
  861. didUA = true
  862. if len(vv) < 1 {
  863. continue
  864. }
  865. vv = vv[:1]
  866. if vv[0] == "" {
  867. continue
  868. }
  869. }
  870. for _, v := range vv {
  871. cc.writeHeader(lowKey, v)
  872. }
  873. }
  874. if shouldSendReqContentLength(req.Method, contentLength) {
  875. cc.writeHeader("content-length", strconv.FormatInt(contentLength, 10))
  876. }
  877. if addGzipHeader {
  878. cc.writeHeader("accept-encoding", "gzip")
  879. }
  880. if !didUA {
  881. cc.writeHeader("user-agent", defaultUserAgent)
  882. }
  883. return cc.hbuf.Bytes()
  884. }
  885. // shouldSendReqContentLength reports whether the http2.Transport should send
  886. // a "content-length" request header. This logic is basically a copy of the net/http
  887. // transferWriter.shouldSendContentLength.
  888. // The contentLength is the corrected contentLength (so 0 means actually 0, not unknown).
  889. // -1 means unknown.
  890. func shouldSendReqContentLength(method string, contentLength int64) bool {
  891. if contentLength > 0 {
  892. return true
  893. }
  894. if contentLength < 0 {
  895. return false
  896. }
  897. // For zero bodies, whether we send a content-length depends on the method.
  898. // It also kinda doesn't matter for http2 either way, with END_STREAM.
  899. switch method {
  900. case "POST", "PUT", "PATCH":
  901. return true
  902. default:
  903. return false
  904. }
  905. }
  906. // requires cc.mu be held.
  907. func (cc *ClientConn) encodeTrailers(req *http.Request) []byte {
  908. cc.hbuf.Reset()
  909. for k, vv := range req.Trailer {
  910. // Transfer-Encoding, etc.. have already been filter at the
  911. // start of RoundTrip
  912. lowKey := strings.ToLower(k)
  913. for _, v := range vv {
  914. cc.writeHeader(lowKey, v)
  915. }
  916. }
  917. return cc.hbuf.Bytes()
  918. }
  919. func (cc *ClientConn) writeHeader(name, value string) {
  920. if VerboseLogs {
  921. log.Printf("http2: Transport encoding header %q = %q", name, value)
  922. }
  923. cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
  924. }
  925. type resAndError struct {
  926. res *http.Response
  927. err error
  928. }
  929. // requires cc.mu be held.
  930. func (cc *ClientConn) newStream() *clientStream {
  931. cs := &clientStream{
  932. cc: cc,
  933. ID: cc.nextStreamID,
  934. resc: make(chan resAndError, 1),
  935. peerReset: make(chan struct{}),
  936. done: make(chan struct{}),
  937. }
  938. cs.flow.add(int32(cc.initialWindowSize))
  939. cs.flow.setConnFlow(&cc.flow)
  940. cs.inflow.add(transportDefaultStreamFlow)
  941. cs.inflow.setConnFlow(&cc.inflow)
  942. cc.nextStreamID += 2
  943. cc.streams[cs.ID] = cs
  944. return cs
  945. }
  946. func (cc *ClientConn) forgetStreamID(id uint32) {
  947. cc.streamByID(id, true)
  948. }
  949. func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream {
  950. cc.mu.Lock()
  951. defer cc.mu.Unlock()
  952. cs := cc.streams[id]
  953. if andRemove && cs != nil && !cc.closed {
  954. delete(cc.streams, id)
  955. close(cs.done)
  956. }
  957. return cs
  958. }
  959. // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.
  960. type clientConnReadLoop struct {
  961. cc *ClientConn
  962. activeRes map[uint32]*clientStream // keyed by streamID
  963. closeWhenIdle bool
  964. }
  965. // readLoop runs in its own goroutine and reads and dispatches frames.
  966. func (cc *ClientConn) readLoop() {
  967. rl := &clientConnReadLoop{
  968. cc: cc,
  969. activeRes: make(map[uint32]*clientStream),
  970. }
  971. defer rl.cleanup()
  972. cc.readerErr = rl.run()
  973. if ce, ok := cc.readerErr.(ConnectionError); ok {
  974. cc.wmu.Lock()
  975. cc.fr.WriteGoAway(0, ErrCode(ce), nil)
  976. cc.wmu.Unlock()
  977. }
  978. }
  979. func (rl *clientConnReadLoop) cleanup() {
  980. cc := rl.cc
  981. defer cc.tconn.Close()
  982. defer cc.t.connPool().MarkDead(cc)
  983. defer close(cc.readerDone)
  984. // Close any response bodies if the server closes prematurely.
  985. // TODO: also do this if we've written the headers but not
  986. // gotten a response yet.
  987. err := cc.readerErr
  988. if err == io.EOF {
  989. err = io.ErrUnexpectedEOF
  990. }
  991. cc.mu.Lock()
  992. for _, cs := range rl.activeRes {
  993. cs.bufPipe.CloseWithError(err)
  994. }
  995. for _, cs := range cc.streams {
  996. select {
  997. case cs.resc <- resAndError{err: err}:
  998. default:
  999. }
  1000. close(cs.done)
  1001. }
  1002. cc.closed = true
  1003. cc.cond.Broadcast()
  1004. cc.mu.Unlock()
  1005. }
  1006. func (rl *clientConnReadLoop) run() error {
  1007. cc := rl.cc
  1008. rl.closeWhenIdle = cc.t.disableKeepAlives()
  1009. gotReply := false // ever saw a reply
  1010. for {
  1011. f, err := cc.fr.ReadFrame()
  1012. if err != nil {
  1013. cc.vlogf("Transport readFrame error: (%T) %v", err, err)
  1014. }
  1015. if se, ok := err.(StreamError); ok {
  1016. if cs := cc.streamByID(se.StreamID, true /*ended; remove it*/); cs != nil {
  1017. rl.endStreamError(cs, cc.fr.errDetail)
  1018. }
  1019. continue
  1020. } else if err != nil {
  1021. return err
  1022. }
  1023. if VerboseLogs {
  1024. cc.vlogf("http2: Transport received %s", summarizeFrame(f))
  1025. }
  1026. maybeIdle := false // whether frame might transition us to idle
  1027. switch f := f.(type) {
  1028. case *MetaHeadersFrame:
  1029. err = rl.processHeaders(f)
  1030. maybeIdle = true
  1031. gotReply = true
  1032. case *DataFrame:
  1033. err = rl.processData(f)
  1034. maybeIdle = true
  1035. case *GoAwayFrame:
  1036. err = rl.processGoAway(f)
  1037. maybeIdle = true
  1038. case *RSTStreamFrame:
  1039. err = rl.processResetStream(f)
  1040. maybeIdle = true
  1041. case *SettingsFrame:
  1042. err = rl.processSettings(f)
  1043. case *PushPromiseFrame:
  1044. err = rl.processPushPromise(f)
  1045. case *WindowUpdateFrame:
  1046. err = rl.processWindowUpdate(f)
  1047. case *PingFrame:
  1048. err = rl.processPing(f)
  1049. default:
  1050. cc.logf("Transport: unhandled response frame type %T", f)
  1051. }
  1052. if err != nil {
  1053. return err
  1054. }
  1055. if rl.closeWhenIdle && gotReply && maybeIdle && len(rl.activeRes) == 0 {
  1056. cc.closeIfIdle()
  1057. }
  1058. }
  1059. }
  1060. func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error {
  1061. cc := rl.cc
  1062. cs := cc.streamByID(f.StreamID, f.StreamEnded())
  1063. if cs == nil {
  1064. // We'd get here if we canceled a request while the
  1065. // server had its response still in flight. So if this
  1066. // was just something we canceled, ignore it.
  1067. return nil
  1068. }
  1069. if !cs.pastHeaders {
  1070. cs.pastHeaders = true
  1071. } else {
  1072. return rl.processTrailers(cs, f)
  1073. }
  1074. res, err := rl.handleResponse(cs, f)
  1075. if err != nil {
  1076. if _, ok := err.(ConnectionError); ok {
  1077. return err
  1078. }
  1079. // Any other error type is a stream error.
  1080. cs.cc.writeStreamReset(f.StreamID, ErrCodeProtocol, err)
  1081. cs.resc <- resAndError{err: err}
  1082. return nil // return nil from process* funcs to keep conn alive
  1083. }
  1084. if res == nil {
  1085. // (nil, nil) special case. See handleResponse docs.
  1086. return nil
  1087. }
  1088. if res.Body != noBody {
  1089. rl.activeRes[cs.ID] = cs
  1090. }
  1091. cs.resTrailer = &res.Trailer
  1092. cs.resc <- resAndError{res: res}
  1093. return nil
  1094. }
  1095. // may return error types nil, or ConnectionError. Any other error value
  1096. // is a StreamError of type ErrCodeProtocol. The returned error in that case
  1097. // is the detail.
  1098. //
  1099. // As a special case, handleResponse may return (nil, nil) to skip the
  1100. // frame (currently only used for 100 expect continue). This special
  1101. // case is going away after Issue 13851 is fixed.
  1102. func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFrame) (*http.Response, error) {
  1103. if f.Truncated {
  1104. return nil, errResponseHeaderListSize
  1105. }
  1106. status := f.PseudoValue("status")
  1107. if status == "" {
  1108. return nil, errors.New("missing status pseudo header")
  1109. }
  1110. statusCode, err := strconv.Atoi(status)
  1111. if err != nil {
  1112. return nil, errors.New("malformed non-numeric status pseudo header")
  1113. }
  1114. if statusCode == 100 {
  1115. // Just skip 100-continue response headers for now.
  1116. // TODO: golang.org/issue/13851 for doing it properly.
  1117. cs.pastHeaders = false // do it all again
  1118. return nil, nil
  1119. }
  1120. header := make(http.Header)
  1121. res := &http.Response{
  1122. Proto: "HTTP/2.0",
  1123. ProtoMajor: 2,
  1124. Header: header,
  1125. StatusCode: statusCode,
  1126. Status: status + " " + http.StatusText(statusCode),
  1127. }
  1128. for _, hf := range f.RegularFields() {
  1129. key := http.CanonicalHeaderKey(hf.Name)
  1130. if key == "Trailer" {
  1131. t := res.Trailer
  1132. if t == nil {
  1133. t = make(http.Header)
  1134. res.Trailer = t
  1135. }
  1136. foreachHeaderElement(hf.Value, func(v string) {
  1137. t[http.CanonicalHeaderKey(v)] = nil
  1138. })
  1139. } else {
  1140. header[key] = append(header[key], hf.Value)
  1141. }
  1142. }
  1143. streamEnded := f.StreamEnded()
  1144. if !streamEnded || cs.req.Method == "HEAD" {
  1145. res.ContentLength = -1
  1146. if clens := res.Header["Content-Length"]; len(clens) == 1 {
  1147. if clen64, err := strconv.ParseInt(clens[0], 10, 64); err == nil {
  1148. res.ContentLength = clen64
  1149. } else {
  1150. // TODO: care? unlike http/1, it won't mess up our framing, so it's
  1151. // more safe smuggling-wise to ignore.
  1152. }
  1153. } else if len(clens) > 1 {
  1154. // TODO: care? unlike http/1, it won't mess up our framing, so it's
  1155. // more safe smuggling-wise to ignore.
  1156. }
  1157. }
  1158. if streamEnded {
  1159. res.Body = noBody
  1160. return res, nil
  1161. }
  1162. buf := new(bytes.Buffer) // TODO(bradfitz): recycle this garbage
  1163. cs.bufPipe = pipe{b: buf}
  1164. cs.bytesRemain = res.ContentLength
  1165. res.Body = transportResponseBody{cs}
  1166. go cs.awaitRequestCancel(requestCancel(cs.req))
  1167. if cs.requestedGzip && res.Header.Get("Content-Encoding") == "gzip" {
  1168. res.Header.Del("Content-Encoding")
  1169. res.Header.Del("Content-Length")
  1170. res.ContentLength = -1
  1171. res.Body = &gzipReader{body: res.Body}
  1172. }
  1173. return res, nil
  1174. }
  1175. func (rl *clientConnReadLoop) processTrailers(cs *clientStream, f *MetaHeadersFrame) error {
  1176. if cs.pastTrailers {
  1177. // Too many HEADERS frames for this stream.
  1178. return ConnectionError(ErrCodeProtocol)
  1179. }
  1180. cs.pastTrailers = true
  1181. if !f.StreamEnded() {
  1182. // We expect that any headers for trailers also
  1183. // has END_STREAM.
  1184. return ConnectionError(ErrCodeProtocol)
  1185. }
  1186. if len(f.PseudoFields()) > 0 {
  1187. // No pseudo header fields are defined for trailers.
  1188. // TODO: ConnectionError might be overly harsh? Check.
  1189. return ConnectionError(ErrCodeProtocol)
  1190. }
  1191. trailer := make(http.Header)
  1192. for _, hf := range f.RegularFields() {
  1193. key := http.CanonicalHeaderKey(hf.Name)
  1194. trailer[key] = append(trailer[key], hf.Value)
  1195. }
  1196. cs.trailer = trailer
  1197. rl.endStream(cs)
  1198. return nil
  1199. }
  1200. // transportResponseBody is the concrete type of Transport.RoundTrip's
  1201. // Response.Body. It is an io.ReadCloser. On Read, it reads from cs.body.
  1202. // On Close it sends RST_STREAM if EOF wasn't already seen.
  1203. type transportResponseBody struct {
  1204. cs *clientStream
  1205. }
  1206. func (b transportResponseBody) Read(p []byte) (n int, err error) {
  1207. cs := b.cs
  1208. cc := cs.cc
  1209. if cs.readErr != nil {
  1210. return 0, cs.readErr
  1211. }
  1212. n, err = b.cs.bufPipe.Read(p)
  1213. if cs.bytesRemain != -1 {
  1214. if int64(n) > cs.bytesRemain {
  1215. n = int(cs.bytesRemain)
  1216. if err == nil {
  1217. err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
  1218. cc.writeStreamReset(cs.ID, ErrCodeProtocol, err)
  1219. }
  1220. cs.readErr = err
  1221. return int(cs.bytesRemain), err
  1222. }
  1223. cs.bytesRemain -= int64(n)
  1224. if err == io.EOF && cs.bytesRemain > 0 {
  1225. err = io.ErrUnexpectedEOF
  1226. cs.readErr = err
  1227. return n, err
  1228. }
  1229. }
  1230. if n == 0 {
  1231. // No flow control tokens to send back.
  1232. return
  1233. }
  1234. cc.mu.Lock()
  1235. defer cc.mu.Unlock()
  1236. var connAdd, streamAdd int32
  1237. // Check the conn-level first, before the stream-level.
  1238. if v := cc.inflow.available(); v < transportDefaultConnFlow/2 {
  1239. connAdd = transportDefaultConnFlow - v
  1240. cc.inflow.add(connAdd)
  1241. }
  1242. if err == nil { // No need to refresh if the stream is over or failed.
  1243. if v := cs.inflow.available(); v < transportDefaultStreamFlow-transportDefaultStreamMinRefresh {
  1244. streamAdd = transportDefaultStreamFlow - v
  1245. cs.inflow.add(streamAdd)
  1246. }
  1247. }
  1248. if connAdd != 0 || streamAdd != 0 {
  1249. cc.wmu.Lock()
  1250. defer cc.wmu.Unlock()
  1251. if connAdd != 0 {
  1252. cc.fr.WriteWindowUpdate(0, mustUint31(connAdd))
  1253. }
  1254. if streamAdd != 0 {
  1255. cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd))
  1256. }
  1257. cc.bw.Flush()
  1258. }
  1259. return
  1260. }
  1261. var errClosedResponseBody = errors.New("http2: response body closed")
  1262. func (b transportResponseBody) Close() error {
  1263. cs := b.cs
  1264. if cs.bufPipe.Err() != io.EOF {
  1265. // TODO: write test for this
  1266. cs.cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  1267. }
  1268. cs.bufPipe.BreakWithError(errClosedResponseBody)
  1269. return nil
  1270. }
  1271. func (rl *clientConnReadLoop) processData(f *DataFrame) error {
  1272. cc := rl.cc
  1273. cs := cc.streamByID(f.StreamID, f.StreamEnded())
  1274. if cs == nil {
  1275. cc.mu.Lock()
  1276. neverSent := cc.nextStreamID
  1277. cc.mu.Unlock()
  1278. if f.StreamID >= neverSent {
  1279. // We never asked for this.
  1280. cc.logf("http2: Transport received unsolicited DATA frame; closing connection")
  1281. return ConnectionError(ErrCodeProtocol)
  1282. }
  1283. // We probably did ask for this, but canceled. Just ignore it.
  1284. // TODO: be stricter here? only silently ignore things which
  1285. // we canceled, but not things which were closed normally
  1286. // by the peer? Tough without accumulating too much state.
  1287. return nil
  1288. }
  1289. if data := f.Data(); len(data) > 0 {
  1290. if cs.bufPipe.b == nil {
  1291. // Data frame after it's already closed?
  1292. cc.logf("http2: Transport received DATA frame for closed stream; closing connection")
  1293. return ConnectionError(ErrCodeProtocol)
  1294. }
  1295. // Check connection-level flow control.
  1296. cc.mu.Lock()
  1297. if cs.inflow.available() >= int32(len(data)) {
  1298. cs.inflow.take(int32(len(data)))
  1299. } else {
  1300. cc.mu.Unlock()
  1301. return ConnectionError(ErrCodeFlowControl)
  1302. }
  1303. cc.mu.Unlock()
  1304. if _, err := cs.bufPipe.Write(data); err != nil {
  1305. rl.endStreamError(cs, err)
  1306. return err
  1307. }
  1308. }
  1309. if f.StreamEnded() {
  1310. rl.endStream(cs)
  1311. }
  1312. return nil
  1313. }
  1314. var errInvalidTrailers = errors.New("http2: invalid trailers")
  1315. func (rl *clientConnReadLoop) endStream(cs *clientStream) {
  1316. // TODO: check that any declared content-length matches, like
  1317. // server.go's (*stream).endStream method.
  1318. rl.endStreamError(cs, nil)
  1319. }
  1320. func (rl *clientConnReadLoop) endStreamError(cs *clientStream, err error) {
  1321. var code func()
  1322. if err == nil {
  1323. err = io.EOF
  1324. code = cs.copyTrailers
  1325. }
  1326. cs.bufPipe.closeWithErrorAndCode(err, code)
  1327. delete(rl.activeRes, cs.ID)
  1328. if cs.req.Close || cs.req.Header.Get("Connection") == "close" {
  1329. rl.closeWhenIdle = true
  1330. }
  1331. }
  1332. func (cs *clientStream) copyTrailers() {
  1333. for k, vv := range cs.trailer {
  1334. t := cs.resTrailer
  1335. if *t == nil {
  1336. *t = make(http.Header)
  1337. }
  1338. (*t)[k] = vv
  1339. }
  1340. }
  1341. func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error {
  1342. cc := rl.cc
  1343. cc.t.connPool().MarkDead(cc)
  1344. if f.ErrCode != 0 {
  1345. // TODO: deal with GOAWAY more. particularly the error code
  1346. cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
  1347. }
  1348. cc.setGoAway(f)
  1349. return nil
  1350. }
  1351. func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error {
  1352. cc := rl.cc
  1353. cc.mu.Lock()
  1354. defer cc.mu.Unlock()
  1355. return f.ForeachSetting(func(s Setting) error {
  1356. switch s.ID {
  1357. case SettingMaxFrameSize:
  1358. cc.maxFrameSize = s.Val
  1359. case SettingMaxConcurrentStreams:
  1360. cc.maxConcurrentStreams = s.Val
  1361. case SettingInitialWindowSize:
  1362. // TODO: error if this is too large.
  1363. // TODO: adjust flow control of still-open
  1364. // frames by the difference of the old initial
  1365. // window size and this one.
  1366. cc.initialWindowSize = s.Val
  1367. default:
  1368. // TODO(bradfitz): handle more settings? SETTINGS_HEADER_TABLE_SIZE probably.
  1369. cc.vlogf("Unhandled Setting: %v", s)
  1370. }
  1371. return nil
  1372. })
  1373. }
  1374. func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error {
  1375. cc := rl.cc
  1376. cs := cc.streamByID(f.StreamID, false)
  1377. if f.StreamID != 0 && cs == nil {
  1378. return nil
  1379. }
  1380. cc.mu.Lock()
  1381. defer cc.mu.Unlock()
  1382. fl := &cc.flow
  1383. if cs != nil {
  1384. fl = &cs.flow
  1385. }
  1386. if !fl.add(int32(f.Increment)) {
  1387. return ConnectionError(ErrCodeFlowControl)
  1388. }
  1389. cc.cond.Broadcast()
  1390. return nil
  1391. }
  1392. func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error {
  1393. cs := rl.cc.streamByID(f.StreamID, true)
  1394. if cs == nil {
  1395. // TODO: return error if server tries to RST_STEAM an idle stream
  1396. return nil
  1397. }
  1398. select {
  1399. case <-cs.peerReset:
  1400. // Already reset.
  1401. // This is the only goroutine
  1402. // which closes this, so there
  1403. // isn't a race.
  1404. default:
  1405. err := StreamError{cs.ID, f.ErrCode}
  1406. cs.resetErr = err
  1407. close(cs.peerReset)
  1408. cs.bufPipe.CloseWithError(err)
  1409. cs.cc.cond.Broadcast() // wake up checkReset via clientStream.awaitFlowControl
  1410. }
  1411. delete(rl.activeRes, cs.ID)
  1412. return nil
  1413. }
  1414. func (rl *clientConnReadLoop) processPing(f *PingFrame) error {
  1415. if f.IsAck() {
  1416. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  1417. // containing this flag."
  1418. return nil
  1419. }
  1420. cc := rl.cc
  1421. cc.wmu.Lock()
  1422. defer cc.wmu.Unlock()
  1423. if err := cc.fr.WritePing(true, f.Data); err != nil {
  1424. return err
  1425. }
  1426. return cc.bw.Flush()
  1427. }
  1428. func (rl *clientConnReadLoop) processPushPromise(f *PushPromiseFrame) error {
  1429. // We told the peer we don't want them.
  1430. // Spec says:
  1431. // "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH
  1432. // setting of the peer endpoint is set to 0. An endpoint that
  1433. // has set this setting and has received acknowledgement MUST
  1434. // treat the receipt of a PUSH_PROMISE frame as a connection
  1435. // error (Section 5.4.1) of type PROTOCOL_ERROR."
  1436. return ConnectionError(ErrCodeProtocol)
  1437. }
  1438. func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) {
  1439. // TODO: do something with err? send it as a debug frame to the peer?
  1440. // But that's only in GOAWAY. Invent a new frame type? Is there one already?
  1441. cc.wmu.Lock()
  1442. cc.fr.WriteRSTStream(streamID, code)
  1443. cc.bw.Flush()
  1444. cc.wmu.Unlock()
  1445. }
  1446. var (
  1447. errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
  1448. errPseudoTrailers = errors.New("http2: invalid pseudo header in trailers")
  1449. )
  1450. func (cc *ClientConn) logf(format string, args ...interface{}) {
  1451. cc.t.logf(format, args...)
  1452. }
  1453. func (cc *ClientConn) vlogf(format string, args ...interface{}) {
  1454. cc.t.vlogf(format, args...)
  1455. }
  1456. func (t *Transport) vlogf(format string, args ...interface{}) {
  1457. if VerboseLogs {
  1458. t.logf(format, args...)
  1459. }
  1460. }
  1461. func (t *Transport) logf(format string, args ...interface{}) {
  1462. log.Printf(format, args...)
  1463. }
  1464. var noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
  1465. func strSliceContains(ss []string, s string) bool {
  1466. for _, v := range ss {
  1467. if v == s {
  1468. return true
  1469. }
  1470. }
  1471. return false
  1472. }
  1473. type erringRoundTripper struct{ err error }
  1474. func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err }
  1475. // gzipReader wraps a response body so it can lazily
  1476. // call gzip.NewReader on the first call to Read
  1477. type gzipReader struct {
  1478. body io.ReadCloser // underlying Response.Body
  1479. zr *gzip.Reader // lazily-initialized gzip reader
  1480. zerr error // sticky error
  1481. }
  1482. func (gz *gzipReader) Read(p []byte) (n int, err error) {
  1483. if gz.zerr != nil {
  1484. return 0, gz.zerr
  1485. }
  1486. if gz.zr == nil {
  1487. gz.zr, err = gzip.NewReader(gz.body)
  1488. if err != nil {
  1489. gz.zerr = err
  1490. return 0, err
  1491. }
  1492. }
  1493. return gz.zr.Read(p)
  1494. }
  1495. func (gz *gzipReader) Close() error {
  1496. return gz.body.Close()
  1497. }
  1498. type errorReader struct{ err error }
  1499. func (r errorReader) Read(p []byte) (int, error) { return 0, r.err }