server.go 94 KB

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