server.go 89 KB

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