server.go 101 KB

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