transport.go 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750
  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 HEADERS w/ END_HEADERS
  161. pastTrailers bool // got second HEADERS frame w/ END_HEADERS
  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. cfg.NextProtos = []string{NextProtoTLS} // TODO: don't override if already in list
  290. cfg.ServerName = host
  291. return cfg
  292. }
  293. func (t *Transport) dialTLS() func(string, string, *tls.Config) (net.Conn, error) {
  294. if t.DialTLS != nil {
  295. return t.DialTLS
  296. }
  297. return t.dialTLSDefault
  298. }
  299. func (t *Transport) dialTLSDefault(network, addr string, cfg *tls.Config) (net.Conn, error) {
  300. cn, err := tls.Dial(network, addr, cfg)
  301. if err != nil {
  302. return nil, err
  303. }
  304. if err := cn.Handshake(); err != nil {
  305. return nil, err
  306. }
  307. if !cfg.InsecureSkipVerify {
  308. if err := cn.VerifyHostname(cfg.ServerName); err != nil {
  309. return nil, err
  310. }
  311. }
  312. state := cn.ConnectionState()
  313. if p := state.NegotiatedProtocol; p != NextProtoTLS {
  314. return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, NextProtoTLS)
  315. }
  316. if !state.NegotiatedProtocolIsMutual {
  317. return nil, errors.New("http2: could not negotiate protocol mutually")
  318. }
  319. return cn, nil
  320. }
  321. // disableKeepAlives reports whether connections should be closed as
  322. // soon as possible after handling the first request.
  323. func (t *Transport) disableKeepAlives() bool {
  324. return t.t1 != nil && t.t1.DisableKeepAlives
  325. }
  326. func (t *Transport) NewClientConn(c net.Conn) (*ClientConn, error) {
  327. if VerboseLogs {
  328. t.vlogf("http2: Transport creating client conn to %v", c.RemoteAddr())
  329. }
  330. if _, err := c.Write(clientPreface); err != nil {
  331. t.vlogf("client preface write error: %v", err)
  332. return nil, err
  333. }
  334. cc := &ClientConn{
  335. t: t,
  336. tconn: c,
  337. readerDone: make(chan struct{}),
  338. nextStreamID: 1,
  339. maxFrameSize: 16 << 10, // spec default
  340. initialWindowSize: 65535, // spec default
  341. maxConcurrentStreams: 1000, // "infinite", per spec. 1000 seems good enough.
  342. streams: make(map[uint32]*clientStream),
  343. }
  344. cc.cond = sync.NewCond(&cc.mu)
  345. cc.flow.add(int32(initialWindowSize))
  346. // TODO: adjust this writer size to account for frame size +
  347. // MTU + crypto/tls record padding.
  348. cc.bw = bufio.NewWriter(stickyErrWriter{c, &cc.werr})
  349. cc.br = bufio.NewReader(c)
  350. cc.fr = NewFramer(cc.bw, cc.br)
  351. // TODO: SetMaxDynamicTableSize, SetMaxDynamicTableSizeLimit on
  352. // henc in response to SETTINGS frames?
  353. cc.henc = hpack.NewEncoder(&cc.hbuf)
  354. if cs, ok := c.(connectionStater); ok {
  355. state := cs.ConnectionState()
  356. cc.tlsState = &state
  357. }
  358. initialSettings := []Setting{
  359. Setting{ID: SettingEnablePush, Val: 0},
  360. Setting{ID: SettingInitialWindowSize, Val: transportDefaultStreamFlow},
  361. }
  362. if max := t.maxHeaderListSize(); max != 0 {
  363. initialSettings = append(initialSettings, Setting{ID: SettingMaxHeaderListSize, Val: max})
  364. }
  365. cc.fr.WriteSettings(initialSettings...)
  366. cc.fr.WriteWindowUpdate(0, transportDefaultConnFlow)
  367. cc.inflow.add(transportDefaultConnFlow + initialWindowSize)
  368. cc.bw.Flush()
  369. if cc.werr != nil {
  370. return nil, cc.werr
  371. }
  372. // Read the obligatory SETTINGS frame
  373. f, err := cc.fr.ReadFrame()
  374. if err != nil {
  375. return nil, err
  376. }
  377. sf, ok := f.(*SettingsFrame)
  378. if !ok {
  379. return nil, fmt.Errorf("expected settings frame, got: %T", f)
  380. }
  381. cc.fr.WriteSettingsAck()
  382. cc.bw.Flush()
  383. sf.ForeachSetting(func(s Setting) error {
  384. switch s.ID {
  385. case SettingMaxFrameSize:
  386. cc.maxFrameSize = s.Val
  387. case SettingMaxConcurrentStreams:
  388. cc.maxConcurrentStreams = s.Val
  389. case SettingInitialWindowSize:
  390. cc.initialWindowSize = s.Val
  391. default:
  392. // TODO(bradfitz): handle more; at least SETTINGS_HEADER_TABLE_SIZE?
  393. t.vlogf("Unhandled Setting: %v", s)
  394. }
  395. return nil
  396. })
  397. go cc.readLoop()
  398. return cc, nil
  399. }
  400. func (cc *ClientConn) setGoAway(f *GoAwayFrame) {
  401. cc.mu.Lock()
  402. defer cc.mu.Unlock()
  403. cc.goAway = f
  404. }
  405. func (cc *ClientConn) CanTakeNewRequest() bool {
  406. cc.mu.Lock()
  407. defer cc.mu.Unlock()
  408. return cc.canTakeNewRequestLocked()
  409. }
  410. func (cc *ClientConn) canTakeNewRequestLocked() bool {
  411. return cc.goAway == nil && !cc.closed &&
  412. int64(len(cc.streams)+1) < int64(cc.maxConcurrentStreams) &&
  413. cc.nextStreamID < 2147483647
  414. }
  415. func (cc *ClientConn) closeIfIdle() {
  416. cc.mu.Lock()
  417. if len(cc.streams) > 0 {
  418. cc.mu.Unlock()
  419. return
  420. }
  421. cc.closed = true
  422. // TODO: do clients send GOAWAY too? maybe? Just Close:
  423. cc.mu.Unlock()
  424. cc.tconn.Close()
  425. }
  426. const maxAllocFrameSize = 512 << 10
  427. // frameBuffer returns a scratch buffer suitable for writing DATA frames.
  428. // They're capped at the min of the peer's max frame size or 512KB
  429. // (kinda arbitrarily), but definitely capped so we don't allocate 4GB
  430. // bufers.
  431. func (cc *ClientConn) frameScratchBuffer() []byte {
  432. cc.mu.Lock()
  433. size := cc.maxFrameSize
  434. if size > maxAllocFrameSize {
  435. size = maxAllocFrameSize
  436. }
  437. for i, buf := range cc.freeBuf {
  438. if len(buf) >= int(size) {
  439. cc.freeBuf[i] = nil
  440. cc.mu.Unlock()
  441. return buf[:size]
  442. }
  443. }
  444. cc.mu.Unlock()
  445. return make([]byte, size)
  446. }
  447. func (cc *ClientConn) putFrameScratchBuffer(buf []byte) {
  448. cc.mu.Lock()
  449. defer cc.mu.Unlock()
  450. const maxBufs = 4 // arbitrary; 4 concurrent requests per conn? investigate.
  451. if len(cc.freeBuf) < maxBufs {
  452. cc.freeBuf = append(cc.freeBuf, buf)
  453. return
  454. }
  455. for i, old := range cc.freeBuf {
  456. if old == nil {
  457. cc.freeBuf[i] = buf
  458. return
  459. }
  460. }
  461. // forget about it.
  462. }
  463. // errRequestCanceled is a copy of net/http's errRequestCanceled because it's not
  464. // exported. At least they'll be DeepEqual for h1-vs-h2 comparisons tests.
  465. var errRequestCanceled = errors.New("net/http: request canceled")
  466. func commaSeparatedTrailers(req *http.Request) (string, error) {
  467. keys := make([]string, 0, len(req.Trailer))
  468. for k := range req.Trailer {
  469. k = http.CanonicalHeaderKey(k)
  470. switch k {
  471. case "Transfer-Encoding", "Trailer", "Content-Length":
  472. return "", &badStringError{"invalid Trailer key", k}
  473. }
  474. keys = append(keys, k)
  475. }
  476. if len(keys) > 0 {
  477. sort.Strings(keys)
  478. // TODO: could do better allocation-wise here, but trailers are rare,
  479. // so being lazy for now.
  480. return strings.Join(keys, ","), nil
  481. }
  482. return "", nil
  483. }
  484. func (cc *ClientConn) responseHeaderTimeout() time.Duration {
  485. if cc.t.t1 != nil {
  486. return cc.t.t1.ResponseHeaderTimeout
  487. }
  488. // No way to do this (yet?) with just an http2.Transport. Probably
  489. // no need. Request.Cancel this is the new way. We only need to support
  490. // this for compatibility with the old http.Transport fields when
  491. // we're doing transparent http2.
  492. return 0
  493. }
  494. // checkConnHeaders checks whether req has any invalid connection-level headers.
  495. // per RFC 7540 section 8.1.2.2: Connection-Specific Header Fields.
  496. // Certain headers are special-cased as okay but not transmitted later.
  497. func checkConnHeaders(req *http.Request) error {
  498. if v := req.Header.Get("Upgrade"); v != "" {
  499. return errors.New("http2: invalid Upgrade request header")
  500. }
  501. if v := req.Header.Get("Transfer-Encoding"); (v != "" && v != "chunked") || len(req.Header["Transfer-Encoding"]) > 1 {
  502. return errors.New("http2: invalid Transfer-Encoding request header")
  503. }
  504. if v := req.Header.Get("Connection"); (v != "" && v != "close" && v != "keep-alive") || len(req.Header["Connection"]) > 1 {
  505. return errors.New("http2: invalid Connection request header")
  506. }
  507. return nil
  508. }
  509. func (cc *ClientConn) RoundTrip(req *http.Request) (*http.Response, error) {
  510. if err := checkConnHeaders(req); err != nil {
  511. return nil, err
  512. }
  513. trailers, err := commaSeparatedTrailers(req)
  514. if err != nil {
  515. return nil, err
  516. }
  517. hasTrailers := trailers != ""
  518. var body io.Reader = req.Body
  519. contentLen := req.ContentLength
  520. if req.Body != nil && contentLen == 0 {
  521. // Test to see if it's actually zero or just unset.
  522. var buf [1]byte
  523. n, rerr := io.ReadFull(body, buf[:])
  524. if rerr != nil && rerr != io.EOF {
  525. contentLen = -1
  526. body = errorReader{rerr}
  527. } else if n == 1 {
  528. // Oh, guess there is data in this Body Reader after all.
  529. // The ContentLength field just wasn't set.
  530. // Stich the Body back together again, re-attaching our
  531. // consumed byte.
  532. contentLen = -1
  533. body = io.MultiReader(bytes.NewReader(buf[:]), body)
  534. } else {
  535. // Body is actually empty.
  536. body = nil
  537. }
  538. }
  539. cc.mu.Lock()
  540. if cc.closed || !cc.canTakeNewRequestLocked() {
  541. cc.mu.Unlock()
  542. return nil, errClientConnUnusable
  543. }
  544. cs := cc.newStream()
  545. cs.req = req
  546. hasBody := body != nil
  547. // TODO(bradfitz): this is a copy of the logic in net/http. Unify somewhere?
  548. if !cc.t.disableCompression() &&
  549. req.Header.Get("Accept-Encoding") == "" &&
  550. req.Header.Get("Range") == "" &&
  551. req.Method != "HEAD" {
  552. // Request gzip only, not deflate. Deflate is ambiguous and
  553. // not as universally supported anyway.
  554. // See: http://www.gzip.org/zlib/zlib_faq.html#faq38
  555. //
  556. // Note that we don't request this for HEAD requests,
  557. // due to a bug in nginx:
  558. // http://trac.nginx.org/nginx/ticket/358
  559. // https://golang.org/issue/5522
  560. //
  561. // We don't request gzip if the request is for a range, since
  562. // auto-decoding a portion of a gzipped document will just fail
  563. // anyway. See https://golang.org/issue/8923
  564. cs.requestedGzip = true
  565. }
  566. // we send: HEADERS{1}, CONTINUATION{0,} + DATA{0,} (DATA is
  567. // sent by writeRequestBody below, along with any Trailers,
  568. // again in form HEADERS{1}, CONTINUATION{0,})
  569. hdrs := cc.encodeHeaders(req, cs.requestedGzip, trailers, contentLen)
  570. cc.wmu.Lock()
  571. endStream := !hasBody && !hasTrailers
  572. werr := cc.writeHeaders(cs.ID, endStream, hdrs)
  573. cc.wmu.Unlock()
  574. cc.mu.Unlock()
  575. if werr != nil {
  576. if hasBody {
  577. req.Body.Close() // per RoundTripper contract
  578. }
  579. cc.forgetStreamID(cs.ID)
  580. // Don't bother sending a RST_STREAM (our write already failed;
  581. // no need to keep writing)
  582. return nil, werr
  583. }
  584. var respHeaderTimer <-chan time.Time
  585. var bodyCopyErrc chan error // result of body copy
  586. if hasBody {
  587. bodyCopyErrc = make(chan error, 1)
  588. go func() {
  589. bodyCopyErrc <- cs.writeRequestBody(body, req.Body)
  590. }()
  591. } else {
  592. if d := cc.responseHeaderTimeout(); d != 0 {
  593. timer := time.NewTimer(d)
  594. defer timer.Stop()
  595. respHeaderTimer = timer.C
  596. }
  597. }
  598. readLoopResCh := cs.resc
  599. requestCanceledCh := requestCancel(req)
  600. bodyWritten := false
  601. for {
  602. select {
  603. case re := <-readLoopResCh:
  604. res := re.res
  605. if re.err != nil || res.StatusCode > 299 {
  606. // On error or status code 3xx, 4xx, 5xx, etc abort any
  607. // ongoing write, assuming that the server doesn't care
  608. // about our request body. If the server replied with 1xx or
  609. // 2xx, however, then assume the server DOES potentially
  610. // want our body (e.g. full-duplex streaming:
  611. // golang.org/issue/13444). If it turns out the server
  612. // doesn't, they'll RST_STREAM us soon enough. This is a
  613. // heuristic to avoid adding knobs to Transport. Hopefully
  614. // we can keep it.
  615. cs.abortRequestBodyWrite(errStopReqBodyWrite)
  616. }
  617. if re.err != nil {
  618. cc.forgetStreamID(cs.ID)
  619. return nil, re.err
  620. }
  621. res.Request = req
  622. res.TLS = cc.tlsState
  623. return res, nil
  624. case <-respHeaderTimer:
  625. cc.forgetStreamID(cs.ID)
  626. if !hasBody || bodyWritten {
  627. cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  628. } else {
  629. cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
  630. }
  631. return nil, errTimeout
  632. case <-requestCanceledCh:
  633. cc.forgetStreamID(cs.ID)
  634. if !hasBody || bodyWritten {
  635. cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  636. } else {
  637. cs.abortRequestBodyWrite(errStopReqBodyWriteAndCancel)
  638. }
  639. return nil, errRequestCanceled
  640. case <-cs.peerReset:
  641. // processResetStream already removed the
  642. // stream from the streams map; no need for
  643. // forgetStreamID.
  644. return nil, cs.resetErr
  645. case err := <-bodyCopyErrc:
  646. if err != nil {
  647. return nil, err
  648. }
  649. bodyWritten = true
  650. if d := cc.responseHeaderTimeout(); d != 0 {
  651. timer := time.NewTimer(d)
  652. defer timer.Stop()
  653. respHeaderTimer = timer.C
  654. }
  655. }
  656. }
  657. }
  658. // requires cc.wmu be held
  659. func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, hdrs []byte) error {
  660. first := true // first frame written (HEADERS is first, then CONTINUATION)
  661. frameSize := int(cc.maxFrameSize)
  662. for len(hdrs) > 0 && cc.werr == nil {
  663. chunk := hdrs
  664. if len(chunk) > frameSize {
  665. chunk = chunk[:frameSize]
  666. }
  667. hdrs = hdrs[len(chunk):]
  668. endHeaders := len(hdrs) == 0
  669. if first {
  670. cc.fr.WriteHeaders(HeadersFrameParam{
  671. StreamID: streamID,
  672. BlockFragment: chunk,
  673. EndStream: endStream,
  674. EndHeaders: endHeaders,
  675. })
  676. first = false
  677. } else {
  678. cc.fr.WriteContinuation(streamID, endHeaders, chunk)
  679. }
  680. }
  681. // TODO(bradfitz): this Flush could potentially block (as
  682. // could the WriteHeaders call(s) above), which means they
  683. // wouldn't respond to Request.Cancel being readable. That's
  684. // rare, but this should probably be in a goroutine.
  685. cc.bw.Flush()
  686. return cc.werr
  687. }
  688. // internal error values; they don't escape to callers
  689. var (
  690. // abort request body write; don't send cancel
  691. errStopReqBodyWrite = errors.New("http2: aborting request body write")
  692. // abort request body write, but send stream reset of cancel.
  693. errStopReqBodyWriteAndCancel = errors.New("http2: canceling request")
  694. )
  695. func (cs *clientStream) writeRequestBody(body io.Reader, bodyCloser io.Closer) (err error) {
  696. cc := cs.cc
  697. sentEnd := false // whether we sent the final DATA frame w/ END_STREAM
  698. buf := cc.frameScratchBuffer()
  699. defer cc.putFrameScratchBuffer(buf)
  700. defer func() {
  701. // TODO: write h12Compare test showing whether
  702. // Request.Body is closed by the Transport,
  703. // and in multiple cases: server replies <=299 and >299
  704. // while still writing request body
  705. cerr := bodyCloser.Close()
  706. if err == nil {
  707. err = cerr
  708. }
  709. }()
  710. req := cs.req
  711. hasTrailers := req.Trailer != nil
  712. var sawEOF bool
  713. for !sawEOF {
  714. n, err := body.Read(buf)
  715. if err == io.EOF {
  716. sawEOF = true
  717. err = nil
  718. } else if err != nil {
  719. return err
  720. }
  721. remain := buf[:n]
  722. for len(remain) > 0 && err == nil {
  723. var allowed int32
  724. allowed, err = cs.awaitFlowControl(len(remain))
  725. switch {
  726. case err == errStopReqBodyWrite:
  727. return err
  728. case err == errStopReqBodyWriteAndCancel:
  729. cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  730. return err
  731. case err != nil:
  732. return err
  733. }
  734. cc.wmu.Lock()
  735. data := remain[:allowed]
  736. remain = remain[allowed:]
  737. sentEnd = sawEOF && len(remain) == 0 && !hasTrailers
  738. err = cc.fr.WriteData(cs.ID, sentEnd, data)
  739. if err == nil {
  740. // TODO(bradfitz): this flush is for latency, not bandwidth.
  741. // Most requests won't need this. Make this opt-in or opt-out?
  742. // Use some heuristic on the body type? Nagel-like timers?
  743. // Based on 'n'? Only last chunk of this for loop, unless flow control
  744. // tokens are low? For now, always:
  745. err = cc.bw.Flush()
  746. }
  747. cc.wmu.Unlock()
  748. }
  749. if err != nil {
  750. return err
  751. }
  752. }
  753. cc.wmu.Lock()
  754. if !sentEnd {
  755. var trls []byte
  756. if hasTrailers {
  757. cc.mu.Lock()
  758. trls = cc.encodeTrailers(req)
  759. cc.mu.Unlock()
  760. }
  761. // Avoid forgetting to send an END_STREAM if the encoded
  762. // trailers are 0 bytes. Both results produce and END_STREAM.
  763. if len(trls) > 0 {
  764. err = cc.writeHeaders(cs.ID, true, trls)
  765. } else {
  766. err = cc.fr.WriteData(cs.ID, true, nil)
  767. }
  768. }
  769. if ferr := cc.bw.Flush(); ferr != nil && err == nil {
  770. err = ferr
  771. }
  772. cc.wmu.Unlock()
  773. return err
  774. }
  775. // awaitFlowControl waits for [1, min(maxBytes, cc.cs.maxFrameSize)] flow
  776. // control tokens from the server.
  777. // It returns either the non-zero number of tokens taken or an error
  778. // if the stream is dead.
  779. func (cs *clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
  780. cc := cs.cc
  781. cc.mu.Lock()
  782. defer cc.mu.Unlock()
  783. for {
  784. if cc.closed {
  785. return 0, errClientConnClosed
  786. }
  787. if cs.stopReqBody != nil {
  788. return 0, cs.stopReqBody
  789. }
  790. if err := cs.checkReset(); err != nil {
  791. return 0, err
  792. }
  793. if a := cs.flow.available(); a > 0 {
  794. take := a
  795. if int(take) > maxBytes {
  796. take = int32(maxBytes) // can't truncate int; take is int32
  797. }
  798. if take > int32(cc.maxFrameSize) {
  799. take = int32(cc.maxFrameSize)
  800. }
  801. cs.flow.take(take)
  802. return take, nil
  803. }
  804. cc.cond.Wait()
  805. }
  806. }
  807. type badStringError struct {
  808. what string
  809. str string
  810. }
  811. func (e *badStringError) Error() string { return fmt.Sprintf("%s %q", e.what, e.str) }
  812. // requires cc.mu be held.
  813. func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) []byte {
  814. cc.hbuf.Reset()
  815. host := req.Host
  816. if host == "" {
  817. host = req.URL.Host
  818. }
  819. // 8.1.2.3 Request Pseudo-Header Fields
  820. // The :path pseudo-header field includes the path and query parts of the
  821. // target URI (the path-absolute production and optionally a '?' character
  822. // followed by the query production (see Sections 3.3 and 3.4 of
  823. // [RFC3986]).
  824. cc.writeHeader(":authority", host)
  825. cc.writeHeader(":method", req.Method)
  826. if req.Method != "CONNECT" {
  827. cc.writeHeader(":path", req.URL.RequestURI())
  828. cc.writeHeader(":scheme", "https")
  829. }
  830. if trailers != "" {
  831. cc.writeHeader("trailer", trailers)
  832. }
  833. var didUA bool
  834. for k, vv := range req.Header {
  835. lowKey := strings.ToLower(k)
  836. switch lowKey {
  837. case "host", "content-length":
  838. // Host is :authority, already sent.
  839. // Content-Length is automatic, set below.
  840. continue
  841. case "connection", "proxy-connection", "transfer-encoding", "upgrade":
  842. // Per 8.1.2.2 Connection-Specific Header
  843. // Fields, don't send connection-specific
  844. // fields. We deal with these earlier in
  845. // RoundTrip, deciding whether they're
  846. // error-worthy, but we don't want to mutate
  847. // the user's *Request so at this point, just
  848. // skip over them at this point.
  849. continue
  850. case "user-agent":
  851. // Match Go's http1 behavior: at most one
  852. // User-Agent. If set to nil or empty string,
  853. // then omit it. Otherwise if not mentioned,
  854. // include the default (below).
  855. didUA = true
  856. if len(vv) < 1 {
  857. continue
  858. }
  859. vv = vv[:1]
  860. if vv[0] == "" {
  861. continue
  862. }
  863. }
  864. for _, v := range vv {
  865. cc.writeHeader(lowKey, v)
  866. }
  867. }
  868. if shouldSendReqContentLength(req.Method, contentLength) {
  869. cc.writeHeader("content-length", strconv.FormatInt(contentLength, 10))
  870. }
  871. if addGzipHeader {
  872. cc.writeHeader("accept-encoding", "gzip")
  873. }
  874. if !didUA {
  875. cc.writeHeader("user-agent", defaultUserAgent)
  876. }
  877. return cc.hbuf.Bytes()
  878. }
  879. // shouldSendReqContentLength reports whether the http2.Transport should send
  880. // a "content-length" request header. This logic is basically a copy of the net/http
  881. // transferWriter.shouldSendContentLength.
  882. // The contentLength is the corrected contentLength (so 0 means actually 0, not unknown).
  883. // -1 means unknown.
  884. func shouldSendReqContentLength(method string, contentLength int64) bool {
  885. if contentLength > 0 {
  886. return true
  887. }
  888. if contentLength < 0 {
  889. return false
  890. }
  891. // For zero bodies, whether we send a content-length depends on the method.
  892. // It also kinda doesn't matter for http2 either way, with END_STREAM.
  893. switch method {
  894. case "POST", "PUT", "PATCH":
  895. return true
  896. default:
  897. return false
  898. }
  899. }
  900. // requires cc.mu be held.
  901. func (cc *ClientConn) encodeTrailers(req *http.Request) []byte {
  902. cc.hbuf.Reset()
  903. for k, vv := range req.Trailer {
  904. // Transfer-Encoding, etc.. have already been filter at the
  905. // start of RoundTrip
  906. lowKey := strings.ToLower(k)
  907. for _, v := range vv {
  908. cc.writeHeader(lowKey, v)
  909. }
  910. }
  911. return cc.hbuf.Bytes()
  912. }
  913. func (cc *ClientConn) writeHeader(name, value string) {
  914. if VerboseLogs {
  915. log.Printf("http2: Transport encoding header %q = %q", name, value)
  916. }
  917. cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
  918. }
  919. type resAndError struct {
  920. res *http.Response
  921. err error
  922. }
  923. // requires cc.mu be held.
  924. func (cc *ClientConn) newStream() *clientStream {
  925. cs := &clientStream{
  926. cc: cc,
  927. ID: cc.nextStreamID,
  928. resc: make(chan resAndError, 1),
  929. peerReset: make(chan struct{}),
  930. done: make(chan struct{}),
  931. }
  932. cs.flow.add(int32(cc.initialWindowSize))
  933. cs.flow.setConnFlow(&cc.flow)
  934. cs.inflow.add(transportDefaultStreamFlow)
  935. cs.inflow.setConnFlow(&cc.inflow)
  936. cc.nextStreamID += 2
  937. cc.streams[cs.ID] = cs
  938. return cs
  939. }
  940. func (cc *ClientConn) forgetStreamID(id uint32) {
  941. cc.streamByID(id, true)
  942. }
  943. func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream {
  944. cc.mu.Lock()
  945. defer cc.mu.Unlock()
  946. cs := cc.streams[id]
  947. if andRemove && cs != nil && !cc.closed {
  948. delete(cc.streams, id)
  949. close(cs.done)
  950. }
  951. return cs
  952. }
  953. // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop.
  954. type clientConnReadLoop struct {
  955. cc *ClientConn
  956. activeRes map[uint32]*clientStream // keyed by streamID
  957. closeWhenIdle bool
  958. hdec *hpack.Decoder
  959. // Fields reset on each HEADERS:
  960. nextRes *http.Response
  961. sawRegHeader bool // saw non-pseudo header
  962. reqMalformed error // non-nil once known to be malformed
  963. lastHeaderEndsStream bool
  964. headerListSize int64 // actually uint32, but easier math this way
  965. }
  966. // readLoop runs in its own goroutine and reads and dispatches frames.
  967. func (cc *ClientConn) readLoop() {
  968. rl := &clientConnReadLoop{
  969. cc: cc,
  970. activeRes: make(map[uint32]*clientStream),
  971. }
  972. rl.hdec = hpack.NewDecoder(initialHeaderTableSize, rl.onNewHeaderField)
  973. defer rl.cleanup()
  974. cc.readerErr = rl.run()
  975. if ce, ok := cc.readerErr.(ConnectionError); ok {
  976. cc.wmu.Lock()
  977. cc.fr.WriteGoAway(0, ErrCode(ce), nil)
  978. cc.wmu.Unlock()
  979. }
  980. }
  981. func (rl *clientConnReadLoop) cleanup() {
  982. cc := rl.cc
  983. defer cc.tconn.Close()
  984. defer cc.t.connPool().MarkDead(cc)
  985. defer close(cc.readerDone)
  986. // Close any response bodies if the server closes prematurely.
  987. // TODO: also do this if we've written the headers but not
  988. // gotten a response yet.
  989. err := cc.readerErr
  990. if err == io.EOF {
  991. err = io.ErrUnexpectedEOF
  992. }
  993. cc.mu.Lock()
  994. for _, cs := range rl.activeRes {
  995. cs.bufPipe.CloseWithError(err)
  996. }
  997. for _, cs := range cc.streams {
  998. select {
  999. case cs.resc <- resAndError{err: err}:
  1000. default:
  1001. }
  1002. close(cs.done)
  1003. }
  1004. cc.closed = true
  1005. cc.cond.Broadcast()
  1006. cc.mu.Unlock()
  1007. }
  1008. func (rl *clientConnReadLoop) run() error {
  1009. cc := rl.cc
  1010. rl.closeWhenIdle = cc.t.disableKeepAlives()
  1011. gotReply := false // ever saw a reply
  1012. for {
  1013. f, err := cc.fr.ReadFrame()
  1014. if err != nil {
  1015. cc.vlogf("Transport readFrame error: (%T) %v", err, err)
  1016. }
  1017. if se, ok := err.(StreamError); ok {
  1018. // TODO: deal with stream errors from the framer.
  1019. return se
  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 *HeadersFrame:
  1029. err = rl.processHeaders(f)
  1030. maybeIdle = true
  1031. gotReply = true
  1032. case *ContinuationFrame:
  1033. err = rl.processContinuation(f)
  1034. maybeIdle = true
  1035. case *DataFrame:
  1036. err = rl.processData(f)
  1037. maybeIdle = true
  1038. case *GoAwayFrame:
  1039. err = rl.processGoAway(f)
  1040. maybeIdle = true
  1041. case *RSTStreamFrame:
  1042. err = rl.processResetStream(f)
  1043. maybeIdle = true
  1044. case *SettingsFrame:
  1045. err = rl.processSettings(f)
  1046. case *PushPromiseFrame:
  1047. err = rl.processPushPromise(f)
  1048. case *WindowUpdateFrame:
  1049. err = rl.processWindowUpdate(f)
  1050. case *PingFrame:
  1051. err = rl.processPing(f)
  1052. default:
  1053. cc.logf("Transport: unhandled response frame type %T", f)
  1054. }
  1055. if err != nil {
  1056. return err
  1057. }
  1058. if rl.closeWhenIdle && gotReply && maybeIdle && len(rl.activeRes) == 0 {
  1059. cc.closeIfIdle()
  1060. }
  1061. }
  1062. }
  1063. func (rl *clientConnReadLoop) processHeaders(f *HeadersFrame) error {
  1064. rl.sawRegHeader = false
  1065. rl.reqMalformed = nil
  1066. rl.lastHeaderEndsStream = f.StreamEnded()
  1067. rl.headerListSize = 0
  1068. rl.nextRes = &http.Response{
  1069. Proto: "HTTP/2.0",
  1070. ProtoMajor: 2,
  1071. Header: make(http.Header),
  1072. }
  1073. rl.hdec.SetEmitEnabled(true)
  1074. return rl.processHeaderBlockFragment(f.HeaderBlockFragment(), f.StreamID, f.HeadersEnded())
  1075. }
  1076. func (rl *clientConnReadLoop) processContinuation(f *ContinuationFrame) error {
  1077. return rl.processHeaderBlockFragment(f.HeaderBlockFragment(), f.StreamID, f.HeadersEnded())
  1078. }
  1079. func (rl *clientConnReadLoop) processHeaderBlockFragment(frag []byte, streamID uint32, finalFrag bool) error {
  1080. cc := rl.cc
  1081. streamEnded := rl.lastHeaderEndsStream
  1082. cs := cc.streamByID(streamID, streamEnded && finalFrag)
  1083. if cs == nil {
  1084. // We'd get here if we canceled a request while the
  1085. // server was mid-way through replying with its
  1086. // headers. (The case of a CONTINUATION arriving
  1087. // without HEADERS would be rejected earlier by the
  1088. // Framer). So if this was just something we canceled,
  1089. // ignore it.
  1090. return nil
  1091. }
  1092. if cs.pastHeaders {
  1093. rl.hdec.SetEmitFunc(func(f hpack.HeaderField) { rl.onNewTrailerField(cs, f) })
  1094. } else {
  1095. rl.hdec.SetEmitFunc(rl.onNewHeaderField)
  1096. }
  1097. _, err := rl.hdec.Write(frag)
  1098. if err != nil {
  1099. return ConnectionError(ErrCodeCompression)
  1100. }
  1101. if finalFrag {
  1102. if err := rl.hdec.Close(); err != nil {
  1103. return ConnectionError(ErrCodeCompression)
  1104. }
  1105. }
  1106. if !finalFrag {
  1107. return nil
  1108. }
  1109. if !cs.pastHeaders {
  1110. cs.pastHeaders = true
  1111. } else {
  1112. // We're dealing with trailers. (and specifically the
  1113. // final frame of headers)
  1114. if cs.pastTrailers {
  1115. // Too many HEADERS frames for this stream.
  1116. return ConnectionError(ErrCodeProtocol)
  1117. }
  1118. cs.pastTrailers = true
  1119. if !streamEnded {
  1120. // We expect that any header block fragment
  1121. // frame for trailers with END_HEADERS also
  1122. // has END_STREAM.
  1123. return ConnectionError(ErrCodeProtocol)
  1124. }
  1125. rl.endStream(cs)
  1126. return nil
  1127. }
  1128. if rl.reqMalformed != nil {
  1129. cs.resc <- resAndError{err: rl.reqMalformed}
  1130. rl.cc.writeStreamReset(cs.ID, ErrCodeProtocol, rl.reqMalformed)
  1131. return nil
  1132. }
  1133. res := rl.nextRes
  1134. if res.StatusCode == 100 {
  1135. // Just skip 100-continue response headers for now.
  1136. // TODO: golang.org/issue/13851 for doing it properly.
  1137. cs.pastHeaders = false // do it all again
  1138. return nil
  1139. }
  1140. if !streamEnded || cs.req.Method == "HEAD" {
  1141. res.ContentLength = -1
  1142. if clens := res.Header["Content-Length"]; len(clens) == 1 {
  1143. if clen64, err := strconv.ParseInt(clens[0], 10, 64); err == nil {
  1144. res.ContentLength = clen64
  1145. } else {
  1146. // TODO: care? unlike http/1, it won't mess up our framing, so it's
  1147. // more safe smuggling-wise to ignore.
  1148. }
  1149. } else if len(clens) > 1 {
  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. }
  1154. if streamEnded {
  1155. res.Body = noBody
  1156. } else {
  1157. buf := new(bytes.Buffer) // TODO(bradfitz): recycle this garbage
  1158. cs.bufPipe = pipe{b: buf}
  1159. cs.bytesRemain = res.ContentLength
  1160. res.Body = transportResponseBody{cs}
  1161. go cs.awaitRequestCancel(requestCancel(cs.req))
  1162. if cs.requestedGzip && res.Header.Get("Content-Encoding") == "gzip" {
  1163. res.Header.Del("Content-Encoding")
  1164. res.Header.Del("Content-Length")
  1165. res.ContentLength = -1
  1166. res.Body = &gzipReader{body: res.Body}
  1167. }
  1168. rl.activeRes[cs.ID] = cs
  1169. }
  1170. cs.resTrailer = &res.Trailer
  1171. cs.resc <- resAndError{res: res}
  1172. rl.nextRes = nil // unused now; will be reset next HEADERS frame
  1173. return nil
  1174. }
  1175. // transportResponseBody is the concrete type of Transport.RoundTrip's
  1176. // Response.Body. It is an io.ReadCloser. On Read, it reads from cs.body.
  1177. // On Close it sends RST_STREAM if EOF wasn't already seen.
  1178. type transportResponseBody struct {
  1179. cs *clientStream
  1180. }
  1181. func (b transportResponseBody) Read(p []byte) (n int, err error) {
  1182. cs := b.cs
  1183. cc := cs.cc
  1184. if cs.readErr != nil {
  1185. return 0, cs.readErr
  1186. }
  1187. n, err = b.cs.bufPipe.Read(p)
  1188. if cs.bytesRemain != -1 {
  1189. if int64(n) > cs.bytesRemain {
  1190. n = int(cs.bytesRemain)
  1191. if err == nil {
  1192. err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
  1193. cc.writeStreamReset(cs.ID, ErrCodeProtocol, err)
  1194. }
  1195. cs.readErr = err
  1196. return int(cs.bytesRemain), err
  1197. }
  1198. cs.bytesRemain -= int64(n)
  1199. if err == io.EOF && cs.bytesRemain > 0 {
  1200. err = io.ErrUnexpectedEOF
  1201. cs.readErr = err
  1202. return n, err
  1203. }
  1204. }
  1205. if n == 0 {
  1206. // No flow control tokens to send back.
  1207. return
  1208. }
  1209. cc.mu.Lock()
  1210. defer cc.mu.Unlock()
  1211. var connAdd, streamAdd int32
  1212. // Check the conn-level first, before the stream-level.
  1213. if v := cc.inflow.available(); v < transportDefaultConnFlow/2 {
  1214. connAdd = transportDefaultConnFlow - v
  1215. cc.inflow.add(connAdd)
  1216. }
  1217. if err == nil { // No need to refresh if the stream is over or failed.
  1218. if v := cs.inflow.available(); v < transportDefaultStreamFlow-transportDefaultStreamMinRefresh {
  1219. streamAdd = transportDefaultStreamFlow - v
  1220. cs.inflow.add(streamAdd)
  1221. }
  1222. }
  1223. if connAdd != 0 || streamAdd != 0 {
  1224. cc.wmu.Lock()
  1225. defer cc.wmu.Unlock()
  1226. if connAdd != 0 {
  1227. cc.fr.WriteWindowUpdate(0, mustUint31(connAdd))
  1228. }
  1229. if streamAdd != 0 {
  1230. cc.fr.WriteWindowUpdate(cs.ID, mustUint31(streamAdd))
  1231. }
  1232. cc.bw.Flush()
  1233. }
  1234. return
  1235. }
  1236. var errClosedResponseBody = errors.New("http2: response body closed")
  1237. func (b transportResponseBody) Close() error {
  1238. cs := b.cs
  1239. if cs.bufPipe.Err() != io.EOF {
  1240. // TODO: write test for this
  1241. cs.cc.writeStreamReset(cs.ID, ErrCodeCancel, nil)
  1242. }
  1243. cs.bufPipe.BreakWithError(errClosedResponseBody)
  1244. return nil
  1245. }
  1246. func (rl *clientConnReadLoop) processData(f *DataFrame) error {
  1247. cc := rl.cc
  1248. cs := cc.streamByID(f.StreamID, f.StreamEnded())
  1249. if cs == nil {
  1250. cc.mu.Lock()
  1251. neverSent := cc.nextStreamID
  1252. cc.mu.Unlock()
  1253. if f.StreamID >= neverSent {
  1254. // We never asked for this.
  1255. cc.logf("http2: Transport received unsolicited DATA frame; closing connection")
  1256. return ConnectionError(ErrCodeProtocol)
  1257. }
  1258. // We probably did ask for this, but canceled. Just ignore it.
  1259. // TODO: be stricter here? only silently ignore things which
  1260. // we canceled, but not things which were closed normally
  1261. // by the peer? Tough without accumulating too much state.
  1262. return nil
  1263. }
  1264. if data := f.Data(); len(data) > 0 {
  1265. if cs.bufPipe.b == nil {
  1266. // Data frame after it's already closed?
  1267. cc.logf("http2: Transport received DATA frame for closed stream; closing connection")
  1268. return ConnectionError(ErrCodeProtocol)
  1269. }
  1270. // Check connection-level flow control.
  1271. cc.mu.Lock()
  1272. if cs.inflow.available() >= int32(len(data)) {
  1273. cs.inflow.take(int32(len(data)))
  1274. } else {
  1275. cc.mu.Unlock()
  1276. return ConnectionError(ErrCodeFlowControl)
  1277. }
  1278. cc.mu.Unlock()
  1279. if _, err := cs.bufPipe.Write(data); err != nil {
  1280. return err
  1281. }
  1282. }
  1283. if f.StreamEnded() {
  1284. rl.endStream(cs)
  1285. }
  1286. return nil
  1287. }
  1288. var errInvalidTrailers = errors.New("http2: invalid trailers")
  1289. func (rl *clientConnReadLoop) endStream(cs *clientStream) {
  1290. // TODO: check that any declared content-length matches, like
  1291. // server.go's (*stream).endStream method.
  1292. err := io.EOF
  1293. code := cs.copyTrailers
  1294. if rl.reqMalformed != nil {
  1295. err = rl.reqMalformed
  1296. code = nil
  1297. }
  1298. cs.bufPipe.closeWithErrorAndCode(err, code)
  1299. delete(rl.activeRes, cs.ID)
  1300. if cs.req.Close || cs.req.Header.Get("Connection") == "close" {
  1301. rl.closeWhenIdle = true
  1302. }
  1303. }
  1304. func (cs *clientStream) copyTrailers() {
  1305. for k, vv := range cs.trailer {
  1306. t := cs.resTrailer
  1307. if *t == nil {
  1308. *t = make(http.Header)
  1309. }
  1310. (*t)[k] = vv
  1311. }
  1312. }
  1313. func (rl *clientConnReadLoop) processGoAway(f *GoAwayFrame) error {
  1314. cc := rl.cc
  1315. cc.t.connPool().MarkDead(cc)
  1316. if f.ErrCode != 0 {
  1317. // TODO: deal with GOAWAY more. particularly the error code
  1318. cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
  1319. }
  1320. cc.setGoAway(f)
  1321. return nil
  1322. }
  1323. func (rl *clientConnReadLoop) processSettings(f *SettingsFrame) error {
  1324. cc := rl.cc
  1325. cc.mu.Lock()
  1326. defer cc.mu.Unlock()
  1327. return f.ForeachSetting(func(s Setting) error {
  1328. switch s.ID {
  1329. case SettingMaxFrameSize:
  1330. cc.maxFrameSize = s.Val
  1331. case SettingMaxConcurrentStreams:
  1332. cc.maxConcurrentStreams = s.Val
  1333. case SettingInitialWindowSize:
  1334. // TODO: error if this is too large.
  1335. // TODO: adjust flow control of still-open
  1336. // frames by the difference of the old initial
  1337. // window size and this one.
  1338. cc.initialWindowSize = s.Val
  1339. default:
  1340. // TODO(bradfitz): handle more settings? SETTINGS_HEADER_TABLE_SIZE probably.
  1341. cc.vlogf("Unhandled Setting: %v", s)
  1342. }
  1343. return nil
  1344. })
  1345. }
  1346. func (rl *clientConnReadLoop) processWindowUpdate(f *WindowUpdateFrame) error {
  1347. cc := rl.cc
  1348. cs := cc.streamByID(f.StreamID, false)
  1349. if f.StreamID != 0 && cs == nil {
  1350. return nil
  1351. }
  1352. cc.mu.Lock()
  1353. defer cc.mu.Unlock()
  1354. fl := &cc.flow
  1355. if cs != nil {
  1356. fl = &cs.flow
  1357. }
  1358. if !fl.add(int32(f.Increment)) {
  1359. return ConnectionError(ErrCodeFlowControl)
  1360. }
  1361. cc.cond.Broadcast()
  1362. return nil
  1363. }
  1364. func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error {
  1365. cs := rl.cc.streamByID(f.StreamID, true)
  1366. if cs == nil {
  1367. // TODO: return error if server tries to RST_STEAM an idle stream
  1368. return nil
  1369. }
  1370. select {
  1371. case <-cs.peerReset:
  1372. // Already reset.
  1373. // This is the only goroutine
  1374. // which closes this, so there
  1375. // isn't a race.
  1376. default:
  1377. err := StreamError{cs.ID, f.ErrCode}
  1378. cs.resetErr = err
  1379. close(cs.peerReset)
  1380. cs.bufPipe.CloseWithError(err)
  1381. cs.cc.cond.Broadcast() // wake up checkReset via clientStream.awaitFlowControl
  1382. }
  1383. delete(rl.activeRes, cs.ID)
  1384. return nil
  1385. }
  1386. func (rl *clientConnReadLoop) processPing(f *PingFrame) error {
  1387. if f.IsAck() {
  1388. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  1389. // containing this flag."
  1390. return nil
  1391. }
  1392. cc := rl.cc
  1393. cc.wmu.Lock()
  1394. defer cc.wmu.Unlock()
  1395. if err := cc.fr.WritePing(true, f.Data); err != nil {
  1396. return err
  1397. }
  1398. return cc.bw.Flush()
  1399. }
  1400. func (rl *clientConnReadLoop) processPushPromise(f *PushPromiseFrame) error {
  1401. // We told the peer we don't want them.
  1402. // Spec says:
  1403. // "PUSH_PROMISE MUST NOT be sent if the SETTINGS_ENABLE_PUSH
  1404. // setting of the peer endpoint is set to 0. An endpoint that
  1405. // has set this setting and has received acknowledgement MUST
  1406. // treat the receipt of a PUSH_PROMISE frame as a connection
  1407. // error (Section 5.4.1) of type PROTOCOL_ERROR."
  1408. return ConnectionError(ErrCodeProtocol)
  1409. }
  1410. func (cc *ClientConn) writeStreamReset(streamID uint32, code ErrCode, err error) {
  1411. // TODO: do something with err? send it as a debug frame to the peer?
  1412. // But that's only in GOAWAY. Invent a new frame type? Is there one already?
  1413. cc.wmu.Lock()
  1414. cc.fr.WriteRSTStream(streamID, code)
  1415. cc.bw.Flush()
  1416. cc.wmu.Unlock()
  1417. }
  1418. var (
  1419. errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
  1420. errPseudoTrailers = errors.New("http2: invalid pseudo header in trailers")
  1421. )
  1422. func (rl *clientConnReadLoop) checkHeaderField(f hpack.HeaderField) bool {
  1423. if rl.reqMalformed != nil {
  1424. return false
  1425. }
  1426. const headerFieldOverhead = 32 // per spec
  1427. rl.headerListSize += int64(len(f.Name)) + int64(len(f.Value)) + headerFieldOverhead
  1428. if max := rl.cc.t.maxHeaderListSize(); max != 0 && rl.headerListSize > int64(max) {
  1429. rl.hdec.SetEmitEnabled(false)
  1430. rl.reqMalformed = errResponseHeaderListSize
  1431. return false
  1432. }
  1433. if !validHeaderFieldValue(f.Value) {
  1434. rl.reqMalformed = errInvalidHeaderFieldValue
  1435. return false
  1436. }
  1437. isPseudo := strings.HasPrefix(f.Name, ":")
  1438. if isPseudo {
  1439. if rl.sawRegHeader {
  1440. rl.reqMalformed = errors.New("http2: invalid pseudo header after regular header")
  1441. return false
  1442. }
  1443. } else {
  1444. if !validHeaderFieldName(f.Name) {
  1445. rl.reqMalformed = errInvalidHeaderFieldName
  1446. return false
  1447. }
  1448. rl.sawRegHeader = true
  1449. }
  1450. return true
  1451. }
  1452. // onNewHeaderField runs on the readLoop goroutine whenever a new
  1453. // hpack header field is decoded.
  1454. func (rl *clientConnReadLoop) onNewHeaderField(f hpack.HeaderField) {
  1455. cc := rl.cc
  1456. if VerboseLogs {
  1457. cc.logf("http2: Transport decoded %v", f)
  1458. }
  1459. if !rl.checkHeaderField(f) {
  1460. return
  1461. }
  1462. isPseudo := strings.HasPrefix(f.Name, ":")
  1463. if isPseudo {
  1464. switch f.Name {
  1465. case ":status":
  1466. code, err := strconv.Atoi(f.Value)
  1467. if err != nil {
  1468. rl.reqMalformed = errors.New("http2: invalid :status")
  1469. return
  1470. }
  1471. rl.nextRes.Status = f.Value + " " + http.StatusText(code)
  1472. rl.nextRes.StatusCode = code
  1473. default:
  1474. // "Endpoints MUST NOT generate pseudo-header
  1475. // fields other than those defined in this
  1476. // document."
  1477. rl.reqMalformed = fmt.Errorf("http2: unknown response pseudo header %q", f.Name)
  1478. }
  1479. return
  1480. }
  1481. key := http.CanonicalHeaderKey(f.Name)
  1482. if key == "Trailer" {
  1483. t := rl.nextRes.Trailer
  1484. if t == nil {
  1485. t = make(http.Header)
  1486. rl.nextRes.Trailer = t
  1487. }
  1488. foreachHeaderElement(f.Value, func(v string) {
  1489. t[http.CanonicalHeaderKey(v)] = nil
  1490. })
  1491. } else {
  1492. rl.nextRes.Header.Add(key, f.Value)
  1493. }
  1494. }
  1495. func (rl *clientConnReadLoop) onNewTrailerField(cs *clientStream, f hpack.HeaderField) {
  1496. if VerboseLogs {
  1497. rl.cc.logf("http2: Transport decoded trailer %v", f)
  1498. }
  1499. if !rl.checkHeaderField(f) {
  1500. return
  1501. }
  1502. if strings.HasPrefix(f.Name, ":") {
  1503. // Pseudo-header fields MUST NOT appear in
  1504. // trailers. Endpoints MUST treat a request or
  1505. // response that contains undefined or invalid
  1506. // pseudo-header fields as malformed.
  1507. rl.reqMalformed = errPseudoTrailers
  1508. return
  1509. }
  1510. key := http.CanonicalHeaderKey(f.Name)
  1511. // The spec says one must predeclare their trailers but in practice
  1512. // popular users (which is to say the only user we found) do not so we
  1513. // violate the spec and accept all of them.
  1514. const acceptAllTrailers = true
  1515. if _, ok := (*cs.resTrailer)[key]; ok || acceptAllTrailers {
  1516. if cs.trailer == nil {
  1517. cs.trailer = make(http.Header)
  1518. }
  1519. cs.trailer[key] = append(cs.trailer[key], f.Value)
  1520. }
  1521. }
  1522. func (cc *ClientConn) logf(format string, args ...interface{}) {
  1523. cc.t.logf(format, args...)
  1524. }
  1525. func (cc *ClientConn) vlogf(format string, args ...interface{}) {
  1526. cc.t.vlogf(format, args...)
  1527. }
  1528. func (t *Transport) vlogf(format string, args ...interface{}) {
  1529. if VerboseLogs {
  1530. t.logf(format, args...)
  1531. }
  1532. }
  1533. func (t *Transport) logf(format string, args ...interface{}) {
  1534. log.Printf(format, args...)
  1535. }
  1536. var noBody io.ReadCloser = ioutil.NopCloser(bytes.NewReader(nil))
  1537. func strSliceContains(ss []string, s string) bool {
  1538. for _, v := range ss {
  1539. if v == s {
  1540. return true
  1541. }
  1542. }
  1543. return false
  1544. }
  1545. type erringRoundTripper struct{ err error }
  1546. func (rt erringRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return nil, rt.err }
  1547. // gzipReader wraps a response body so it can lazily
  1548. // call gzip.NewReader on the first call to Read
  1549. type gzipReader struct {
  1550. body io.ReadCloser // underlying Response.Body
  1551. zr *gzip.Reader // lazily-initialized gzip reader
  1552. zerr error // sticky error
  1553. }
  1554. func (gz *gzipReader) Read(p []byte) (n int, err error) {
  1555. if gz.zerr != nil {
  1556. return 0, gz.zerr
  1557. }
  1558. if gz.zr == nil {
  1559. gz.zr, err = gzip.NewReader(gz.body)
  1560. if err != nil {
  1561. gz.zerr = err
  1562. return 0, err
  1563. }
  1564. }
  1565. return gz.zr.Read(p)
  1566. }
  1567. func (gz *gzipReader) Close() error {
  1568. return gz.body.Close()
  1569. }
  1570. type errorReader struct{ err error }
  1571. func (r errorReader) Read(p []byte) (int, error) { return 0, r.err }