server.go 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620
  1. // Copyright 2014 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. // TODO: turn off the serve goroutine when idle, so
  5. // an idle conn only has the readFrames goroutine active. (which could
  6. // also be optimized probably to pin less memory in crypto/tls). This
  7. // would involve tracking when the serve goroutine is active (atomic
  8. // int32 read/CAS probably?) and starting it up when frames arrive,
  9. // and shutting it down when all handlers exit. the occasional PING
  10. // packets could use time.AfterFunc to call sc.wakeStartServeLoop()
  11. // (which is a no-op if already running) and then queue the PING write
  12. // as normal. The serve loop would then exit in most cases (if no
  13. // Handlers running) and not be woken up again until the PING packet
  14. // returns.
  15. // TODO (maybe): add a mechanism for Handlers to going into
  16. // half-closed-local mode (rw.(io.Closer) test?) but not exit their
  17. // handler, and continue to be able to read from the
  18. // Request.Body. This would be a somewhat semantic change from HTTP/1
  19. // (or at least what we expose in net/http), so I'd probably want to
  20. // add it there too. For now, this package says that returning from
  21. // the Handler ServeHTTP function means you're both done reading and
  22. // done writing, without a way to stop just one or the other.
  23. package http2
  24. import (
  25. "bufio"
  26. "bytes"
  27. "crypto/tls"
  28. "errors"
  29. "fmt"
  30. "io"
  31. "log"
  32. "math"
  33. "net"
  34. "net/http"
  35. "net/textproto"
  36. "net/url"
  37. "os"
  38. "reflect"
  39. "runtime"
  40. "strconv"
  41. "strings"
  42. "sync"
  43. "time"
  44. "golang.org/x/net/http2/hpack"
  45. )
  46. const (
  47. prefaceTimeout = 10 * time.Second
  48. firstSettingsTimeout = 2 * time.Second // should be in-flight with preface anyway
  49. handlerChunkWriteSize = 4 << 10
  50. defaultMaxStreams = 250 // TODO: make this 100 as the GFE seems to?
  51. )
  52. var (
  53. errClientDisconnected = errors.New("client disconnected")
  54. errClosedBody = errors.New("body closed by handler")
  55. errHandlerComplete = errors.New("http2: request body closed due to handler exiting")
  56. errStreamClosed = errors.New("http2: stream closed")
  57. )
  58. var responseWriterStatePool = sync.Pool{
  59. New: func() interface{} {
  60. rws := &responseWriterState{}
  61. rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize)
  62. return rws
  63. },
  64. }
  65. // Test hooks.
  66. var (
  67. testHookOnConn func()
  68. testHookGetServerConn func(*serverConn)
  69. testHookOnPanicMu *sync.Mutex // nil except in tests
  70. testHookOnPanic func(sc *serverConn, panicVal interface{}) (rePanic bool)
  71. )
  72. // Server is an HTTP/2 server.
  73. type Server struct {
  74. // MaxHandlers limits the number of http.Handler ServeHTTP goroutines
  75. // which may run at a time over all connections.
  76. // Negative or zero no limit.
  77. // TODO: implement
  78. MaxHandlers int
  79. // MaxConcurrentStreams optionally specifies the number of
  80. // concurrent streams that each client may have open at a
  81. // time. This is unrelated to the number of http.Handler goroutines
  82. // which may be active globally, which is MaxHandlers.
  83. // If zero, MaxConcurrentStreams defaults to at least 100, per
  84. // the HTTP/2 spec's recommendations.
  85. MaxConcurrentStreams uint32
  86. // MaxReadFrameSize optionally specifies the largest frame
  87. // this server is willing to read. A valid value is between
  88. // 16k and 16M, inclusive. If zero or otherwise invalid, a
  89. // default value is used.
  90. MaxReadFrameSize uint32
  91. // PermitProhibitedCipherSuites, if true, permits the use of
  92. // cipher suites prohibited by the HTTP/2 spec.
  93. PermitProhibitedCipherSuites bool
  94. // IdleTimeout specifies how long until idle clients should be
  95. // closed with a GOAWAY frame. PING frames are not considered
  96. // activity for the purposes of IdleTimeout.
  97. IdleTimeout time.Duration
  98. // NewWriteScheduler constructs a write scheduler for a connection.
  99. // If nil, a default scheduler is chosen.
  100. NewWriteScheduler func() WriteScheduler
  101. }
  102. func (s *Server) maxReadFrameSize() uint32 {
  103. if v := s.MaxReadFrameSize; v >= minMaxFrameSize && v <= maxFrameSize {
  104. return v
  105. }
  106. return defaultMaxReadFrameSize
  107. }
  108. func (s *Server) maxConcurrentStreams() uint32 {
  109. if v := s.MaxConcurrentStreams; v > 0 {
  110. return v
  111. }
  112. return defaultMaxStreams
  113. }
  114. // List of funcs for ConfigureServer to run. Both h1 and h2 are guaranteed
  115. // to be non-nil.
  116. var configServerFuncs []func(h1 *http.Server, h2 *Server) error
  117. // ConfigureServer adds HTTP/2 support to a net/http Server.
  118. //
  119. // The configuration conf may be nil.
  120. //
  121. // ConfigureServer must be called before s begins serving.
  122. func ConfigureServer(s *http.Server, conf *Server) error {
  123. if s == nil {
  124. panic("nil *http.Server")
  125. }
  126. if conf == nil {
  127. conf = new(Server)
  128. }
  129. if err := configureServer18(s, conf); err != nil {
  130. return err
  131. }
  132. if s.TLSConfig == nil {
  133. s.TLSConfig = new(tls.Config)
  134. } else if s.TLSConfig.CipherSuites != nil {
  135. // If they already provided a CipherSuite list, return
  136. // an error if it has a bad order or is missing
  137. // ECDHE_RSA_WITH_AES_128_GCM_SHA256.
  138. const requiredCipher = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  139. haveRequired := false
  140. sawBad := false
  141. for i, cs := range s.TLSConfig.CipherSuites {
  142. if cs == requiredCipher {
  143. haveRequired = true
  144. }
  145. if isBadCipher(cs) {
  146. sawBad = true
  147. } else if sawBad {
  148. return fmt.Errorf("http2: TLSConfig.CipherSuites index %d contains an HTTP/2-approved cipher suite (%#04x), but it comes after unapproved cipher suites. With this configuration, clients that don't support previous, approved cipher suites may be given an unapproved one and reject the connection.", i, cs)
  149. }
  150. }
  151. if !haveRequired {
  152. return fmt.Errorf("http2: TLSConfig.CipherSuites is missing HTTP/2-required TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256")
  153. }
  154. }
  155. // Note: not setting MinVersion to tls.VersionTLS12,
  156. // as we don't want to interfere with HTTP/1.1 traffic
  157. // on the user's server. We enforce TLS 1.2 later once
  158. // we accept a connection. Ideally this should be done
  159. // during next-proto selection, but using TLS <1.2 with
  160. // HTTP/2 is still the client's bug.
  161. s.TLSConfig.PreferServerCipherSuites = true
  162. haveNPN := false
  163. for _, p := range s.TLSConfig.NextProtos {
  164. if p == NextProtoTLS {
  165. haveNPN = true
  166. break
  167. }
  168. }
  169. if !haveNPN {
  170. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, NextProtoTLS)
  171. }
  172. // h2-14 is temporary (as of 2015-03-05) while we wait for all browsers
  173. // to switch to "h2".
  174. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, "h2-14")
  175. if s.TLSNextProto == nil {
  176. s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
  177. }
  178. protoHandler := func(hs *http.Server, c *tls.Conn, h http.Handler) {
  179. if testHookOnConn != nil {
  180. testHookOnConn()
  181. }
  182. conf.ServeConn(c, &ServeConnOpts{
  183. Handler: h,
  184. BaseConfig: hs,
  185. })
  186. }
  187. s.TLSNextProto[NextProtoTLS] = protoHandler
  188. s.TLSNextProto["h2-14"] = protoHandler // temporary; see above.
  189. return nil
  190. }
  191. // ServeConnOpts are options for the Server.ServeConn method.
  192. type ServeConnOpts struct {
  193. // BaseConfig optionally sets the base configuration
  194. // for values. If nil, defaults are used.
  195. BaseConfig *http.Server
  196. // Handler specifies which handler to use for processing
  197. // requests. If nil, BaseConfig.Handler is used. If BaseConfig
  198. // or BaseConfig.Handler is nil, http.DefaultServeMux is used.
  199. Handler http.Handler
  200. }
  201. func (o *ServeConnOpts) baseConfig() *http.Server {
  202. if o != nil && o.BaseConfig != nil {
  203. return o.BaseConfig
  204. }
  205. return new(http.Server)
  206. }
  207. func (o *ServeConnOpts) handler() http.Handler {
  208. if o != nil {
  209. if o.Handler != nil {
  210. return o.Handler
  211. }
  212. if o.BaseConfig != nil && o.BaseConfig.Handler != nil {
  213. return o.BaseConfig.Handler
  214. }
  215. }
  216. return http.DefaultServeMux
  217. }
  218. // ServeConn serves HTTP/2 requests on the provided connection and
  219. // blocks until the connection is no longer readable.
  220. //
  221. // ServeConn starts speaking HTTP/2 assuming that c has not had any
  222. // reads or writes. It writes its initial settings frame and expects
  223. // to be able to read the preface and settings frame from the
  224. // client. If c has a ConnectionState method like a *tls.Conn, the
  225. // ConnectionState is used to verify the TLS ciphersuite and to set
  226. // the Request.TLS field in Handlers.
  227. //
  228. // ServeConn does not support h2c by itself. Any h2c support must be
  229. // implemented in terms of providing a suitably-behaving net.Conn.
  230. //
  231. // The opts parameter is optional. If nil, default values are used.
  232. func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) {
  233. baseCtx, cancel := serverConnBaseContext(c, opts)
  234. defer cancel()
  235. sc := &serverConn{
  236. srv: s,
  237. hs: opts.baseConfig(),
  238. conn: c,
  239. baseCtx: baseCtx,
  240. remoteAddrStr: c.RemoteAddr().String(),
  241. bw: newBufferedWriter(c),
  242. handler: opts.handler(),
  243. streams: make(map[uint32]*stream),
  244. readFrameCh: make(chan readFrameResult),
  245. wantWriteFrameCh: make(chan FrameWriteRequest, 8),
  246. wantStartPushCh: make(chan startPushRequest, 8),
  247. wroteFrameCh: make(chan frameWriteResult, 1), // buffered; one send in writeFrameAsync
  248. bodyReadCh: make(chan bodyReadMsg), // buffering doesn't matter either way
  249. doneServing: make(chan struct{}),
  250. clientMaxStreams: math.MaxUint32, // Section 6.5.2: "Initially, there is no limit to this value"
  251. advMaxStreams: s.maxConcurrentStreams(),
  252. initialWindowSize: initialWindowSize,
  253. maxFrameSize: initialMaxFrameSize,
  254. headerTableSize: initialHeaderTableSize,
  255. serveG: newGoroutineLock(),
  256. pushEnabled: true,
  257. }
  258. if s.NewWriteScheduler != nil {
  259. sc.writeSched = s.NewWriteScheduler()
  260. } else {
  261. sc.writeSched = NewRandomWriteScheduler()
  262. }
  263. sc.flow.add(initialWindowSize)
  264. sc.inflow.add(initialWindowSize)
  265. sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
  266. fr := NewFramer(sc.bw, c)
  267. fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil)
  268. fr.MaxHeaderListSize = sc.maxHeaderListSize()
  269. fr.SetMaxReadFrameSize(s.maxReadFrameSize())
  270. sc.framer = fr
  271. if tc, ok := c.(connectionStater); ok {
  272. sc.tlsState = new(tls.ConnectionState)
  273. *sc.tlsState = tc.ConnectionState()
  274. // 9.2 Use of TLS Features
  275. // An implementation of HTTP/2 over TLS MUST use TLS
  276. // 1.2 or higher with the restrictions on feature set
  277. // and cipher suite described in this section. Due to
  278. // implementation limitations, it might not be
  279. // possible to fail TLS negotiation. An endpoint MUST
  280. // immediately terminate an HTTP/2 connection that
  281. // does not meet the TLS requirements described in
  282. // this section with a connection error (Section
  283. // 5.4.1) of type INADEQUATE_SECURITY.
  284. if sc.tlsState.Version < tls.VersionTLS12 {
  285. sc.rejectConn(ErrCodeInadequateSecurity, "TLS version too low")
  286. return
  287. }
  288. if sc.tlsState.ServerName == "" {
  289. // Client must use SNI, but we don't enforce that anymore,
  290. // since it was causing problems when connecting to bare IP
  291. // addresses during development.
  292. //
  293. // TODO: optionally enforce? Or enforce at the time we receive
  294. // a new request, and verify the the ServerName matches the :authority?
  295. // But that precludes proxy situations, perhaps.
  296. //
  297. // So for now, do nothing here again.
  298. }
  299. if !s.PermitProhibitedCipherSuites && isBadCipher(sc.tlsState.CipherSuite) {
  300. // "Endpoints MAY choose to generate a connection error
  301. // (Section 5.4.1) of type INADEQUATE_SECURITY if one of
  302. // the prohibited cipher suites are negotiated."
  303. //
  304. // We choose that. In my opinion, the spec is weak
  305. // here. It also says both parties must support at least
  306. // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 so there's no
  307. // excuses here. If we really must, we could allow an
  308. // "AllowInsecureWeakCiphers" option on the server later.
  309. // Let's see how it plays out first.
  310. sc.rejectConn(ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite))
  311. return
  312. }
  313. }
  314. if hook := testHookGetServerConn; hook != nil {
  315. hook(sc)
  316. }
  317. sc.serve()
  318. }
  319. func (sc *serverConn) rejectConn(err ErrCode, debug string) {
  320. sc.vlogf("http2: server rejecting conn: %v, %s", err, debug)
  321. // ignoring errors. hanging up anyway.
  322. sc.framer.WriteGoAway(0, err, []byte(debug))
  323. sc.bw.Flush()
  324. sc.conn.Close()
  325. }
  326. type serverConn struct {
  327. // Immutable:
  328. srv *Server
  329. hs *http.Server
  330. conn net.Conn
  331. bw *bufferedWriter // writing to conn
  332. handler http.Handler
  333. baseCtx contextContext
  334. framer *Framer
  335. doneServing chan struct{} // closed when serverConn.serve ends
  336. readFrameCh chan readFrameResult // written by serverConn.readFrames
  337. wantWriteFrameCh chan FrameWriteRequest // from handlers -> serve
  338. wantStartPushCh chan startPushRequest // from handlers -> serve
  339. wroteFrameCh chan frameWriteResult // from writeFrameAsync -> serve, tickles more frame writes
  340. bodyReadCh chan bodyReadMsg // from handlers -> serve
  341. testHookCh chan func(int) // code to run on the serve loop
  342. flow flow // conn-wide (not stream-specific) outbound flow control
  343. inflow flow // conn-wide inbound flow control
  344. tlsState *tls.ConnectionState // shared by all handlers, like net/http
  345. remoteAddrStr string
  346. writeSched WriteScheduler
  347. // Everything following is owned by the serve loop; use serveG.check():
  348. serveG goroutineLock // used to verify funcs are on serve()
  349. pushEnabled bool
  350. sawFirstSettings bool // got the initial SETTINGS frame after the preface
  351. needToSendSettingsAck bool
  352. unackedSettings int // how many SETTINGS have we sent without ACKs?
  353. clientMaxStreams uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)
  354. advMaxStreams uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client
  355. curClientStreams uint32 // number of open streams initiated by the client
  356. curPushedStreams uint32 // number of open streams initiated by server push
  357. maxStreamID uint32 // max ever seen from client
  358. maxPushPromiseID uint32 // ID of the last push promise, or 0 if there have been no pushes
  359. streams map[uint32]*stream
  360. initialWindowSize int32
  361. maxFrameSize int32
  362. headerTableSize uint32
  363. peerMaxHeaderListSize uint32 // zero means unknown (default)
  364. canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case
  365. writingFrame bool // started writing a frame (on serve goroutine or separate)
  366. writingFrameAsync bool // started a frame on its own goroutine but haven't heard back on wroteFrameCh
  367. needsFrameFlush bool // last frame write wasn't a flush
  368. inGoAway bool // we've started to or sent GOAWAY
  369. inFrameScheduleLoop bool // whether we're in the scheduleFrameWrite loop
  370. needToSendGoAway bool // we need to schedule a GOAWAY frame write
  371. goAwayCode ErrCode
  372. shutdownTimerCh <-chan time.Time // nil until used
  373. shutdownTimer *time.Timer // nil until used
  374. idleTimer *time.Timer // nil if unused
  375. idleTimerCh <-chan time.Time // nil if unused
  376. // Owned by the writeFrameAsync goroutine:
  377. headerWriteBuf bytes.Buffer
  378. hpackEncoder *hpack.Encoder
  379. }
  380. func (sc *serverConn) maxHeaderListSize() uint32 {
  381. n := sc.hs.MaxHeaderBytes
  382. if n <= 0 {
  383. n = http.DefaultMaxHeaderBytes
  384. }
  385. // http2's count is in a slightly different unit and includes 32 bytes per pair.
  386. // So, take the net/http.Server value and pad it up a bit, assuming 10 headers.
  387. const perFieldOverhead = 32 // per http2 spec
  388. const typicalHeaders = 10 // conservative
  389. return uint32(n + typicalHeaders*perFieldOverhead)
  390. }
  391. // stream represents a stream. This is the minimal metadata needed by
  392. // the serve goroutine. Most of the actual stream state is owned by
  393. // the http.Handler's goroutine in the responseWriter. Because the
  394. // responseWriter's responseWriterState is recycled at the end of a
  395. // handler, this struct intentionally has no pointer to the
  396. // *responseWriter{,State} itself, as the Handler ending nils out the
  397. // responseWriter's state field.
  398. type stream struct {
  399. // immutable:
  400. sc *serverConn
  401. id uint32
  402. body *pipe // non-nil if expecting DATA frames
  403. cw closeWaiter // closed wait stream transitions to closed state
  404. ctx contextContext
  405. cancelCtx func()
  406. // owned by serverConn's serve loop:
  407. bodyBytes int64 // body bytes seen so far
  408. declBodyBytes int64 // or -1 if undeclared
  409. flow flow // limits writing from Handler to client
  410. inflow flow // what the client is allowed to POST/etc to us
  411. parent *stream // or nil
  412. numTrailerValues int64
  413. weight uint8
  414. state streamState
  415. sentReset bool // only true once detached from streams map
  416. gotReset bool // only true once detacted from streams map
  417. gotTrailerHeader bool // HEADER frame for trailers was seen
  418. wroteHeaders bool // whether we wrote headers (not status 100)
  419. reqBuf []byte // if non-nil, body pipe buffer to return later at EOF
  420. trailer http.Header // accumulated trailers
  421. reqTrailer http.Header // handler's Request.Trailer
  422. }
  423. func (sc *serverConn) Framer() *Framer { return sc.framer }
  424. func (sc *serverConn) CloseConn() error { return sc.conn.Close() }
  425. func (sc *serverConn) Flush() error { return sc.bw.Flush() }
  426. func (sc *serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) {
  427. return sc.hpackEncoder, &sc.headerWriteBuf
  428. }
  429. func (sc *serverConn) state(streamID uint32) (streamState, *stream) {
  430. sc.serveG.check()
  431. // http://tools.ietf.org/html/rfc7540#section-5.1
  432. if st, ok := sc.streams[streamID]; ok {
  433. return st.state, st
  434. }
  435. // "The first use of a new stream identifier implicitly closes all
  436. // streams in the "idle" state that might have been initiated by
  437. // that peer with a lower-valued stream identifier. For example, if
  438. // a client sends a HEADERS frame on stream 7 without ever sending a
  439. // frame on stream 5, then stream 5 transitions to the "closed"
  440. // state when the first frame for stream 7 is sent or received."
  441. if streamID <= sc.maxStreamID {
  442. return stateClosed, nil
  443. }
  444. return stateIdle, nil
  445. }
  446. // setConnState calls the net/http ConnState hook for this connection, if configured.
  447. // Note that the net/http package does StateNew and StateClosed for us.
  448. // There is currently no plan for StateHijacked or hijacking HTTP/2 connections.
  449. func (sc *serverConn) setConnState(state http.ConnState) {
  450. if sc.hs.ConnState != nil {
  451. sc.hs.ConnState(sc.conn, state)
  452. }
  453. }
  454. func (sc *serverConn) vlogf(format string, args ...interface{}) {
  455. if VerboseLogs {
  456. sc.logf(format, args...)
  457. }
  458. }
  459. func (sc *serverConn) logf(format string, args ...interface{}) {
  460. if lg := sc.hs.ErrorLog; lg != nil {
  461. lg.Printf(format, args...)
  462. } else {
  463. log.Printf(format, args...)
  464. }
  465. }
  466. // errno returns v's underlying uintptr, else 0.
  467. //
  468. // TODO: remove this helper function once http2 can use build
  469. // tags. See comment in isClosedConnError.
  470. func errno(v error) uintptr {
  471. if rv := reflect.ValueOf(v); rv.Kind() == reflect.Uintptr {
  472. return uintptr(rv.Uint())
  473. }
  474. return 0
  475. }
  476. // isClosedConnError reports whether err is an error from use of a closed
  477. // network connection.
  478. func isClosedConnError(err error) bool {
  479. if err == nil {
  480. return false
  481. }
  482. // TODO: remove this string search and be more like the Windows
  483. // case below. That might involve modifying the standard library
  484. // to return better error types.
  485. str := err.Error()
  486. if strings.Contains(str, "use of closed network connection") {
  487. return true
  488. }
  489. // TODO(bradfitz): x/tools/cmd/bundle doesn't really support
  490. // build tags, so I can't make an http2_windows.go file with
  491. // Windows-specific stuff. Fix that and move this, once we
  492. // have a way to bundle this into std's net/http somehow.
  493. if runtime.GOOS == "windows" {
  494. if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
  495. if se, ok := oe.Err.(*os.SyscallError); ok && se.Syscall == "wsarecv" {
  496. const WSAECONNABORTED = 10053
  497. const WSAECONNRESET = 10054
  498. if n := errno(se.Err); n == WSAECONNRESET || n == WSAECONNABORTED {
  499. return true
  500. }
  501. }
  502. }
  503. }
  504. return false
  505. }
  506. func (sc *serverConn) condlogf(err error, format string, args ...interface{}) {
  507. if err == nil {
  508. return
  509. }
  510. if err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) {
  511. // Boring, expected errors.
  512. sc.vlogf(format, args...)
  513. } else {
  514. sc.logf(format, args...)
  515. }
  516. }
  517. func (sc *serverConn) canonicalHeader(v string) string {
  518. sc.serveG.check()
  519. cv, ok := commonCanonHeader[v]
  520. if ok {
  521. return cv
  522. }
  523. cv, ok = sc.canonHeader[v]
  524. if ok {
  525. return cv
  526. }
  527. if sc.canonHeader == nil {
  528. sc.canonHeader = make(map[string]string)
  529. }
  530. cv = http.CanonicalHeaderKey(v)
  531. sc.canonHeader[v] = cv
  532. return cv
  533. }
  534. type readFrameResult struct {
  535. f Frame // valid until readMore is called
  536. err error
  537. // readMore should be called once the consumer no longer needs or
  538. // retains f. After readMore, f is invalid and more frames can be
  539. // read.
  540. readMore func()
  541. }
  542. // readFrames is the loop that reads incoming frames.
  543. // It takes care to only read one frame at a time, blocking until the
  544. // consumer is done with the frame.
  545. // It's run on its own goroutine.
  546. func (sc *serverConn) readFrames() {
  547. gate := make(gate)
  548. gateDone := gate.Done
  549. for {
  550. f, err := sc.framer.ReadFrame()
  551. select {
  552. case sc.readFrameCh <- readFrameResult{f, err, gateDone}:
  553. case <-sc.doneServing:
  554. return
  555. }
  556. select {
  557. case <-gate:
  558. case <-sc.doneServing:
  559. return
  560. }
  561. if terminalReadFrameError(err) {
  562. return
  563. }
  564. }
  565. }
  566. // frameWriteResult is the message passed from writeFrameAsync to the serve goroutine.
  567. type frameWriteResult struct {
  568. wr FrameWriteRequest // what was written (or attempted)
  569. err error // result of the writeFrame call
  570. }
  571. // writeFrameAsync runs in its own goroutine and writes a single frame
  572. // and then reports when it's done.
  573. // At most one goroutine can be running writeFrameAsync at a time per
  574. // serverConn.
  575. func (sc *serverConn) writeFrameAsync(wr FrameWriteRequest) {
  576. err := wr.write.writeFrame(sc)
  577. sc.wroteFrameCh <- frameWriteResult{wr, err}
  578. }
  579. func (sc *serverConn) closeAllStreamsOnConnClose() {
  580. sc.serveG.check()
  581. for _, st := range sc.streams {
  582. sc.closeStream(st, errClientDisconnected)
  583. }
  584. }
  585. func (sc *serverConn) stopShutdownTimer() {
  586. sc.serveG.check()
  587. if t := sc.shutdownTimer; t != nil {
  588. t.Stop()
  589. }
  590. }
  591. func (sc *serverConn) notePanic() {
  592. // Note: this is for serverConn.serve panicking, not http.Handler code.
  593. if testHookOnPanicMu != nil {
  594. testHookOnPanicMu.Lock()
  595. defer testHookOnPanicMu.Unlock()
  596. }
  597. if testHookOnPanic != nil {
  598. if e := recover(); e != nil {
  599. if testHookOnPanic(sc, e) {
  600. panic(e)
  601. }
  602. }
  603. }
  604. }
  605. func (sc *serverConn) serve() {
  606. sc.serveG.check()
  607. defer sc.notePanic()
  608. defer sc.conn.Close()
  609. defer sc.closeAllStreamsOnConnClose()
  610. defer sc.stopShutdownTimer()
  611. defer close(sc.doneServing) // unblocks handlers trying to send
  612. if VerboseLogs {
  613. sc.vlogf("http2: server connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
  614. }
  615. sc.writeFrame(FrameWriteRequest{
  616. write: writeSettings{
  617. {SettingMaxFrameSize, sc.srv.maxReadFrameSize()},
  618. {SettingMaxConcurrentStreams, sc.advMaxStreams},
  619. {SettingMaxHeaderListSize, sc.maxHeaderListSize()},
  620. // TODO: more actual settings, notably
  621. // SettingInitialWindowSize, but then we also
  622. // want to bump up the conn window size the
  623. // same amount here right after the settings
  624. },
  625. })
  626. sc.unackedSettings++
  627. if err := sc.readPreface(); err != nil {
  628. sc.condlogf(err, "http2: server: error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
  629. return
  630. }
  631. // Now that we've got the preface, get us out of the
  632. // "StateNew" state. We can't go directly to idle, though.
  633. // Active means we read some data and anticipate a request. We'll
  634. // do another Active when we get a HEADERS frame.
  635. sc.setConnState(http.StateActive)
  636. sc.setConnState(http.StateIdle)
  637. if sc.srv.IdleTimeout != 0 {
  638. sc.idleTimer = time.NewTimer(sc.srv.IdleTimeout)
  639. defer sc.idleTimer.Stop()
  640. sc.idleTimerCh = sc.idleTimer.C
  641. }
  642. go sc.readFrames() // closed by defer sc.conn.Close above
  643. settingsTimer := time.NewTimer(firstSettingsTimeout)
  644. loopNum := 0
  645. for {
  646. loopNum++
  647. select {
  648. case wr := <-sc.wantWriteFrameCh:
  649. sc.writeFrame(wr)
  650. case spr := <-sc.wantStartPushCh:
  651. sc.startPush(spr)
  652. case res := <-sc.wroteFrameCh:
  653. sc.wroteFrame(res)
  654. case res := <-sc.readFrameCh:
  655. if !sc.processFrameFromReader(res) {
  656. return
  657. }
  658. res.readMore()
  659. if settingsTimer.C != nil {
  660. settingsTimer.Stop()
  661. settingsTimer.C = nil
  662. }
  663. case m := <-sc.bodyReadCh:
  664. sc.noteBodyRead(m.st, m.n)
  665. case <-settingsTimer.C:
  666. sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
  667. return
  668. case <-sc.shutdownTimerCh:
  669. sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
  670. return
  671. case <-sc.idleTimerCh:
  672. sc.vlogf("connection is idle")
  673. sc.goAway(ErrCodeNo)
  674. case fn := <-sc.testHookCh:
  675. fn(loopNum)
  676. }
  677. }
  678. }
  679. // readPreface reads the ClientPreface greeting from the peer
  680. // or returns an error on timeout or an invalid greeting.
  681. func (sc *serverConn) readPreface() error {
  682. errc := make(chan error, 1)
  683. go func() {
  684. // Read the client preface
  685. buf := make([]byte, len(ClientPreface))
  686. if _, err := io.ReadFull(sc.conn, buf); err != nil {
  687. errc <- err
  688. } else if !bytes.Equal(buf, clientPreface) {
  689. errc <- fmt.Errorf("bogus greeting %q", buf)
  690. } else {
  691. errc <- nil
  692. }
  693. }()
  694. timer := time.NewTimer(prefaceTimeout) // TODO: configurable on *Server?
  695. defer timer.Stop()
  696. select {
  697. case <-timer.C:
  698. return errors.New("timeout waiting for client preface")
  699. case err := <-errc:
  700. if err == nil {
  701. if VerboseLogs {
  702. sc.vlogf("http2: server: client %v said hello", sc.conn.RemoteAddr())
  703. }
  704. }
  705. return err
  706. }
  707. }
  708. var errChanPool = sync.Pool{
  709. New: func() interface{} { return make(chan error, 1) },
  710. }
  711. var writeDataPool = sync.Pool{
  712. New: func() interface{} { return new(writeData) },
  713. }
  714. // writeDataFromHandler writes DATA response frames from a handler on
  715. // the given stream.
  716. func (sc *serverConn) writeDataFromHandler(stream *stream, data []byte, endStream bool) error {
  717. ch := errChanPool.Get().(chan error)
  718. writeArg := writeDataPool.Get().(*writeData)
  719. *writeArg = writeData{stream.id, data, endStream}
  720. err := sc.writeFrameFromHandler(FrameWriteRequest{
  721. write: writeArg,
  722. stream: stream,
  723. done: ch,
  724. })
  725. if err != nil {
  726. return err
  727. }
  728. var frameWriteDone bool // the frame write is done (successfully or not)
  729. select {
  730. case err = <-ch:
  731. frameWriteDone = true
  732. case <-sc.doneServing:
  733. return errClientDisconnected
  734. case <-stream.cw:
  735. // If both ch and stream.cw were ready (as might
  736. // happen on the final Write after an http.Handler
  737. // ends), prefer the write result. Otherwise this
  738. // might just be us successfully closing the stream.
  739. // The writeFrameAsync and serve goroutines guarantee
  740. // that the ch send will happen before the stream.cw
  741. // close.
  742. select {
  743. case err = <-ch:
  744. frameWriteDone = true
  745. default:
  746. return errStreamClosed
  747. }
  748. }
  749. errChanPool.Put(ch)
  750. if frameWriteDone {
  751. writeDataPool.Put(writeArg)
  752. }
  753. return err
  754. }
  755. // writeFrameFromHandler sends wr to sc.wantWriteFrameCh, but aborts
  756. // if the connection has gone away.
  757. //
  758. // This must not be run from the serve goroutine itself, else it might
  759. // deadlock writing to sc.wantWriteFrameCh (which is only mildly
  760. // buffered and is read by serve itself). If you're on the serve
  761. // goroutine, call writeFrame instead.
  762. func (sc *serverConn) writeFrameFromHandler(wr FrameWriteRequest) error {
  763. sc.serveG.checkNotOn() // NOT
  764. select {
  765. case sc.wantWriteFrameCh <- wr:
  766. return nil
  767. case <-sc.doneServing:
  768. // Serve loop is gone.
  769. // Client has closed their connection to the server.
  770. return errClientDisconnected
  771. }
  772. }
  773. // writeFrame schedules a frame to write and sends it if there's nothing
  774. // already being written.
  775. //
  776. // There is no pushback here (the serve goroutine never blocks). It's
  777. // the http.Handlers that block, waiting for their previous frames to
  778. // make it onto the wire
  779. //
  780. // If you're not on the serve goroutine, use writeFrameFromHandler instead.
  781. func (sc *serverConn) writeFrame(wr FrameWriteRequest) {
  782. sc.serveG.check()
  783. var ignoreWrite bool
  784. // Don't send a 100-continue response if we've already sent headers.
  785. // See golang.org/issue/14030.
  786. switch wr.write.(type) {
  787. case *writeResHeaders:
  788. wr.stream.wroteHeaders = true
  789. case write100ContinueHeadersFrame:
  790. if wr.stream.wroteHeaders {
  791. ignoreWrite = true
  792. }
  793. }
  794. if !ignoreWrite {
  795. sc.writeSched.Push(wr)
  796. }
  797. sc.scheduleFrameWrite()
  798. }
  799. // startFrameWrite starts a goroutine to write wr (in a separate
  800. // goroutine since that might block on the network), and updates the
  801. // serve goroutine's state about the world, updated from info in wr.
  802. func (sc *serverConn) startFrameWrite(wr FrameWriteRequest) {
  803. sc.serveG.check()
  804. if sc.writingFrame {
  805. panic("internal error: can only be writing one frame at a time")
  806. }
  807. st := wr.stream
  808. if st != nil {
  809. switch st.state {
  810. case stateHalfClosedLocal:
  811. panic("internal error: attempt to send frame on half-closed-local stream")
  812. case stateClosed:
  813. if st.sentReset || st.gotReset {
  814. // Skip this frame.
  815. sc.scheduleFrameWrite()
  816. return
  817. }
  818. panic(fmt.Sprintf("internal error: attempt to send a write %v on a closed stream", wr))
  819. }
  820. }
  821. if wpp, ok := wr.write.(*writePushPromise); ok {
  822. var err error
  823. wpp.promisedID, err = wpp.allocatePromisedID()
  824. if err != nil {
  825. sc.writingFrameAsync = false
  826. if wr.done != nil {
  827. wr.done <- err
  828. }
  829. return
  830. }
  831. }
  832. sc.writingFrame = true
  833. sc.needsFrameFlush = true
  834. if wr.write.staysWithinBuffer(sc.bw.Available()) {
  835. sc.writingFrameAsync = false
  836. err := wr.write.writeFrame(sc)
  837. sc.wroteFrame(frameWriteResult{wr, err})
  838. } else {
  839. sc.writingFrameAsync = true
  840. go sc.writeFrameAsync(wr)
  841. }
  842. }
  843. // errHandlerPanicked is the error given to any callers blocked in a read from
  844. // Request.Body when the main goroutine panics. Since most handlers read in the
  845. // the main ServeHTTP goroutine, this will show up rarely.
  846. var errHandlerPanicked = errors.New("http2: handler panicked")
  847. // wroteFrame is called on the serve goroutine with the result of
  848. // whatever happened on writeFrameAsync.
  849. func (sc *serverConn) wroteFrame(res frameWriteResult) {
  850. sc.serveG.check()
  851. if !sc.writingFrame {
  852. panic("internal error: expected to be already writing a frame")
  853. }
  854. sc.writingFrame = false
  855. sc.writingFrameAsync = false
  856. wr := res.wr
  857. st := wr.stream
  858. closeStream := endsStream(wr.write)
  859. if _, ok := wr.write.(handlerPanicRST); ok {
  860. sc.closeStream(st, errHandlerPanicked)
  861. }
  862. // Reply (if requested) to the blocked ServeHTTP goroutine.
  863. if ch := wr.done; ch != nil {
  864. select {
  865. case ch <- res.err:
  866. default:
  867. panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wr.write))
  868. }
  869. }
  870. wr.write = nil // prevent use (assume it's tainted after wr.done send)
  871. if closeStream {
  872. if st == nil {
  873. panic("internal error: expecting non-nil stream")
  874. }
  875. switch st.state {
  876. case stateOpen:
  877. // Here we would go to stateHalfClosedLocal in
  878. // theory, but since our handler is done and
  879. // the net/http package provides no mechanism
  880. // for closing a ResponseWriter while still
  881. // reading data (see possible TODO at top of
  882. // this file), we go into closed state here
  883. // anyway, after telling the peer we're
  884. // hanging up on them.
  885. st.state = stateHalfClosedLocal // won't last long, but necessary for closeStream via resetStream
  886. errCancel := streamError(st.id, ErrCodeCancel)
  887. sc.resetStream(errCancel)
  888. case stateHalfClosedRemote:
  889. sc.closeStream(st, errHandlerComplete)
  890. }
  891. }
  892. sc.scheduleFrameWrite()
  893. }
  894. // scheduleFrameWrite tickles the frame writing scheduler.
  895. //
  896. // If a frame is already being written, nothing happens. This will be called again
  897. // when the frame is done being written.
  898. //
  899. // If a frame isn't being written we need to send one, the best frame
  900. // to send is selected, preferring first things that aren't
  901. // stream-specific (e.g. ACKing settings), and then finding the
  902. // highest priority stream.
  903. //
  904. // If a frame isn't being written and there's nothing else to send, we
  905. // flush the write buffer.
  906. func (sc *serverConn) scheduleFrameWrite() {
  907. sc.serveG.check()
  908. if sc.writingFrame || sc.inFrameScheduleLoop {
  909. return
  910. }
  911. sc.inFrameScheduleLoop = true
  912. for !sc.writingFrameAsync {
  913. if sc.needToSendGoAway {
  914. sc.needToSendGoAway = false
  915. sc.startFrameWrite(FrameWriteRequest{
  916. write: &writeGoAway{
  917. maxStreamID: sc.maxStreamID,
  918. code: sc.goAwayCode,
  919. },
  920. })
  921. continue
  922. }
  923. if sc.needToSendSettingsAck {
  924. sc.needToSendSettingsAck = false
  925. sc.startFrameWrite(FrameWriteRequest{write: writeSettingsAck{}})
  926. continue
  927. }
  928. if !sc.inGoAway {
  929. if wr, ok := sc.writeSched.Pop(); ok {
  930. sc.startFrameWrite(wr)
  931. continue
  932. }
  933. }
  934. if sc.needsFrameFlush {
  935. sc.startFrameWrite(FrameWriteRequest{write: flushFrameWriter{}})
  936. sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
  937. continue
  938. }
  939. break
  940. }
  941. sc.inFrameScheduleLoop = false
  942. }
  943. func (sc *serverConn) goAway(code ErrCode) {
  944. sc.serveG.check()
  945. if sc.inGoAway {
  946. return
  947. }
  948. if code != ErrCodeNo {
  949. sc.shutDownIn(250 * time.Millisecond)
  950. } else {
  951. // TODO: configurable
  952. sc.shutDownIn(1 * time.Second)
  953. }
  954. sc.inGoAway = true
  955. sc.needToSendGoAway = true
  956. sc.goAwayCode = code
  957. sc.scheduleFrameWrite()
  958. }
  959. func (sc *serverConn) shutDownIn(d time.Duration) {
  960. sc.serveG.check()
  961. sc.shutdownTimer = time.NewTimer(d)
  962. sc.shutdownTimerCh = sc.shutdownTimer.C
  963. }
  964. func (sc *serverConn) resetStream(se StreamError) {
  965. sc.serveG.check()
  966. sc.writeFrame(FrameWriteRequest{write: se})
  967. if st, ok := sc.streams[se.StreamID]; ok {
  968. st.sentReset = true
  969. sc.closeStream(st, se)
  970. }
  971. }
  972. // processFrameFromReader processes the serve loop's read from readFrameCh from the
  973. // frame-reading goroutine.
  974. // processFrameFromReader returns whether the connection should be kept open.
  975. func (sc *serverConn) processFrameFromReader(res readFrameResult) bool {
  976. sc.serveG.check()
  977. err := res.err
  978. if err != nil {
  979. if err == ErrFrameTooLarge {
  980. sc.goAway(ErrCodeFrameSize)
  981. return true // goAway will close the loop
  982. }
  983. clientGone := err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err)
  984. if clientGone {
  985. // TODO: could we also get into this state if
  986. // the peer does a half close
  987. // (e.g. CloseWrite) because they're done
  988. // sending frames but they're still wanting
  989. // our open replies? Investigate.
  990. // TODO: add CloseWrite to crypto/tls.Conn first
  991. // so we have a way to test this? I suppose
  992. // just for testing we could have a non-TLS mode.
  993. return false
  994. }
  995. } else {
  996. f := res.f
  997. if VerboseLogs {
  998. sc.vlogf("http2: server read frame %v", summarizeFrame(f))
  999. }
  1000. err = sc.processFrame(f)
  1001. if err == nil {
  1002. return true
  1003. }
  1004. }
  1005. switch ev := err.(type) {
  1006. case StreamError:
  1007. sc.resetStream(ev)
  1008. return true
  1009. case goAwayFlowError:
  1010. sc.goAway(ErrCodeFlowControl)
  1011. return true
  1012. case ConnectionError:
  1013. sc.logf("http2: server connection error from %v: %v", sc.conn.RemoteAddr(), ev)
  1014. sc.goAway(ErrCode(ev))
  1015. return true // goAway will handle shutdown
  1016. default:
  1017. if res.err != nil {
  1018. sc.vlogf("http2: server closing client connection; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
  1019. } else {
  1020. sc.logf("http2: server closing client connection: %v", err)
  1021. }
  1022. return false
  1023. }
  1024. }
  1025. func (sc *serverConn) processFrame(f Frame) error {
  1026. sc.serveG.check()
  1027. // First frame received must be SETTINGS.
  1028. if !sc.sawFirstSettings {
  1029. if _, ok := f.(*SettingsFrame); !ok {
  1030. return ConnectionError(ErrCodeProtocol)
  1031. }
  1032. sc.sawFirstSettings = true
  1033. }
  1034. switch f := f.(type) {
  1035. case *SettingsFrame:
  1036. return sc.processSettings(f)
  1037. case *MetaHeadersFrame:
  1038. return sc.processHeaders(f)
  1039. case *WindowUpdateFrame:
  1040. return sc.processWindowUpdate(f)
  1041. case *PingFrame:
  1042. return sc.processPing(f)
  1043. case *DataFrame:
  1044. return sc.processData(f)
  1045. case *RSTStreamFrame:
  1046. return sc.processResetStream(f)
  1047. case *PriorityFrame:
  1048. return sc.processPriority(f)
  1049. case *PushPromiseFrame:
  1050. // A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE
  1051. // frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1052. return ConnectionError(ErrCodeProtocol)
  1053. default:
  1054. sc.vlogf("http2: server ignoring frame: %v", f.Header())
  1055. return nil
  1056. }
  1057. }
  1058. func (sc *serverConn) processPing(f *PingFrame) error {
  1059. sc.serveG.check()
  1060. if f.IsAck() {
  1061. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  1062. // containing this flag."
  1063. return nil
  1064. }
  1065. if f.StreamID != 0 {
  1066. // "PING frames are not associated with any individual
  1067. // stream. If a PING frame is received with a stream
  1068. // identifier field value other than 0x0, the recipient MUST
  1069. // respond with a connection error (Section 5.4.1) of type
  1070. // PROTOCOL_ERROR."
  1071. return ConnectionError(ErrCodeProtocol)
  1072. }
  1073. if sc.inGoAway {
  1074. return nil
  1075. }
  1076. sc.writeFrame(FrameWriteRequest{write: writePingAck{f}})
  1077. return nil
  1078. }
  1079. func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  1080. sc.serveG.check()
  1081. if sc.inGoAway {
  1082. return nil
  1083. }
  1084. switch {
  1085. case f.StreamID != 0: // stream-level flow control
  1086. state, st := sc.state(f.StreamID)
  1087. if state == stateIdle {
  1088. // Section 5.1: "Receiving any frame other than HEADERS
  1089. // or PRIORITY on a stream in this state MUST be
  1090. // treated as a connection error (Section 5.4.1) of
  1091. // type PROTOCOL_ERROR."
  1092. return ConnectionError(ErrCodeProtocol)
  1093. }
  1094. if st == nil {
  1095. // "WINDOW_UPDATE can be sent by a peer that has sent a
  1096. // frame bearing the END_STREAM flag. This means that a
  1097. // receiver could receive a WINDOW_UPDATE frame on a "half
  1098. // closed (remote)" or "closed" stream. A receiver MUST
  1099. // NOT treat this as an error, see Section 5.1."
  1100. return nil
  1101. }
  1102. if !st.flow.add(int32(f.Increment)) {
  1103. return streamError(f.StreamID, ErrCodeFlowControl)
  1104. }
  1105. default: // connection-level flow control
  1106. if !sc.flow.add(int32(f.Increment)) {
  1107. return goAwayFlowError{}
  1108. }
  1109. }
  1110. sc.scheduleFrameWrite()
  1111. return nil
  1112. }
  1113. func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
  1114. sc.serveG.check()
  1115. if sc.inGoAway {
  1116. return nil
  1117. }
  1118. state, st := sc.state(f.StreamID)
  1119. if state == stateIdle {
  1120. // 6.4 "RST_STREAM frames MUST NOT be sent for a
  1121. // stream in the "idle" state. If a RST_STREAM frame
  1122. // identifying an idle stream is received, the
  1123. // recipient MUST treat this as a connection error
  1124. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1125. return ConnectionError(ErrCodeProtocol)
  1126. }
  1127. if st != nil {
  1128. st.gotReset = true
  1129. st.cancelCtx()
  1130. sc.closeStream(st, streamError(f.StreamID, f.ErrCode))
  1131. }
  1132. return nil
  1133. }
  1134. func (sc *serverConn) closeStream(st *stream, err error) {
  1135. sc.serveG.check()
  1136. if st.state == stateIdle || st.state == stateClosed {
  1137. panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
  1138. }
  1139. st.state = stateClosed
  1140. if st.isPushed() {
  1141. sc.curPushedStreams--
  1142. } else {
  1143. sc.curClientStreams--
  1144. }
  1145. if sc.curClientStreams+sc.curPushedStreams == 0 {
  1146. sc.setConnState(http.StateIdle)
  1147. }
  1148. delete(sc.streams, st.id)
  1149. if len(sc.streams) == 0 && sc.srv.IdleTimeout != 0 {
  1150. sc.idleTimer.Reset(sc.srv.IdleTimeout)
  1151. }
  1152. if p := st.body; p != nil {
  1153. // Return any buffered unread bytes worth of conn-level flow control.
  1154. // See golang.org/issue/16481
  1155. sc.sendWindowUpdate(nil, p.Len())
  1156. p.CloseWithError(err)
  1157. }
  1158. st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc
  1159. sc.writeSched.CloseStream(st.id)
  1160. }
  1161. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  1162. sc.serveG.check()
  1163. if f.IsAck() {
  1164. sc.unackedSettings--
  1165. if sc.unackedSettings < 0 {
  1166. // Why is the peer ACKing settings we never sent?
  1167. // The spec doesn't mention this case, but
  1168. // hang up on them anyway.
  1169. return ConnectionError(ErrCodeProtocol)
  1170. }
  1171. return nil
  1172. }
  1173. if sc.inGoAway {
  1174. return nil
  1175. }
  1176. if err := f.ForeachSetting(sc.processSetting); err != nil {
  1177. return err
  1178. }
  1179. sc.needToSendSettingsAck = true
  1180. sc.scheduleFrameWrite()
  1181. return nil
  1182. }
  1183. func (sc *serverConn) processSetting(s Setting) error {
  1184. sc.serveG.check()
  1185. if err := s.Valid(); err != nil {
  1186. return err
  1187. }
  1188. if VerboseLogs {
  1189. sc.vlogf("http2: server processing setting %v", s)
  1190. }
  1191. switch s.ID {
  1192. case SettingHeaderTableSize:
  1193. sc.headerTableSize = s.Val
  1194. sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
  1195. case SettingEnablePush:
  1196. sc.pushEnabled = s.Val != 0
  1197. case SettingMaxConcurrentStreams:
  1198. sc.clientMaxStreams = s.Val
  1199. case SettingInitialWindowSize:
  1200. return sc.processSettingInitialWindowSize(s.Val)
  1201. case SettingMaxFrameSize:
  1202. sc.maxFrameSize = int32(s.Val) // the maximum valid s.Val is < 2^31
  1203. case SettingMaxHeaderListSize:
  1204. sc.peerMaxHeaderListSize = s.Val
  1205. default:
  1206. // Unknown setting: "An endpoint that receives a SETTINGS
  1207. // frame with any unknown or unsupported identifier MUST
  1208. // ignore that setting."
  1209. if VerboseLogs {
  1210. sc.vlogf("http2: server ignoring unknown setting %v", s)
  1211. }
  1212. }
  1213. return nil
  1214. }
  1215. func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  1216. sc.serveG.check()
  1217. // Note: val already validated to be within range by
  1218. // processSetting's Valid call.
  1219. // "A SETTINGS frame can alter the initial flow control window
  1220. // size for all current streams. When the value of
  1221. // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  1222. // adjust the size of all stream flow control windows that it
  1223. // maintains by the difference between the new value and the
  1224. // old value."
  1225. old := sc.initialWindowSize
  1226. sc.initialWindowSize = int32(val)
  1227. growth := sc.initialWindowSize - old // may be negative
  1228. for _, st := range sc.streams {
  1229. if !st.flow.add(growth) {
  1230. // 6.9.2 Initial Flow Control Window Size
  1231. // "An endpoint MUST treat a change to
  1232. // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  1233. // control window to exceed the maximum size as a
  1234. // connection error (Section 5.4.1) of type
  1235. // FLOW_CONTROL_ERROR."
  1236. return ConnectionError(ErrCodeFlowControl)
  1237. }
  1238. }
  1239. return nil
  1240. }
  1241. func (sc *serverConn) processData(f *DataFrame) error {
  1242. sc.serveG.check()
  1243. if sc.inGoAway {
  1244. return nil
  1245. }
  1246. data := f.Data()
  1247. // "If a DATA frame is received whose stream is not in "open"
  1248. // or "half closed (local)" state, the recipient MUST respond
  1249. // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  1250. id := f.Header().StreamID
  1251. state, st := sc.state(id)
  1252. if id == 0 || state == stateIdle {
  1253. // Section 5.1: "Receiving any frame other than HEADERS
  1254. // or PRIORITY on a stream in this state MUST be
  1255. // treated as a connection error (Section 5.4.1) of
  1256. // type PROTOCOL_ERROR."
  1257. return ConnectionError(ErrCodeProtocol)
  1258. }
  1259. if st == nil || state != stateOpen || st.gotTrailerHeader {
  1260. // This includes sending a RST_STREAM if the stream is
  1261. // in stateHalfClosedLocal (which currently means that
  1262. // the http.Handler returned, so it's done reading &
  1263. // done writing). Try to stop the client from sending
  1264. // more DATA.
  1265. // But still enforce their connection-level flow control,
  1266. // and return any flow control bytes since we're not going
  1267. // to consume them.
  1268. if sc.inflow.available() < int32(f.Length) {
  1269. return streamError(id, ErrCodeFlowControl)
  1270. }
  1271. // Deduct the flow control from inflow, since we're
  1272. // going to immediately add it back in
  1273. // sendWindowUpdate, which also schedules sending the
  1274. // frames.
  1275. sc.inflow.take(int32(f.Length))
  1276. sc.sendWindowUpdate(nil, int(f.Length)) // conn-level
  1277. return streamError(id, ErrCodeStreamClosed)
  1278. }
  1279. if st.body == nil {
  1280. panic("internal error: should have a body in this state")
  1281. }
  1282. // Sender sending more than they'd declared?
  1283. if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  1284. st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  1285. return streamError(id, ErrCodeStreamClosed)
  1286. }
  1287. if f.Length > 0 {
  1288. // Check whether the client has flow control quota.
  1289. if st.inflow.available() < int32(f.Length) {
  1290. return streamError(id, ErrCodeFlowControl)
  1291. }
  1292. st.inflow.take(int32(f.Length))
  1293. if len(data) > 0 {
  1294. wrote, err := st.body.Write(data)
  1295. if err != nil {
  1296. return streamError(id, ErrCodeStreamClosed)
  1297. }
  1298. if wrote != len(data) {
  1299. panic("internal error: bad Writer")
  1300. }
  1301. st.bodyBytes += int64(len(data))
  1302. }
  1303. // Return any padded flow control now, since we won't
  1304. // refund it later on body reads.
  1305. if pad := int32(f.Length) - int32(len(data)); pad > 0 {
  1306. sc.sendWindowUpdate32(nil, pad)
  1307. sc.sendWindowUpdate32(st, pad)
  1308. }
  1309. }
  1310. if f.StreamEnded() {
  1311. st.endStream()
  1312. }
  1313. return nil
  1314. }
  1315. // isPushed reports whether the stream is server-initiated.
  1316. func (st *stream) isPushed() bool {
  1317. return st.id%2 == 0
  1318. }
  1319. // endStream closes a Request.Body's pipe. It is called when a DATA
  1320. // frame says a request body is over (or after trailers).
  1321. func (st *stream) endStream() {
  1322. sc := st.sc
  1323. sc.serveG.check()
  1324. if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  1325. st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
  1326. st.declBodyBytes, st.bodyBytes))
  1327. } else {
  1328. st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest)
  1329. st.body.CloseWithError(io.EOF)
  1330. }
  1331. st.state = stateHalfClosedRemote
  1332. }
  1333. // copyTrailersToHandlerRequest is run in the Handler's goroutine in
  1334. // its Request.Body.Read just before it gets io.EOF.
  1335. func (st *stream) copyTrailersToHandlerRequest() {
  1336. for k, vv := range st.trailer {
  1337. if _, ok := st.reqTrailer[k]; ok {
  1338. // Only copy it over it was pre-declared.
  1339. st.reqTrailer[k] = vv
  1340. }
  1341. }
  1342. }
  1343. func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error {
  1344. sc.serveG.check()
  1345. id := f.StreamID
  1346. if sc.inGoAway {
  1347. // Ignore.
  1348. return nil
  1349. }
  1350. // http://tools.ietf.org/html/rfc7540#section-5.1.1
  1351. // Streams initiated by a client MUST use odd-numbered stream
  1352. // identifiers. [...] An endpoint that receives an unexpected
  1353. // stream identifier MUST respond with a connection error
  1354. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1355. if id%2 != 1 {
  1356. return ConnectionError(ErrCodeProtocol)
  1357. }
  1358. // A HEADERS frame can be used to create a new stream or
  1359. // send a trailer for an open one. If we already have a stream
  1360. // open, let it process its own HEADERS frame (trailers at this
  1361. // point, if it's valid).
  1362. if st := sc.streams[f.StreamID]; st != nil {
  1363. return st.processTrailerHeaders(f)
  1364. }
  1365. // [...] The identifier of a newly established stream MUST be
  1366. // numerically greater than all streams that the initiating
  1367. // endpoint has opened or reserved. [...] An endpoint that
  1368. // receives an unexpected stream identifier MUST respond with
  1369. // a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1370. if id <= sc.maxStreamID {
  1371. return ConnectionError(ErrCodeProtocol)
  1372. }
  1373. sc.maxStreamID = id
  1374. if sc.idleTimer != nil {
  1375. sc.idleTimer.Stop()
  1376. }
  1377. // http://tools.ietf.org/html/rfc7540#section-5.1.2
  1378. // [...] Endpoints MUST NOT exceed the limit set by their peer. An
  1379. // endpoint that receives a HEADERS frame that causes their
  1380. // advertised concurrent stream limit to be exceeded MUST treat
  1381. // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR
  1382. // or REFUSED_STREAM.
  1383. if sc.curClientStreams+1 > sc.advMaxStreams {
  1384. if sc.unackedSettings == 0 {
  1385. // They should know better.
  1386. return streamError(id, ErrCodeProtocol)
  1387. }
  1388. // Assume it's a network race, where they just haven't
  1389. // received our last SETTINGS update. But actually
  1390. // this can't happen yet, because we don't yet provide
  1391. // a way for users to adjust server parameters at
  1392. // runtime.
  1393. return streamError(id, ErrCodeRefusedStream)
  1394. }
  1395. initialState := stateOpen
  1396. if f.StreamEnded() {
  1397. initialState = stateHalfClosedRemote
  1398. }
  1399. st := sc.newStream(id, 0, initialState)
  1400. if f.HasPriority() {
  1401. if err := checkPriority(f.StreamID, f.Priority); err != nil {
  1402. return err
  1403. }
  1404. sc.writeSched.AdjustStream(st.id, f.Priority)
  1405. }
  1406. rw, req, err := sc.newWriterAndRequest(st, f)
  1407. if err != nil {
  1408. return err
  1409. }
  1410. st.reqTrailer = req.Trailer
  1411. if st.reqTrailer != nil {
  1412. st.trailer = make(http.Header)
  1413. }
  1414. st.body = req.Body.(*requestBody).pipe // may be nil
  1415. st.declBodyBytes = req.ContentLength
  1416. handler := sc.handler.ServeHTTP
  1417. if f.Truncated {
  1418. // Their header list was too long. Send a 431 error.
  1419. handler = handleHeaderListTooLong
  1420. } else if err := checkValidHTTP2RequestHeaders(req.Header); err != nil {
  1421. handler = new400Handler(err)
  1422. }
  1423. // The net/http package sets the read deadline from the
  1424. // http.Server.ReadTimeout during the TLS handshake, but then
  1425. // passes the connection off to us with the deadline already
  1426. // set. Disarm it here after the request headers are read,
  1427. // similar to how the http1 server works. Here it's
  1428. // technically more like the http1 Server's ReadHeaderTimeout
  1429. // (in Go 1.8), though. That's a more sane option anyway.
  1430. if sc.hs.ReadTimeout != 0 {
  1431. sc.conn.SetReadDeadline(time.Time{})
  1432. }
  1433. go sc.runHandler(rw, req, handler)
  1434. return nil
  1435. }
  1436. func (st *stream) processTrailerHeaders(f *MetaHeadersFrame) error {
  1437. sc := st.sc
  1438. sc.serveG.check()
  1439. if st.gotTrailerHeader {
  1440. return ConnectionError(ErrCodeProtocol)
  1441. }
  1442. st.gotTrailerHeader = true
  1443. if !f.StreamEnded() {
  1444. return streamError(st.id, ErrCodeProtocol)
  1445. }
  1446. if len(f.PseudoFields()) > 0 {
  1447. return streamError(st.id, ErrCodeProtocol)
  1448. }
  1449. if st.trailer != nil {
  1450. for _, hf := range f.RegularFields() {
  1451. key := sc.canonicalHeader(hf.Name)
  1452. if !ValidTrailerHeader(key) {
  1453. // TODO: send more details to the peer somehow. But http2 has
  1454. // no way to send debug data at a stream level. Discuss with
  1455. // HTTP folk.
  1456. return streamError(st.id, ErrCodeProtocol)
  1457. }
  1458. st.trailer[key] = append(st.trailer[key], hf.Value)
  1459. }
  1460. }
  1461. st.endStream()
  1462. return nil
  1463. }
  1464. func checkPriority(streamID uint32, p PriorityParam) error {
  1465. if streamID == p.StreamDep {
  1466. // Section 5.3.1: "A stream cannot depend on itself. An endpoint MUST treat
  1467. // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR."
  1468. // Section 5.3.3 says that a stream can depend on one of its dependencies,
  1469. // so it's only self-dependencies that are forbidden.
  1470. return streamError(streamID, ErrCodeProtocol)
  1471. }
  1472. return nil
  1473. }
  1474. func (sc *serverConn) processPriority(f *PriorityFrame) error {
  1475. if sc.inGoAway {
  1476. return nil
  1477. }
  1478. if err := checkPriority(f.StreamID, f.PriorityParam); err != nil {
  1479. return err
  1480. }
  1481. sc.writeSched.AdjustStream(f.StreamID, f.PriorityParam)
  1482. return nil
  1483. }
  1484. func (sc *serverConn) newStream(id, pusherID uint32, state streamState) *stream {
  1485. sc.serveG.check()
  1486. if id == 0 {
  1487. panic("internal error: cannot create stream with id 0")
  1488. }
  1489. ctx, cancelCtx := contextWithCancel(sc.baseCtx)
  1490. st := &stream{
  1491. sc: sc,
  1492. id: id,
  1493. state: state,
  1494. ctx: ctx,
  1495. cancelCtx: cancelCtx,
  1496. }
  1497. st.cw.Init()
  1498. st.flow.conn = &sc.flow // link to conn-level counter
  1499. st.flow.add(sc.initialWindowSize)
  1500. st.inflow.conn = &sc.inflow // link to conn-level counter
  1501. st.inflow.add(initialWindowSize) // TODO: update this when we send a higher initial window size in the initial settings
  1502. sc.streams[id] = st
  1503. sc.writeSched.OpenStream(st.id, OpenStreamOptions{PusherID: pusherID})
  1504. if st.isPushed() {
  1505. sc.curPushedStreams++
  1506. } else {
  1507. sc.curClientStreams++
  1508. }
  1509. if sc.curClientStreams+sc.curPushedStreams == 1 {
  1510. sc.setConnState(http.StateActive)
  1511. }
  1512. return st
  1513. }
  1514. func (sc *serverConn) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*responseWriter, *http.Request, error) {
  1515. sc.serveG.check()
  1516. rp := requestParam{
  1517. method: f.PseudoValue("method"),
  1518. scheme: f.PseudoValue("scheme"),
  1519. authority: f.PseudoValue("authority"),
  1520. path: f.PseudoValue("path"),
  1521. }
  1522. isConnect := rp.method == "CONNECT"
  1523. if isConnect {
  1524. if rp.path != "" || rp.scheme != "" || rp.authority == "" {
  1525. return nil, nil, streamError(f.StreamID, ErrCodeProtocol)
  1526. }
  1527. } else if rp.method == "" || rp.path == "" || (rp.scheme != "https" && rp.scheme != "http") {
  1528. // See 8.1.2.6 Malformed Requests and Responses:
  1529. //
  1530. // Malformed requests or responses that are detected
  1531. // MUST be treated as a stream error (Section 5.4.2)
  1532. // of type PROTOCOL_ERROR."
  1533. //
  1534. // 8.1.2.3 Request Pseudo-Header Fields
  1535. // "All HTTP/2 requests MUST include exactly one valid
  1536. // value for the :method, :scheme, and :path
  1537. // pseudo-header fields"
  1538. return nil, nil, streamError(f.StreamID, ErrCodeProtocol)
  1539. }
  1540. bodyOpen := !f.StreamEnded()
  1541. if rp.method == "HEAD" && bodyOpen {
  1542. // HEAD requests can't have bodies
  1543. return nil, nil, streamError(f.StreamID, ErrCodeProtocol)
  1544. }
  1545. rp.header = make(http.Header)
  1546. for _, hf := range f.RegularFields() {
  1547. rp.header.Add(sc.canonicalHeader(hf.Name), hf.Value)
  1548. }
  1549. if rp.authority == "" {
  1550. rp.authority = rp.header.Get("Host")
  1551. }
  1552. rw, req, err := sc.newWriterAndRequestNoBody(st, rp)
  1553. if err != nil {
  1554. return nil, nil, err
  1555. }
  1556. if bodyOpen {
  1557. st.reqBuf = getRequestBodyBuf()
  1558. req.Body.(*requestBody).pipe = &pipe{
  1559. b: &fixedBuffer{buf: st.reqBuf},
  1560. }
  1561. if vv, ok := rp.header["Content-Length"]; ok {
  1562. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  1563. } else {
  1564. req.ContentLength = -1
  1565. }
  1566. }
  1567. return rw, req, nil
  1568. }
  1569. type requestParam struct {
  1570. method string
  1571. scheme, authority, path string
  1572. header http.Header
  1573. }
  1574. func (sc *serverConn) newWriterAndRequestNoBody(st *stream, rp requestParam) (*responseWriter, *http.Request, error) {
  1575. sc.serveG.check()
  1576. var tlsState *tls.ConnectionState // nil if not scheme https
  1577. if rp.scheme == "https" {
  1578. tlsState = sc.tlsState
  1579. }
  1580. needsContinue := rp.header.Get("Expect") == "100-continue"
  1581. if needsContinue {
  1582. rp.header.Del("Expect")
  1583. }
  1584. // Merge Cookie headers into one "; "-delimited value.
  1585. if cookies := rp.header["Cookie"]; len(cookies) > 1 {
  1586. rp.header.Set("Cookie", strings.Join(cookies, "; "))
  1587. }
  1588. // Setup Trailers
  1589. var trailer http.Header
  1590. for _, v := range rp.header["Trailer"] {
  1591. for _, key := range strings.Split(v, ",") {
  1592. key = http.CanonicalHeaderKey(strings.TrimSpace(key))
  1593. switch key {
  1594. case "Transfer-Encoding", "Trailer", "Content-Length":
  1595. // Bogus. (copy of http1 rules)
  1596. // Ignore.
  1597. default:
  1598. if trailer == nil {
  1599. trailer = make(http.Header)
  1600. }
  1601. trailer[key] = nil
  1602. }
  1603. }
  1604. }
  1605. delete(rp.header, "Trailer")
  1606. var url_ *url.URL
  1607. var requestURI string
  1608. if rp.method == "CONNECT" {
  1609. url_ = &url.URL{Host: rp.authority}
  1610. requestURI = rp.authority // mimic HTTP/1 server behavior
  1611. } else {
  1612. var err error
  1613. url_, err = url.ParseRequestURI(rp.path)
  1614. if err != nil {
  1615. return nil, nil, streamError(st.id, ErrCodeProtocol)
  1616. }
  1617. requestURI = rp.path
  1618. }
  1619. body := &requestBody{
  1620. conn: sc,
  1621. stream: st,
  1622. needsContinue: needsContinue,
  1623. }
  1624. req := &http.Request{
  1625. Method: rp.method,
  1626. URL: url_,
  1627. RemoteAddr: sc.remoteAddrStr,
  1628. Header: rp.header,
  1629. RequestURI: requestURI,
  1630. Proto: "HTTP/2.0",
  1631. ProtoMajor: 2,
  1632. ProtoMinor: 0,
  1633. TLS: tlsState,
  1634. Host: rp.authority,
  1635. Body: body,
  1636. Trailer: trailer,
  1637. }
  1638. req = requestWithContext(req, st.ctx)
  1639. rws := responseWriterStatePool.Get().(*responseWriterState)
  1640. bwSave := rws.bw
  1641. *rws = responseWriterState{} // zero all the fields
  1642. rws.conn = sc
  1643. rws.bw = bwSave
  1644. rws.bw.Reset(chunkWriter{rws})
  1645. rws.stream = st
  1646. rws.req = req
  1647. rws.body = body
  1648. rw := &responseWriter{rws: rws}
  1649. return rw, req, nil
  1650. }
  1651. var reqBodyCache = make(chan []byte, 8)
  1652. func getRequestBodyBuf() []byte {
  1653. select {
  1654. case b := <-reqBodyCache:
  1655. return b
  1656. default:
  1657. return make([]byte, initialWindowSize)
  1658. }
  1659. }
  1660. func putRequestBodyBuf(b []byte) {
  1661. select {
  1662. case reqBodyCache <- b:
  1663. default:
  1664. }
  1665. }
  1666. // Run on its own goroutine.
  1667. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) {
  1668. didPanic := true
  1669. defer func() {
  1670. rw.rws.stream.cancelCtx()
  1671. if didPanic {
  1672. e := recover()
  1673. // Same as net/http:
  1674. const size = 64 << 10
  1675. buf := make([]byte, size)
  1676. buf = buf[:runtime.Stack(buf, false)]
  1677. sc.writeFrameFromHandler(FrameWriteRequest{
  1678. write: handlerPanicRST{rw.rws.stream.id},
  1679. stream: rw.rws.stream,
  1680. })
  1681. sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf)
  1682. return
  1683. }
  1684. rw.handlerDone()
  1685. }()
  1686. handler(rw, req)
  1687. didPanic = false
  1688. }
  1689. func handleHeaderListTooLong(w http.ResponseWriter, r *http.Request) {
  1690. // 10.5.1 Limits on Header Block Size:
  1691. // .. "A server that receives a larger header block than it is
  1692. // willing to handle can send an HTTP 431 (Request Header Fields Too
  1693. // Large) status code"
  1694. const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+
  1695. w.WriteHeader(statusRequestHeaderFieldsTooLarge)
  1696. io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
  1697. }
  1698. // called from handler goroutines.
  1699. // h may be nil.
  1700. func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error {
  1701. sc.serveG.checkNotOn() // NOT on
  1702. var errc chan error
  1703. if headerData.h != nil {
  1704. // If there's a header map (which we don't own), so we have to block on
  1705. // waiting for this frame to be written, so an http.Flush mid-handler
  1706. // writes out the correct value of keys, before a handler later potentially
  1707. // mutates it.
  1708. errc = errChanPool.Get().(chan error)
  1709. }
  1710. if err := sc.writeFrameFromHandler(FrameWriteRequest{
  1711. write: headerData,
  1712. stream: st,
  1713. done: errc,
  1714. }); err != nil {
  1715. return err
  1716. }
  1717. if errc != nil {
  1718. select {
  1719. case err := <-errc:
  1720. errChanPool.Put(errc)
  1721. return err
  1722. case <-sc.doneServing:
  1723. return errClientDisconnected
  1724. case <-st.cw:
  1725. return errStreamClosed
  1726. }
  1727. }
  1728. return nil
  1729. }
  1730. // called from handler goroutines.
  1731. func (sc *serverConn) write100ContinueHeaders(st *stream) {
  1732. sc.writeFrameFromHandler(FrameWriteRequest{
  1733. write: write100ContinueHeadersFrame{st.id},
  1734. stream: st,
  1735. })
  1736. }
  1737. // A bodyReadMsg tells the server loop that the http.Handler read n
  1738. // bytes of the DATA from the client on the given stream.
  1739. type bodyReadMsg struct {
  1740. st *stream
  1741. n int
  1742. }
  1743. // called from handler goroutines.
  1744. // Notes that the handler for the given stream ID read n bytes of its body
  1745. // and schedules flow control tokens to be sent.
  1746. func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int, err error) {
  1747. sc.serveG.checkNotOn() // NOT on
  1748. if n > 0 {
  1749. select {
  1750. case sc.bodyReadCh <- bodyReadMsg{st, n}:
  1751. case <-sc.doneServing:
  1752. }
  1753. }
  1754. if err == io.EOF {
  1755. if buf := st.reqBuf; buf != nil {
  1756. st.reqBuf = nil // shouldn't matter; field unused by other
  1757. putRequestBodyBuf(buf)
  1758. }
  1759. }
  1760. }
  1761. func (sc *serverConn) noteBodyRead(st *stream, n int) {
  1762. sc.serveG.check()
  1763. sc.sendWindowUpdate(nil, n) // conn-level
  1764. if st.state != stateHalfClosedRemote && st.state != stateClosed {
  1765. // Don't send this WINDOW_UPDATE if the stream is closed
  1766. // remotely.
  1767. sc.sendWindowUpdate(st, n)
  1768. }
  1769. }
  1770. // st may be nil for conn-level
  1771. func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
  1772. sc.serveG.check()
  1773. // "The legal range for the increment to the flow control
  1774. // window is 1 to 2^31-1 (2,147,483,647) octets."
  1775. // A Go Read call on 64-bit machines could in theory read
  1776. // a larger Read than this. Very unlikely, but we handle it here
  1777. // rather than elsewhere for now.
  1778. const maxUint31 = 1<<31 - 1
  1779. for n >= maxUint31 {
  1780. sc.sendWindowUpdate32(st, maxUint31)
  1781. n -= maxUint31
  1782. }
  1783. sc.sendWindowUpdate32(st, int32(n))
  1784. }
  1785. // st may be nil for conn-level
  1786. func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) {
  1787. sc.serveG.check()
  1788. if n == 0 {
  1789. return
  1790. }
  1791. if n < 0 {
  1792. panic("negative update")
  1793. }
  1794. var streamID uint32
  1795. if st != nil {
  1796. streamID = st.id
  1797. }
  1798. sc.writeFrame(FrameWriteRequest{
  1799. write: writeWindowUpdate{streamID: streamID, n: uint32(n)},
  1800. stream: st,
  1801. })
  1802. var ok bool
  1803. if st == nil {
  1804. ok = sc.inflow.add(n)
  1805. } else {
  1806. ok = st.inflow.add(n)
  1807. }
  1808. if !ok {
  1809. panic("internal error; sent too many window updates without decrements?")
  1810. }
  1811. }
  1812. // requestBody is the Handler's Request.Body type.
  1813. // Read and Close may be called concurrently.
  1814. type requestBody struct {
  1815. stream *stream
  1816. conn *serverConn
  1817. closed bool // for use by Close only
  1818. sawEOF bool // for use by Read only
  1819. pipe *pipe // non-nil if we have a HTTP entity message body
  1820. needsContinue bool // need to send a 100-continue
  1821. }
  1822. func (b *requestBody) Close() error {
  1823. if b.pipe != nil && !b.closed {
  1824. b.pipe.BreakWithError(errClosedBody)
  1825. }
  1826. b.closed = true
  1827. return nil
  1828. }
  1829. func (b *requestBody) Read(p []byte) (n int, err error) {
  1830. if b.needsContinue {
  1831. b.needsContinue = false
  1832. b.conn.write100ContinueHeaders(b.stream)
  1833. }
  1834. if b.pipe == nil || b.sawEOF {
  1835. return 0, io.EOF
  1836. }
  1837. n, err = b.pipe.Read(p)
  1838. if err == io.EOF {
  1839. b.sawEOF = true
  1840. }
  1841. if b.conn == nil && inTests {
  1842. return
  1843. }
  1844. b.conn.noteBodyReadFromHandler(b.stream, n, err)
  1845. return
  1846. }
  1847. // responseWriter is the http.ResponseWriter implementation. It's
  1848. // intentionally small (1 pointer wide) to minimize garbage. The
  1849. // responseWriterState pointer inside is zeroed at the end of a
  1850. // request (in handlerDone) and calls on the responseWriter thereafter
  1851. // simply crash (caller's mistake), but the much larger responseWriterState
  1852. // and buffers are reused between multiple requests.
  1853. type responseWriter struct {
  1854. rws *responseWriterState
  1855. }
  1856. // Optional http.ResponseWriter interfaces implemented.
  1857. var (
  1858. _ http.CloseNotifier = (*responseWriter)(nil)
  1859. _ http.Flusher = (*responseWriter)(nil)
  1860. _ stringWriter = (*responseWriter)(nil)
  1861. )
  1862. type responseWriterState struct {
  1863. // immutable within a request:
  1864. stream *stream
  1865. req *http.Request
  1866. body *requestBody // to close at end of request, if DATA frames didn't
  1867. conn *serverConn
  1868. // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
  1869. bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
  1870. // mutated by http.Handler goroutine:
  1871. handlerHeader http.Header // nil until called
  1872. snapHeader http.Header // snapshot of handlerHeader at WriteHeader time
  1873. trailers []string // set in writeChunk
  1874. status int // status code passed to WriteHeader
  1875. wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
  1876. sentHeader bool // have we sent the header frame?
  1877. handlerDone bool // handler has finished
  1878. sentContentLen int64 // non-zero if handler set a Content-Length header
  1879. wroteBytes int64
  1880. closeNotifierMu sync.Mutex // guards closeNotifierCh
  1881. closeNotifierCh chan bool // nil until first used
  1882. }
  1883. type chunkWriter struct{ rws *responseWriterState }
  1884. func (cw chunkWriter) Write(p []byte) (n int, err error) { return cw.rws.writeChunk(p) }
  1885. func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) != 0 }
  1886. // declareTrailer is called for each Trailer header when the
  1887. // response header is written. It notes that a header will need to be
  1888. // written in the trailers at the end of the response.
  1889. func (rws *responseWriterState) declareTrailer(k string) {
  1890. k = http.CanonicalHeaderKey(k)
  1891. if !ValidTrailerHeader(k) {
  1892. // Forbidden by RFC 2616 14.40.
  1893. rws.conn.logf("ignoring invalid trailer %q", k)
  1894. return
  1895. }
  1896. if !strSliceContains(rws.trailers, k) {
  1897. rws.trailers = append(rws.trailers, k)
  1898. }
  1899. }
  1900. // writeChunk writes chunks from the bufio.Writer. But because
  1901. // bufio.Writer may bypass its chunking, sometimes p may be
  1902. // arbitrarily large.
  1903. //
  1904. // writeChunk is also responsible (on the first chunk) for sending the
  1905. // HEADER response.
  1906. func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
  1907. if !rws.wroteHeader {
  1908. rws.writeHeader(200)
  1909. }
  1910. isHeadResp := rws.req.Method == "HEAD"
  1911. if !rws.sentHeader {
  1912. rws.sentHeader = true
  1913. var ctype, clen string
  1914. if clen = rws.snapHeader.Get("Content-Length"); clen != "" {
  1915. rws.snapHeader.Del("Content-Length")
  1916. clen64, err := strconv.ParseInt(clen, 10, 64)
  1917. if err == nil && clen64 >= 0 {
  1918. rws.sentContentLen = clen64
  1919. } else {
  1920. clen = ""
  1921. }
  1922. }
  1923. if clen == "" && rws.handlerDone && bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) {
  1924. clen = strconv.Itoa(len(p))
  1925. }
  1926. _, hasContentType := rws.snapHeader["Content-Type"]
  1927. if !hasContentType && bodyAllowedForStatus(rws.status) {
  1928. ctype = http.DetectContentType(p)
  1929. }
  1930. var date string
  1931. if _, ok := rws.snapHeader["Date"]; !ok {
  1932. // TODO(bradfitz): be faster here, like net/http? measure.
  1933. date = time.Now().UTC().Format(http.TimeFormat)
  1934. }
  1935. for _, v := range rws.snapHeader["Trailer"] {
  1936. foreachHeaderElement(v, rws.declareTrailer)
  1937. }
  1938. endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp
  1939. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  1940. streamID: rws.stream.id,
  1941. httpResCode: rws.status,
  1942. h: rws.snapHeader,
  1943. endStream: endStream,
  1944. contentType: ctype,
  1945. contentLength: clen,
  1946. date: date,
  1947. })
  1948. if err != nil {
  1949. return 0, err
  1950. }
  1951. if endStream {
  1952. return 0, nil
  1953. }
  1954. }
  1955. if isHeadResp {
  1956. return len(p), nil
  1957. }
  1958. if len(p) == 0 && !rws.handlerDone {
  1959. return 0, nil
  1960. }
  1961. if rws.handlerDone {
  1962. rws.promoteUndeclaredTrailers()
  1963. }
  1964. endStream := rws.handlerDone && !rws.hasTrailers()
  1965. if len(p) > 0 || endStream {
  1966. // only send a 0 byte DATA frame if we're ending the stream.
  1967. if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil {
  1968. return 0, err
  1969. }
  1970. }
  1971. if rws.handlerDone && rws.hasTrailers() {
  1972. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  1973. streamID: rws.stream.id,
  1974. h: rws.handlerHeader,
  1975. trailers: rws.trailers,
  1976. endStream: true,
  1977. })
  1978. return len(p), err
  1979. }
  1980. return len(p), nil
  1981. }
  1982. // TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
  1983. // that, if present, signals that the map entry is actually for
  1984. // the response trailers, and not the response headers. The prefix
  1985. // is stripped after the ServeHTTP call finishes and the values are
  1986. // sent in the trailers.
  1987. //
  1988. // This mechanism is intended only for trailers that are not known
  1989. // prior to the headers being written. If the set of trailers is fixed
  1990. // or known before the header is written, the normal Go trailers mechanism
  1991. // is preferred:
  1992. // https://golang.org/pkg/net/http/#ResponseWriter
  1993. // https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
  1994. const TrailerPrefix = "Trailer:"
  1995. // promoteUndeclaredTrailers permits http.Handlers to set trailers
  1996. // after the header has already been flushed. Because the Go
  1997. // ResponseWriter interface has no way to set Trailers (only the
  1998. // Header), and because we didn't want to expand the ResponseWriter
  1999. // interface, and because nobody used trailers, and because RFC 2616
  2000. // says you SHOULD (but not must) predeclare any trailers in the
  2001. // header, the official ResponseWriter rules said trailers in Go must
  2002. // be predeclared, and then we reuse the same ResponseWriter.Header()
  2003. // map to mean both Headers and Trailers. When it's time to write the
  2004. // Trailers, we pick out the fields of Headers that were declared as
  2005. // trailers. That worked for a while, until we found the first major
  2006. // user of Trailers in the wild: gRPC (using them only over http2),
  2007. // and gRPC libraries permit setting trailers mid-stream without
  2008. // predeclarnig them. So: change of plans. We still permit the old
  2009. // way, but we also permit this hack: if a Header() key begins with
  2010. // "Trailer:", the suffix of that key is a Trailer. Because ':' is an
  2011. // invalid token byte anyway, there is no ambiguity. (And it's already
  2012. // filtered out) It's mildly hacky, but not terrible.
  2013. //
  2014. // This method runs after the Handler is done and promotes any Header
  2015. // fields to be trailers.
  2016. func (rws *responseWriterState) promoteUndeclaredTrailers() {
  2017. for k, vv := range rws.handlerHeader {
  2018. if !strings.HasPrefix(k, TrailerPrefix) {
  2019. continue
  2020. }
  2021. trailerKey := strings.TrimPrefix(k, TrailerPrefix)
  2022. rws.declareTrailer(trailerKey)
  2023. rws.handlerHeader[http.CanonicalHeaderKey(trailerKey)] = vv
  2024. }
  2025. if len(rws.trailers) > 1 {
  2026. sorter := sorterPool.Get().(*sorter)
  2027. sorter.SortStrings(rws.trailers)
  2028. sorterPool.Put(sorter)
  2029. }
  2030. }
  2031. func (w *responseWriter) Flush() {
  2032. rws := w.rws
  2033. if rws == nil {
  2034. panic("Header called after Handler finished")
  2035. }
  2036. if rws.bw.Buffered() > 0 {
  2037. if err := rws.bw.Flush(); err != nil {
  2038. // Ignore the error. The frame writer already knows.
  2039. return
  2040. }
  2041. } else {
  2042. // The bufio.Writer won't call chunkWriter.Write
  2043. // (writeChunk with zero bytes, so we have to do it
  2044. // ourselves to force the HTTP response header and/or
  2045. // final DATA frame (with END_STREAM) to be sent.
  2046. rws.writeChunk(nil)
  2047. }
  2048. }
  2049. func (w *responseWriter) CloseNotify() <-chan bool {
  2050. rws := w.rws
  2051. if rws == nil {
  2052. panic("CloseNotify called after Handler finished")
  2053. }
  2054. rws.closeNotifierMu.Lock()
  2055. ch := rws.closeNotifierCh
  2056. if ch == nil {
  2057. ch = make(chan bool, 1)
  2058. rws.closeNotifierCh = ch
  2059. go func() {
  2060. rws.stream.cw.Wait() // wait for close
  2061. ch <- true
  2062. }()
  2063. }
  2064. rws.closeNotifierMu.Unlock()
  2065. return ch
  2066. }
  2067. func (w *responseWriter) Header() http.Header {
  2068. rws := w.rws
  2069. if rws == nil {
  2070. panic("Header called after Handler finished")
  2071. }
  2072. if rws.handlerHeader == nil {
  2073. rws.handlerHeader = make(http.Header)
  2074. }
  2075. return rws.handlerHeader
  2076. }
  2077. func (w *responseWriter) WriteHeader(code int) {
  2078. rws := w.rws
  2079. if rws == nil {
  2080. panic("WriteHeader called after Handler finished")
  2081. }
  2082. rws.writeHeader(code)
  2083. }
  2084. func (rws *responseWriterState) writeHeader(code int) {
  2085. if !rws.wroteHeader {
  2086. rws.wroteHeader = true
  2087. rws.status = code
  2088. if len(rws.handlerHeader) > 0 {
  2089. rws.snapHeader = cloneHeader(rws.handlerHeader)
  2090. }
  2091. }
  2092. }
  2093. func cloneHeader(h http.Header) http.Header {
  2094. h2 := make(http.Header, len(h))
  2095. for k, vv := range h {
  2096. vv2 := make([]string, len(vv))
  2097. copy(vv2, vv)
  2098. h2[k] = vv2
  2099. }
  2100. return h2
  2101. }
  2102. // The Life Of A Write is like this:
  2103. //
  2104. // * Handler calls w.Write or w.WriteString ->
  2105. // * -> rws.bw (*bufio.Writer) ->
  2106. // * (Handler migth call Flush)
  2107. // * -> chunkWriter{rws}
  2108. // * -> responseWriterState.writeChunk(p []byte)
  2109. // * -> responseWriterState.writeChunk (most of the magic; see comment there)
  2110. func (w *responseWriter) Write(p []byte) (n int, err error) {
  2111. return w.write(len(p), p, "")
  2112. }
  2113. func (w *responseWriter) WriteString(s string) (n int, err error) {
  2114. return w.write(len(s), nil, s)
  2115. }
  2116. // either dataB or dataS is non-zero.
  2117. func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  2118. rws := w.rws
  2119. if rws == nil {
  2120. panic("Write called after Handler finished")
  2121. }
  2122. if !rws.wroteHeader {
  2123. w.WriteHeader(200)
  2124. }
  2125. if !bodyAllowedForStatus(rws.status) {
  2126. return 0, http.ErrBodyNotAllowed
  2127. }
  2128. rws.wroteBytes += int64(len(dataB)) + int64(len(dataS)) // only one can be set
  2129. if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen {
  2130. // TODO: send a RST_STREAM
  2131. return 0, errors.New("http2: handler wrote more than declared Content-Length")
  2132. }
  2133. if dataB != nil {
  2134. return rws.bw.Write(dataB)
  2135. } else {
  2136. return rws.bw.WriteString(dataS)
  2137. }
  2138. }
  2139. func (w *responseWriter) handlerDone() {
  2140. rws := w.rws
  2141. rws.handlerDone = true
  2142. w.Flush()
  2143. w.rws = nil
  2144. responseWriterStatePool.Put(rws)
  2145. }
  2146. // Push errors.
  2147. var (
  2148. ErrRecursivePush = errors.New("http2: recursive push not allowed")
  2149. ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS")
  2150. )
  2151. // pushOptions is the internal version of http.PushOptions, which we
  2152. // cannot include here because it's only defined in Go 1.8 and later.
  2153. type pushOptions struct {
  2154. Method string
  2155. Header http.Header
  2156. }
  2157. func (w *responseWriter) push(target string, opts pushOptions) error {
  2158. st := w.rws.stream
  2159. sc := st.sc
  2160. sc.serveG.checkNotOn()
  2161. // No recursive pushes: "PUSH_PROMISE frames MUST only be sent on a peer-initiated stream."
  2162. // http://tools.ietf.org/html/rfc7540#section-6.6
  2163. if st.isPushed() {
  2164. return ErrRecursivePush
  2165. }
  2166. // Default options.
  2167. if opts.Method == "" {
  2168. opts.Method = "GET"
  2169. }
  2170. if opts.Header == nil {
  2171. opts.Header = http.Header{}
  2172. }
  2173. wantScheme := "http"
  2174. if w.rws.req.TLS != nil {
  2175. wantScheme = "https"
  2176. }
  2177. // Validate the request.
  2178. u, err := url.Parse(target)
  2179. if err != nil {
  2180. return err
  2181. }
  2182. if u.Scheme == "" {
  2183. if !strings.HasPrefix(target, "/") {
  2184. return fmt.Errorf("target must be an absolute URL or an absolute path: %q", target)
  2185. }
  2186. u.Scheme = wantScheme
  2187. u.Host = w.rws.req.Host
  2188. } else {
  2189. if u.Scheme != wantScheme {
  2190. return fmt.Errorf("cannot push URL with scheme %q from request with scheme %q", u.Scheme, wantScheme)
  2191. }
  2192. if u.Host == "" {
  2193. return errors.New("URL must have a host")
  2194. }
  2195. }
  2196. for k := range opts.Header {
  2197. if strings.HasPrefix(k, ":") {
  2198. return fmt.Errorf("promised request headers cannot include psuedo header %q", k)
  2199. }
  2200. // These headers are meaningful only if the request has a body,
  2201. // but PUSH_PROMISE requests cannot have a body.
  2202. // http://tools.ietf.org/html/rfc7540#section-8.2
  2203. // Also disallow Host, since the promised URL must be absolute.
  2204. switch strings.ToLower(k) {
  2205. case "content-length", "content-encoding", "trailer", "te", "expect", "host":
  2206. return fmt.Errorf("promised request headers cannot include %q", k)
  2207. }
  2208. }
  2209. if err := checkValidHTTP2RequestHeaders(opts.Header); err != nil {
  2210. return err
  2211. }
  2212. // The RFC effectively limits promised requests to GET and HEAD:
  2213. // "Promised requests MUST be cacheable [GET, HEAD, or POST], and MUST be safe [GET or HEAD]"
  2214. // http://tools.ietf.org/html/rfc7540#section-8.2
  2215. if opts.Method != "GET" && opts.Method != "HEAD" {
  2216. return fmt.Errorf("method %q must be GET or HEAD", opts.Method)
  2217. }
  2218. msg := startPushRequest{
  2219. parent: st,
  2220. method: opts.Method,
  2221. url: u,
  2222. header: cloneHeader(opts.Header),
  2223. done: errChanPool.Get().(chan error),
  2224. }
  2225. select {
  2226. case <-sc.doneServing:
  2227. return errClientDisconnected
  2228. case <-st.cw:
  2229. return errStreamClosed
  2230. case sc.wantStartPushCh <- msg:
  2231. }
  2232. select {
  2233. case <-sc.doneServing:
  2234. return errClientDisconnected
  2235. case <-st.cw:
  2236. return errStreamClosed
  2237. case err := <-msg.done:
  2238. errChanPool.Put(msg.done)
  2239. return err
  2240. }
  2241. }
  2242. type startPushRequest struct {
  2243. parent *stream
  2244. method string
  2245. url *url.URL
  2246. header http.Header
  2247. done chan error
  2248. }
  2249. func (sc *serverConn) startPush(msg startPushRequest) {
  2250. sc.serveG.check()
  2251. // http://tools.ietf.org/html/rfc7540#section-6.6.
  2252. // PUSH_PROMISE frames MUST only be sent on a peer-initiated stream that
  2253. // is in either the "open" or "half-closed (remote)" state.
  2254. if msg.parent.state != stateOpen && msg.parent.state != stateHalfClosedRemote {
  2255. // responseWriter.Push checks that the stream is peer-initiaed.
  2256. msg.done <- errStreamClosed
  2257. return
  2258. }
  2259. // http://tools.ietf.org/html/rfc7540#section-6.6.
  2260. if !sc.pushEnabled {
  2261. msg.done <- http.ErrNotSupported
  2262. return
  2263. }
  2264. // PUSH_PROMISE frames must be sent in increasing order by stream ID, so
  2265. // we allocate an ID for the promised stream lazily, when the PUSH_PROMISE
  2266. // is written. Once the ID is allocated, we start the request handler.
  2267. allocatePromisedID := func() (uint32, error) {
  2268. sc.serveG.check()
  2269. // Check this again, just in case. Technically, we might have received
  2270. // an updated SETTINGS by the time we got around to writing this frame.
  2271. if !sc.pushEnabled {
  2272. return 0, http.ErrNotSupported
  2273. }
  2274. // http://tools.ietf.org/html/rfc7540#section-6.5.2.
  2275. if sc.curPushedStreams+1 > sc.clientMaxStreams {
  2276. return 0, ErrPushLimitReached
  2277. }
  2278. // http://tools.ietf.org/html/rfc7540#section-5.1.1.
  2279. // Streams initiated by the server MUST use even-numbered identifiers.
  2280. sc.maxPushPromiseID += 2
  2281. promisedID := sc.maxPushPromiseID
  2282. // http://tools.ietf.org/html/rfc7540#section-8.2.
  2283. // Strictly speaking, the new stream should start in "reserved (local)", then
  2284. // transition to "half closed (remote)" after sending the initial HEADERS, but
  2285. // we start in "half closed (remote)" for simplicity.
  2286. // See further comments at the definition of stateHalfClosedRemote.
  2287. promised := sc.newStream(promisedID, msg.parent.id, stateHalfClosedRemote)
  2288. rw, req, err := sc.newWriterAndRequestNoBody(promised, requestParam{
  2289. method: msg.method,
  2290. scheme: msg.url.Scheme,
  2291. authority: msg.url.Host,
  2292. path: msg.url.RequestURI(),
  2293. header: msg.header,
  2294. })
  2295. if err != nil {
  2296. // Should not happen, since we've already validated msg.url.
  2297. panic(fmt.Sprintf("newWriterAndRequestNoBody(%+v): %v", msg.url, err))
  2298. }
  2299. go sc.runHandler(rw, req, sc.handler.ServeHTTP)
  2300. return promisedID, nil
  2301. }
  2302. sc.writeFrame(FrameWriteRequest{
  2303. write: &writePushPromise{
  2304. streamID: msg.parent.id,
  2305. method: msg.method,
  2306. url: msg.url,
  2307. h: msg.header,
  2308. allocatePromisedID: allocatePromisedID,
  2309. },
  2310. stream: msg.parent,
  2311. done: msg.done,
  2312. })
  2313. }
  2314. // foreachHeaderElement splits v according to the "#rule" construction
  2315. // in RFC 2616 section 2.1 and calls fn for each non-empty element.
  2316. func foreachHeaderElement(v string, fn func(string)) {
  2317. v = textproto.TrimString(v)
  2318. if v == "" {
  2319. return
  2320. }
  2321. if !strings.Contains(v, ",") {
  2322. fn(v)
  2323. return
  2324. }
  2325. for _, f := range strings.Split(v, ",") {
  2326. if f = textproto.TrimString(f); f != "" {
  2327. fn(f)
  2328. }
  2329. }
  2330. }
  2331. // From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2
  2332. var connHeaders = []string{
  2333. "Connection",
  2334. "Keep-Alive",
  2335. "Proxy-Connection",
  2336. "Transfer-Encoding",
  2337. "Upgrade",
  2338. }
  2339. // checkValidHTTP2RequestHeaders checks whether h is a valid HTTP/2 request,
  2340. // per RFC 7540 Section 8.1.2.2.
  2341. // The returned error is reported to users.
  2342. func checkValidHTTP2RequestHeaders(h http.Header) error {
  2343. for _, k := range connHeaders {
  2344. if _, ok := h[k]; ok {
  2345. return fmt.Errorf("request header %q is not valid in HTTP/2", k)
  2346. }
  2347. }
  2348. te := h["Te"]
  2349. if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) {
  2350. return errors.New(`request header "TE" may only be "trailers" in HTTP/2`)
  2351. }
  2352. return nil
  2353. }
  2354. func new400Handler(err error) http.HandlerFunc {
  2355. return func(w http.ResponseWriter, r *http.Request) {
  2356. http.Error(w, err.Error(), http.StatusBadRequest)
  2357. }
  2358. }
  2359. // ValidTrailerHeader reports whether name is a valid header field name to appear
  2360. // in trailers.
  2361. // See: http://tools.ietf.org/html/rfc7230#section-4.1.2
  2362. func ValidTrailerHeader(name string) bool {
  2363. name = http.CanonicalHeaderKey(name)
  2364. if strings.HasPrefix(name, "If-") || badTrailer[name] {
  2365. return false
  2366. }
  2367. return true
  2368. }
  2369. var badTrailer = map[string]bool{
  2370. "Authorization": true,
  2371. "Cache-Control": true,
  2372. "Connection": true,
  2373. "Content-Encoding": true,
  2374. "Content-Length": true,
  2375. "Content-Range": true,
  2376. "Content-Type": true,
  2377. "Expect": true,
  2378. "Host": true,
  2379. "Keep-Alive": true,
  2380. "Max-Forwards": true,
  2381. "Pragma": true,
  2382. "Proxy-Authenticate": true,
  2383. "Proxy-Authorization": true,
  2384. "Proxy-Connection": true,
  2385. "Range": true,
  2386. "Realm": true,
  2387. "Te": true,
  2388. "Trailer": true,
  2389. "Transfer-Encoding": true,
  2390. "Www-Authenticate": true,
  2391. }