server.go 83 KB

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