server.go 91 KB

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