server.go 91 KB

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