You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

server.go 94 kB

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