transport.go 54 KB

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