server.go 84 KB

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