server.go 88 KB

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