server.go 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753
  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. gracefulShutdownCh = h1ServerShutdownChan(sc.hs)
  656. }
  657. go sc.readFrames() // closed by defer sc.conn.Close above
  658. settingsTimer := time.NewTimer(firstSettingsTimeout)
  659. loopNum := 0
  660. for {
  661. loopNum++
  662. select {
  663. case wr := <-sc.wantWriteFrameCh:
  664. sc.writeFrame(wr)
  665. case spr := <-sc.wantStartPushCh:
  666. sc.startPush(spr)
  667. case res := <-sc.wroteFrameCh:
  668. sc.wroteFrame(res)
  669. case res := <-sc.readFrameCh:
  670. if !sc.processFrameFromReader(res) {
  671. return
  672. }
  673. res.readMore()
  674. if settingsTimer.C != nil {
  675. settingsTimer.Stop()
  676. settingsTimer.C = nil
  677. }
  678. case m := <-sc.bodyReadCh:
  679. sc.noteBodyRead(m.st, m.n)
  680. case <-settingsTimer.C:
  681. sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
  682. return
  683. case <-gracefulShutdownCh:
  684. gracefulShutdownCh = nil
  685. sc.startGracefulShutdown()
  686. case <-sc.shutdownTimerCh:
  687. sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
  688. return
  689. case <-sc.idleTimerCh:
  690. sc.vlogf("connection is idle")
  691. sc.goAway(ErrCodeNo)
  692. case fn := <-sc.testHookCh:
  693. fn(loopNum)
  694. }
  695. if sc.inGoAway && sc.curOpenStreams() == 0 && !sc.needToSendGoAway && !sc.writingFrame {
  696. return
  697. }
  698. }
  699. }
  700. // readPreface reads the ClientPreface greeting from the peer
  701. // or returns an error on timeout or an invalid greeting.
  702. func (sc *serverConn) readPreface() error {
  703. errc := make(chan error, 1)
  704. go func() {
  705. // Read the client preface
  706. buf := make([]byte, len(ClientPreface))
  707. if _, err := io.ReadFull(sc.conn, buf); err != nil {
  708. errc <- err
  709. } else if !bytes.Equal(buf, clientPreface) {
  710. errc <- fmt.Errorf("bogus greeting %q", buf)
  711. } else {
  712. errc <- nil
  713. }
  714. }()
  715. timer := time.NewTimer(prefaceTimeout) // TODO: configurable on *Server?
  716. defer timer.Stop()
  717. select {
  718. case <-timer.C:
  719. return errors.New("timeout waiting for client preface")
  720. case err := <-errc:
  721. if err == nil {
  722. if VerboseLogs {
  723. sc.vlogf("http2: server: client %v said hello", sc.conn.RemoteAddr())
  724. }
  725. }
  726. return err
  727. }
  728. }
  729. var errChanPool = sync.Pool{
  730. New: func() interface{} { return make(chan error, 1) },
  731. }
  732. var writeDataPool = sync.Pool{
  733. New: func() interface{} { return new(writeData) },
  734. }
  735. // writeDataFromHandler writes DATA response frames from a handler on
  736. // the given stream.
  737. func (sc *serverConn) writeDataFromHandler(stream *stream, data []byte, endStream bool) error {
  738. ch := errChanPool.Get().(chan error)
  739. writeArg := writeDataPool.Get().(*writeData)
  740. *writeArg = writeData{stream.id, data, endStream}
  741. err := sc.writeFrameFromHandler(FrameWriteRequest{
  742. write: writeArg,
  743. stream: stream,
  744. done: ch,
  745. })
  746. if err != nil {
  747. return err
  748. }
  749. var frameWriteDone bool // the frame write is done (successfully or not)
  750. select {
  751. case err = <-ch:
  752. frameWriteDone = true
  753. case <-sc.doneServing:
  754. return errClientDisconnected
  755. case <-stream.cw:
  756. // If both ch and stream.cw were ready (as might
  757. // happen on the final Write after an http.Handler
  758. // ends), prefer the write result. Otherwise this
  759. // might just be us successfully closing the stream.
  760. // The writeFrameAsync and serve goroutines guarantee
  761. // that the ch send will happen before the stream.cw
  762. // close.
  763. select {
  764. case err = <-ch:
  765. frameWriteDone = true
  766. default:
  767. return errStreamClosed
  768. }
  769. }
  770. errChanPool.Put(ch)
  771. if frameWriteDone {
  772. writeDataPool.Put(writeArg)
  773. }
  774. return err
  775. }
  776. // writeFrameFromHandler sends wr to sc.wantWriteFrameCh, but aborts
  777. // if the connection has gone away.
  778. //
  779. // This must not be run from the serve goroutine itself, else it might
  780. // deadlock writing to sc.wantWriteFrameCh (which is only mildly
  781. // buffered and is read by serve itself). If you're on the serve
  782. // goroutine, call writeFrame instead.
  783. func (sc *serverConn) writeFrameFromHandler(wr FrameWriteRequest) error {
  784. sc.serveG.checkNotOn() // NOT
  785. select {
  786. case sc.wantWriteFrameCh <- wr:
  787. return nil
  788. case <-sc.doneServing:
  789. // Serve loop is gone.
  790. // Client has closed their connection to the server.
  791. return errClientDisconnected
  792. }
  793. }
  794. // writeFrame schedules a frame to write and sends it if there's nothing
  795. // already being written.
  796. //
  797. // There is no pushback here (the serve goroutine never blocks). It's
  798. // the http.Handlers that block, waiting for their previous frames to
  799. // make it onto the wire
  800. //
  801. // If you're not on the serve goroutine, use writeFrameFromHandler instead.
  802. func (sc *serverConn) writeFrame(wr FrameWriteRequest) {
  803. sc.serveG.check()
  804. // If true, wr will not be written and wr.done will not be signaled.
  805. var ignoreWrite bool
  806. // We are not allowed to write frames on closed streams. RFC 7540 Section
  807. // 5.1.1 says: "An endpoint MUST NOT send frames other than PRIORITY on
  808. // a closed stream." Our server never sends PRIORITY, so that exception
  809. // does not apply.
  810. //
  811. // The serverConn might close an open stream while the stream's handler
  812. // is still running. For example, the server might close a stream when it
  813. // receives bad data from the client. If this happens, the handler might
  814. // attempt to write a frame after the stream has been closed (since the
  815. // handler hasn't yet been notified of the close). In this case, we simply
  816. // ignore the frame. The handler will notice that the stream is closed when
  817. // it waits for the frame to be written.
  818. //
  819. // As an exception to this rule, we allow sending RST_STREAM after close.
  820. // This allows us to immediately reject new streams without tracking any
  821. // state for those streams (except for the queued RST_STREAM frame). This
  822. // may result in duplicate RST_STREAMs in some cases, but the client should
  823. // ignore those.
  824. if wr.StreamID() != 0 {
  825. _, isReset := wr.write.(StreamError)
  826. if state, _ := sc.state(wr.StreamID()); state == stateClosed && !isReset {
  827. ignoreWrite = true
  828. }
  829. }
  830. // Don't send a 100-continue response if we've already sent headers.
  831. // See golang.org/issue/14030.
  832. switch wr.write.(type) {
  833. case *writeResHeaders:
  834. wr.stream.wroteHeaders = true
  835. case write100ContinueHeadersFrame:
  836. if wr.stream.wroteHeaders {
  837. // We do not need to notify wr.done because this frame is
  838. // never written with wr.done != nil.
  839. if wr.done != nil {
  840. panic("wr.done != nil for write100ContinueHeadersFrame")
  841. }
  842. ignoreWrite = true
  843. }
  844. }
  845. if !ignoreWrite {
  846. sc.writeSched.Push(wr)
  847. }
  848. sc.scheduleFrameWrite()
  849. }
  850. // startFrameWrite starts a goroutine to write wr (in a separate
  851. // goroutine since that might block on the network), and updates the
  852. // serve goroutine's state about the world, updated from info in wr.
  853. func (sc *serverConn) startFrameWrite(wr FrameWriteRequest) {
  854. sc.serveG.check()
  855. if sc.writingFrame {
  856. panic("internal error: can only be writing one frame at a time")
  857. }
  858. st := wr.stream
  859. if st != nil {
  860. switch st.state {
  861. case stateHalfClosedLocal:
  862. switch wr.write.(type) {
  863. case StreamError, handlerPanicRST, writeWindowUpdate:
  864. // RFC 7540 Section 5.1 allows sending RST_STREAM, PRIORITY, and WINDOW_UPDATE
  865. // in this state. (We never send PRIORITY from the server, so that is not checked.)
  866. default:
  867. panic(fmt.Sprintf("internal error: attempt to send frame on a half-closed-local stream: %v", wr))
  868. }
  869. case stateClosed:
  870. panic(fmt.Sprintf("internal error: attempt to send frame on a closed stream: %v", wr))
  871. }
  872. }
  873. if wpp, ok := wr.write.(*writePushPromise); ok {
  874. var err error
  875. wpp.promisedID, err = wpp.allocatePromisedID()
  876. if err != nil {
  877. sc.writingFrameAsync = false
  878. wr.replyToWriter(err)
  879. return
  880. }
  881. }
  882. sc.writingFrame = true
  883. sc.needsFrameFlush = true
  884. if wr.write.staysWithinBuffer(sc.bw.Available()) {
  885. sc.writingFrameAsync = false
  886. err := wr.write.writeFrame(sc)
  887. sc.wroteFrame(frameWriteResult{wr, err})
  888. } else {
  889. sc.writingFrameAsync = true
  890. go sc.writeFrameAsync(wr)
  891. }
  892. }
  893. // errHandlerPanicked is the error given to any callers blocked in a read from
  894. // Request.Body when the main goroutine panics. Since most handlers read in the
  895. // the main ServeHTTP goroutine, this will show up rarely.
  896. var errHandlerPanicked = errors.New("http2: handler panicked")
  897. // wroteFrame is called on the serve goroutine with the result of
  898. // whatever happened on writeFrameAsync.
  899. func (sc *serverConn) wroteFrame(res frameWriteResult) {
  900. sc.serveG.check()
  901. if !sc.writingFrame {
  902. panic("internal error: expected to be already writing a frame")
  903. }
  904. sc.writingFrame = false
  905. sc.writingFrameAsync = false
  906. wr := res.wr
  907. if writeEndsStream(wr.write) {
  908. st := wr.stream
  909. if st == nil {
  910. panic("internal error: expecting non-nil stream")
  911. }
  912. switch st.state {
  913. case stateOpen:
  914. // Here we would go to stateHalfClosedLocal in
  915. // theory, but since our handler is done and
  916. // the net/http package provides no mechanism
  917. // for closing a ResponseWriter while still
  918. // reading data (see possible TODO at top of
  919. // this file), we go into closed state here
  920. // anyway, after telling the peer we're
  921. // hanging up on them. We'll transition to
  922. // stateClosed after the RST_STREAM frame is
  923. // written.
  924. st.state = stateHalfClosedLocal
  925. sc.resetStream(streamError(st.id, ErrCodeCancel))
  926. case stateHalfClosedRemote:
  927. sc.closeStream(st, errHandlerComplete)
  928. }
  929. } else {
  930. switch v := wr.write.(type) {
  931. case StreamError:
  932. // st may be unknown if the RST_STREAM was generated to reject bad input.
  933. if st, ok := sc.streams[v.StreamID]; ok {
  934. sc.closeStream(st, v)
  935. }
  936. case handlerPanicRST:
  937. sc.closeStream(wr.stream, errHandlerPanicked)
  938. }
  939. }
  940. // Reply (if requested) to unblock the ServeHTTP goroutine.
  941. wr.replyToWriter(res.err)
  942. sc.scheduleFrameWrite()
  943. }
  944. // scheduleFrameWrite tickles the frame writing scheduler.
  945. //
  946. // If a frame is already being written, nothing happens. This will be called again
  947. // when the frame is done being written.
  948. //
  949. // If a frame isn't being written we need to send one, the best frame
  950. // to send is selected, preferring first things that aren't
  951. // stream-specific (e.g. ACKing settings), and then finding the
  952. // highest priority stream.
  953. //
  954. // If a frame isn't being written and there's nothing else to send, we
  955. // flush the write buffer.
  956. func (sc *serverConn) scheduleFrameWrite() {
  957. sc.serveG.check()
  958. if sc.writingFrame || sc.inFrameScheduleLoop {
  959. return
  960. }
  961. sc.inFrameScheduleLoop = true
  962. for !sc.writingFrameAsync {
  963. if sc.needToSendGoAway {
  964. sc.needToSendGoAway = false
  965. sc.startFrameWrite(FrameWriteRequest{
  966. write: &writeGoAway{
  967. maxStreamID: sc.maxClientStreamID,
  968. code: sc.goAwayCode,
  969. },
  970. })
  971. continue
  972. }
  973. if sc.needToSendSettingsAck {
  974. sc.needToSendSettingsAck = false
  975. sc.startFrameWrite(FrameWriteRequest{write: writeSettingsAck{}})
  976. continue
  977. }
  978. if !sc.inGoAway || sc.goAwayCode == ErrCodeNo {
  979. if wr, ok := sc.writeSched.Pop(); ok {
  980. sc.startFrameWrite(wr)
  981. continue
  982. }
  983. }
  984. if sc.needsFrameFlush {
  985. sc.startFrameWrite(FrameWriteRequest{write: flushFrameWriter{}})
  986. sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
  987. continue
  988. }
  989. break
  990. }
  991. sc.inFrameScheduleLoop = false
  992. }
  993. // startGracefulShutdown sends a GOAWAY with ErrCodeNo to tell the
  994. // client we're gracefully shutting down. The connection isn't closed
  995. // until all current streams are done.
  996. func (sc *serverConn) startGracefulShutdown() {
  997. sc.goAwayIn(ErrCodeNo, 0)
  998. }
  999. func (sc *serverConn) goAway(code ErrCode) {
  1000. sc.serveG.check()
  1001. var forceCloseIn time.Duration
  1002. if code != ErrCodeNo {
  1003. forceCloseIn = 250 * time.Millisecond
  1004. } else {
  1005. // TODO: configurable
  1006. forceCloseIn = 1 * time.Second
  1007. }
  1008. sc.goAwayIn(code, forceCloseIn)
  1009. }
  1010. func (sc *serverConn) goAwayIn(code ErrCode, forceCloseIn time.Duration) {
  1011. sc.serveG.check()
  1012. if sc.inGoAway {
  1013. return
  1014. }
  1015. if forceCloseIn != 0 {
  1016. sc.shutDownIn(forceCloseIn)
  1017. }
  1018. sc.inGoAway = true
  1019. sc.needToSendGoAway = true
  1020. sc.goAwayCode = code
  1021. sc.scheduleFrameWrite()
  1022. }
  1023. func (sc *serverConn) shutDownIn(d time.Duration) {
  1024. sc.serveG.check()
  1025. sc.shutdownTimer = time.NewTimer(d)
  1026. sc.shutdownTimerCh = sc.shutdownTimer.C
  1027. }
  1028. func (sc *serverConn) resetStream(se StreamError) {
  1029. sc.serveG.check()
  1030. sc.writeFrame(FrameWriteRequest{write: se})
  1031. if st, ok := sc.streams[se.StreamID]; ok {
  1032. st.resetQueued = true
  1033. }
  1034. }
  1035. // processFrameFromReader processes the serve loop's read from readFrameCh from the
  1036. // frame-reading goroutine.
  1037. // processFrameFromReader returns whether the connection should be kept open.
  1038. func (sc *serverConn) processFrameFromReader(res readFrameResult) bool {
  1039. sc.serveG.check()
  1040. err := res.err
  1041. if err != nil {
  1042. if err == ErrFrameTooLarge {
  1043. sc.goAway(ErrCodeFrameSize)
  1044. return true // goAway will close the loop
  1045. }
  1046. clientGone := err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err)
  1047. if clientGone {
  1048. // TODO: could we also get into this state if
  1049. // the peer does a half close
  1050. // (e.g. CloseWrite) because they're done
  1051. // sending frames but they're still wanting
  1052. // our open replies? Investigate.
  1053. // TODO: add CloseWrite to crypto/tls.Conn first
  1054. // so we have a way to test this? I suppose
  1055. // just for testing we could have a non-TLS mode.
  1056. return false
  1057. }
  1058. } else {
  1059. f := res.f
  1060. if VerboseLogs {
  1061. sc.vlogf("http2: server read frame %v", summarizeFrame(f))
  1062. }
  1063. err = sc.processFrame(f)
  1064. if err == nil {
  1065. return true
  1066. }
  1067. }
  1068. switch ev := err.(type) {
  1069. case StreamError:
  1070. sc.resetStream(ev)
  1071. return true
  1072. case goAwayFlowError:
  1073. sc.goAway(ErrCodeFlowControl)
  1074. return true
  1075. case ConnectionError:
  1076. sc.logf("http2: server connection error from %v: %v", sc.conn.RemoteAddr(), ev)
  1077. sc.goAway(ErrCode(ev))
  1078. return true // goAway will handle shutdown
  1079. default:
  1080. if res.err != nil {
  1081. sc.vlogf("http2: server closing client connection; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
  1082. } else {
  1083. sc.logf("http2: server closing client connection: %v", err)
  1084. }
  1085. return false
  1086. }
  1087. }
  1088. func (sc *serverConn) processFrame(f Frame) error {
  1089. sc.serveG.check()
  1090. // First frame received must be SETTINGS.
  1091. if !sc.sawFirstSettings {
  1092. if _, ok := f.(*SettingsFrame); !ok {
  1093. return ConnectionError(ErrCodeProtocol)
  1094. }
  1095. sc.sawFirstSettings = true
  1096. }
  1097. switch f := f.(type) {
  1098. case *SettingsFrame:
  1099. return sc.processSettings(f)
  1100. case *MetaHeadersFrame:
  1101. return sc.processHeaders(f)
  1102. case *WindowUpdateFrame:
  1103. return sc.processWindowUpdate(f)
  1104. case *PingFrame:
  1105. return sc.processPing(f)
  1106. case *DataFrame:
  1107. return sc.processData(f)
  1108. case *RSTStreamFrame:
  1109. return sc.processResetStream(f)
  1110. case *PriorityFrame:
  1111. return sc.processPriority(f)
  1112. case *GoAwayFrame:
  1113. return sc.processGoAway(f)
  1114. case *PushPromiseFrame:
  1115. // A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE
  1116. // frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1117. return ConnectionError(ErrCodeProtocol)
  1118. default:
  1119. sc.vlogf("http2: server ignoring frame: %v", f.Header())
  1120. return nil
  1121. }
  1122. }
  1123. func (sc *serverConn) processPing(f *PingFrame) error {
  1124. sc.serveG.check()
  1125. if f.IsAck() {
  1126. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  1127. // containing this flag."
  1128. return nil
  1129. }
  1130. if f.StreamID != 0 {
  1131. // "PING frames are not associated with any individual
  1132. // stream. If a PING frame is received with a stream
  1133. // identifier field value other than 0x0, the recipient MUST
  1134. // respond with a connection error (Section 5.4.1) of type
  1135. // PROTOCOL_ERROR."
  1136. return ConnectionError(ErrCodeProtocol)
  1137. }
  1138. if sc.inGoAway && sc.goAwayCode != ErrCodeNo {
  1139. return nil
  1140. }
  1141. sc.writeFrame(FrameWriteRequest{write: writePingAck{f}})
  1142. return nil
  1143. }
  1144. func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  1145. sc.serveG.check()
  1146. switch {
  1147. case f.StreamID != 0: // stream-level flow control
  1148. state, st := sc.state(f.StreamID)
  1149. if state == stateIdle {
  1150. // Section 5.1: "Receiving any frame other than HEADERS
  1151. // or PRIORITY on a stream in this state MUST be
  1152. // treated as a connection error (Section 5.4.1) of
  1153. // type PROTOCOL_ERROR."
  1154. return ConnectionError(ErrCodeProtocol)
  1155. }
  1156. if st == nil {
  1157. // "WINDOW_UPDATE can be sent by a peer that has sent a
  1158. // frame bearing the END_STREAM flag. This means that a
  1159. // receiver could receive a WINDOW_UPDATE frame on a "half
  1160. // closed (remote)" or "closed" stream. A receiver MUST
  1161. // NOT treat this as an error, see Section 5.1."
  1162. return nil
  1163. }
  1164. if !st.flow.add(int32(f.Increment)) {
  1165. return streamError(f.StreamID, ErrCodeFlowControl)
  1166. }
  1167. default: // connection-level flow control
  1168. if !sc.flow.add(int32(f.Increment)) {
  1169. return goAwayFlowError{}
  1170. }
  1171. }
  1172. sc.scheduleFrameWrite()
  1173. return nil
  1174. }
  1175. func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
  1176. sc.serveG.check()
  1177. state, st := sc.state(f.StreamID)
  1178. if state == stateIdle {
  1179. // 6.4 "RST_STREAM frames MUST NOT be sent for a
  1180. // stream in the "idle" state. If a RST_STREAM frame
  1181. // identifying an idle stream is received, the
  1182. // recipient MUST treat this as a connection error
  1183. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1184. return ConnectionError(ErrCodeProtocol)
  1185. }
  1186. if st != nil {
  1187. st.cancelCtx()
  1188. sc.closeStream(st, streamError(f.StreamID, f.ErrCode))
  1189. }
  1190. return nil
  1191. }
  1192. func (sc *serverConn) closeStream(st *stream, err error) {
  1193. sc.serveG.check()
  1194. if st.state == stateIdle || st.state == stateClosed {
  1195. panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
  1196. }
  1197. st.state = stateClosed
  1198. if st.isPushed() {
  1199. sc.curPushedStreams--
  1200. } else {
  1201. sc.curClientStreams--
  1202. }
  1203. delete(sc.streams, st.id)
  1204. if len(sc.streams) == 0 {
  1205. sc.setConnState(http.StateIdle)
  1206. if sc.srv.IdleTimeout != 0 {
  1207. sc.idleTimer.Reset(sc.srv.IdleTimeout)
  1208. }
  1209. if h1ServerKeepAlivesDisabled(sc.hs) {
  1210. sc.startGracefulShutdown()
  1211. }
  1212. }
  1213. if p := st.body; p != nil {
  1214. // Return any buffered unread bytes worth of conn-level flow control.
  1215. // See golang.org/issue/16481
  1216. sc.sendWindowUpdate(nil, p.Len())
  1217. p.CloseWithError(err)
  1218. }
  1219. st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc
  1220. sc.writeSched.CloseStream(st.id)
  1221. }
  1222. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  1223. sc.serveG.check()
  1224. if f.IsAck() {
  1225. sc.unackedSettings--
  1226. if sc.unackedSettings < 0 {
  1227. // Why is the peer ACKing settings we never sent?
  1228. // The spec doesn't mention this case, but
  1229. // hang up on them anyway.
  1230. return ConnectionError(ErrCodeProtocol)
  1231. }
  1232. return nil
  1233. }
  1234. if err := f.ForeachSetting(sc.processSetting); err != nil {
  1235. return err
  1236. }
  1237. sc.needToSendSettingsAck = true
  1238. sc.scheduleFrameWrite()
  1239. return nil
  1240. }
  1241. func (sc *serverConn) processSetting(s Setting) error {
  1242. sc.serveG.check()
  1243. if err := s.Valid(); err != nil {
  1244. return err
  1245. }
  1246. if VerboseLogs {
  1247. sc.vlogf("http2: server processing setting %v", s)
  1248. }
  1249. switch s.ID {
  1250. case SettingHeaderTableSize:
  1251. sc.headerTableSize = s.Val
  1252. sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
  1253. case SettingEnablePush:
  1254. sc.pushEnabled = s.Val != 0
  1255. case SettingMaxConcurrentStreams:
  1256. sc.clientMaxStreams = s.Val
  1257. case SettingInitialWindowSize:
  1258. return sc.processSettingInitialWindowSize(s.Val)
  1259. case SettingMaxFrameSize:
  1260. sc.maxFrameSize = int32(s.Val) // the maximum valid s.Val is < 2^31
  1261. case SettingMaxHeaderListSize:
  1262. sc.peerMaxHeaderListSize = s.Val
  1263. default:
  1264. // Unknown setting: "An endpoint that receives a SETTINGS
  1265. // frame with any unknown or unsupported identifier MUST
  1266. // ignore that setting."
  1267. if VerboseLogs {
  1268. sc.vlogf("http2: server ignoring unknown setting %v", s)
  1269. }
  1270. }
  1271. return nil
  1272. }
  1273. func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  1274. sc.serveG.check()
  1275. // Note: val already validated to be within range by
  1276. // processSetting's Valid call.
  1277. // "A SETTINGS frame can alter the initial flow control window
  1278. // size for all current streams. When the value of
  1279. // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  1280. // adjust the size of all stream flow control windows that it
  1281. // maintains by the difference between the new value and the
  1282. // old value."
  1283. old := sc.initialWindowSize
  1284. sc.initialWindowSize = int32(val)
  1285. growth := sc.initialWindowSize - old // may be negative
  1286. for _, st := range sc.streams {
  1287. if !st.flow.add(growth) {
  1288. // 6.9.2 Initial Flow Control Window Size
  1289. // "An endpoint MUST treat a change to
  1290. // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  1291. // control window to exceed the maximum size as a
  1292. // connection error (Section 5.4.1) of type
  1293. // FLOW_CONTROL_ERROR."
  1294. return ConnectionError(ErrCodeFlowControl)
  1295. }
  1296. }
  1297. return nil
  1298. }
  1299. func (sc *serverConn) processData(f *DataFrame) error {
  1300. sc.serveG.check()
  1301. if sc.inGoAway && sc.goAwayCode != ErrCodeNo {
  1302. return nil
  1303. }
  1304. data := f.Data()
  1305. // "If a DATA frame is received whose stream is not in "open"
  1306. // or "half closed (local)" state, the recipient MUST respond
  1307. // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  1308. id := f.Header().StreamID
  1309. state, st := sc.state(id)
  1310. if id == 0 || state == stateIdle {
  1311. // Section 5.1: "Receiving any frame other than HEADERS
  1312. // or PRIORITY on a stream in this state MUST be
  1313. // treated as a connection error (Section 5.4.1) of
  1314. // type PROTOCOL_ERROR."
  1315. return ConnectionError(ErrCodeProtocol)
  1316. }
  1317. if st == nil || state != stateOpen || st.gotTrailerHeader || st.resetQueued {
  1318. // This includes sending a RST_STREAM if the stream is
  1319. // in stateHalfClosedLocal (which currently means that
  1320. // the http.Handler returned, so it's done reading &
  1321. // done writing). Try to stop the client from sending
  1322. // more DATA.
  1323. // But still enforce their connection-level flow control,
  1324. // and return any flow control bytes since we're not going
  1325. // to consume them.
  1326. if sc.inflow.available() < int32(f.Length) {
  1327. return streamError(id, ErrCodeFlowControl)
  1328. }
  1329. // Deduct the flow control from inflow, since we're
  1330. // going to immediately add it back in
  1331. // sendWindowUpdate, which also schedules sending the
  1332. // frames.
  1333. sc.inflow.take(int32(f.Length))
  1334. sc.sendWindowUpdate(nil, int(f.Length)) // conn-level
  1335. if st != nil && st.resetQueued {
  1336. // Already have a stream error in flight. Don't send another.
  1337. return nil
  1338. }
  1339. return streamError(id, ErrCodeStreamClosed)
  1340. }
  1341. if st.body == nil {
  1342. panic("internal error: should have a body in this state")
  1343. }
  1344. // Sender sending more than they'd declared?
  1345. if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  1346. st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  1347. return streamError(id, ErrCodeStreamClosed)
  1348. }
  1349. if f.Length > 0 {
  1350. // Check whether the client has flow control quota.
  1351. if st.inflow.available() < int32(f.Length) {
  1352. return streamError(id, ErrCodeFlowControl)
  1353. }
  1354. st.inflow.take(int32(f.Length))
  1355. if len(data) > 0 {
  1356. wrote, err := st.body.Write(data)
  1357. if err != nil {
  1358. return streamError(id, ErrCodeStreamClosed)
  1359. }
  1360. if wrote != len(data) {
  1361. panic("internal error: bad Writer")
  1362. }
  1363. st.bodyBytes += int64(len(data))
  1364. }
  1365. // Return any padded flow control now, since we won't
  1366. // refund it later on body reads.
  1367. if pad := int32(f.Length) - int32(len(data)); pad > 0 {
  1368. sc.sendWindowUpdate32(nil, pad)
  1369. sc.sendWindowUpdate32(st, pad)
  1370. }
  1371. }
  1372. if f.StreamEnded() {
  1373. st.endStream()
  1374. }
  1375. return nil
  1376. }
  1377. func (sc *serverConn) processGoAway(f *GoAwayFrame) error {
  1378. sc.serveG.check()
  1379. if f.ErrCode != ErrCodeNo {
  1380. sc.logf("http2: received GOAWAY %+v, starting graceful shutdown", f)
  1381. } else {
  1382. sc.vlogf("http2: received GOAWAY %+v, starting graceful shutdown", f)
  1383. }
  1384. sc.startGracefulShutdown()
  1385. // http://tools.ietf.org/html/rfc7540#section-6.8
  1386. // We should not create any new streams, which means we should disable push.
  1387. sc.pushEnabled = false
  1388. return nil
  1389. }
  1390. // isPushed reports whether the stream is server-initiated.
  1391. func (st *stream) isPushed() bool {
  1392. return st.id%2 == 0
  1393. }
  1394. // endStream closes a Request.Body's pipe. It is called when a DATA
  1395. // frame says a request body is over (or after trailers).
  1396. func (st *stream) endStream() {
  1397. sc := st.sc
  1398. sc.serveG.check()
  1399. if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  1400. st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
  1401. st.declBodyBytes, st.bodyBytes))
  1402. } else {
  1403. st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest)
  1404. st.body.CloseWithError(io.EOF)
  1405. }
  1406. st.state = stateHalfClosedRemote
  1407. }
  1408. // copyTrailersToHandlerRequest is run in the Handler's goroutine in
  1409. // its Request.Body.Read just before it gets io.EOF.
  1410. func (st *stream) copyTrailersToHandlerRequest() {
  1411. for k, vv := range st.trailer {
  1412. if _, ok := st.reqTrailer[k]; ok {
  1413. // Only copy it over it was pre-declared.
  1414. st.reqTrailer[k] = vv
  1415. }
  1416. }
  1417. }
  1418. func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error {
  1419. sc.serveG.check()
  1420. id := f.StreamID
  1421. if sc.inGoAway {
  1422. // Ignore.
  1423. return nil
  1424. }
  1425. // http://tools.ietf.org/html/rfc7540#section-5.1.1
  1426. // Streams initiated by a client MUST use odd-numbered stream
  1427. // identifiers. [...] An endpoint that receives an unexpected
  1428. // stream identifier MUST respond with a connection error
  1429. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1430. if id%2 != 1 {
  1431. return ConnectionError(ErrCodeProtocol)
  1432. }
  1433. // A HEADERS frame can be used to create a new stream or
  1434. // send a trailer for an open one. If we already have a stream
  1435. // open, let it process its own HEADERS frame (trailers at this
  1436. // point, if it's valid).
  1437. if st := sc.streams[f.StreamID]; st != nil {
  1438. if st.resetQueued {
  1439. // We're sending RST_STREAM to close the stream, so don't bother
  1440. // processing this frame.
  1441. return nil
  1442. }
  1443. return st.processTrailerHeaders(f)
  1444. }
  1445. // [...] The identifier of a newly established stream MUST be
  1446. // numerically greater than all streams that the initiating
  1447. // endpoint has opened or reserved. [...] An endpoint that
  1448. // receives an unexpected stream identifier MUST respond with
  1449. // a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1450. if id <= sc.maxClientStreamID {
  1451. return ConnectionError(ErrCodeProtocol)
  1452. }
  1453. sc.maxClientStreamID = id
  1454. if sc.idleTimer != nil {
  1455. sc.idleTimer.Stop()
  1456. }
  1457. // http://tools.ietf.org/html/rfc7540#section-5.1.2
  1458. // [...] Endpoints MUST NOT exceed the limit set by their peer. An
  1459. // endpoint that receives a HEADERS frame that causes their
  1460. // advertised concurrent stream limit to be exceeded MUST treat
  1461. // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR
  1462. // or REFUSED_STREAM.
  1463. if sc.curClientStreams+1 > sc.advMaxStreams {
  1464. if sc.unackedSettings == 0 {
  1465. // They should know better.
  1466. return streamError(id, ErrCodeProtocol)
  1467. }
  1468. // Assume it's a network race, where they just haven't
  1469. // received our last SETTINGS update. But actually
  1470. // this can't happen yet, because we don't yet provide
  1471. // a way for users to adjust server parameters at
  1472. // runtime.
  1473. return streamError(id, ErrCodeRefusedStream)
  1474. }
  1475. initialState := stateOpen
  1476. if f.StreamEnded() {
  1477. initialState = stateHalfClosedRemote
  1478. }
  1479. st := sc.newStream(id, 0, initialState)
  1480. if f.HasPriority() {
  1481. if err := checkPriority(f.StreamID, f.Priority); err != nil {
  1482. return err
  1483. }
  1484. sc.writeSched.AdjustStream(st.id, f.Priority)
  1485. }
  1486. rw, req, err := sc.newWriterAndRequest(st, f)
  1487. if err != nil {
  1488. return err
  1489. }
  1490. st.reqTrailer = req.Trailer
  1491. if st.reqTrailer != nil {
  1492. st.trailer = make(http.Header)
  1493. }
  1494. st.body = req.Body.(*requestBody).pipe // may be nil
  1495. st.declBodyBytes = req.ContentLength
  1496. handler := sc.handler.ServeHTTP
  1497. if f.Truncated {
  1498. // Their header list was too long. Send a 431 error.
  1499. handler = handleHeaderListTooLong
  1500. } else if err := checkValidHTTP2RequestHeaders(req.Header); err != nil {
  1501. handler = new400Handler(err)
  1502. }
  1503. // The net/http package sets the read deadline from the
  1504. // http.Server.ReadTimeout during the TLS handshake, but then
  1505. // passes the connection off to us with the deadline already
  1506. // set. Disarm it here after the request headers are read,
  1507. // similar to how the http1 server works. Here it's
  1508. // technically more like the http1 Server's ReadHeaderTimeout
  1509. // (in Go 1.8), though. That's a more sane option anyway.
  1510. if sc.hs.ReadTimeout != 0 {
  1511. sc.conn.SetReadDeadline(time.Time{})
  1512. }
  1513. go sc.runHandler(rw, req, handler)
  1514. return nil
  1515. }
  1516. func (st *stream) processTrailerHeaders(f *MetaHeadersFrame) error {
  1517. sc := st.sc
  1518. sc.serveG.check()
  1519. if st.gotTrailerHeader {
  1520. return ConnectionError(ErrCodeProtocol)
  1521. }
  1522. st.gotTrailerHeader = true
  1523. if !f.StreamEnded() {
  1524. return streamError(st.id, ErrCodeProtocol)
  1525. }
  1526. if len(f.PseudoFields()) > 0 {
  1527. return streamError(st.id, ErrCodeProtocol)
  1528. }
  1529. if st.trailer != nil {
  1530. for _, hf := range f.RegularFields() {
  1531. key := sc.canonicalHeader(hf.Name)
  1532. if !ValidTrailerHeader(key) {
  1533. // TODO: send more details to the peer somehow. But http2 has
  1534. // no way to send debug data at a stream level. Discuss with
  1535. // HTTP folk.
  1536. return streamError(st.id, ErrCodeProtocol)
  1537. }
  1538. st.trailer[key] = append(st.trailer[key], hf.Value)
  1539. }
  1540. }
  1541. st.endStream()
  1542. return nil
  1543. }
  1544. func checkPriority(streamID uint32, p PriorityParam) error {
  1545. if streamID == p.StreamDep {
  1546. // Section 5.3.1: "A stream cannot depend on itself. An endpoint MUST treat
  1547. // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR."
  1548. // Section 5.3.3 says that a stream can depend on one of its dependencies,
  1549. // so it's only self-dependencies that are forbidden.
  1550. return streamError(streamID, ErrCodeProtocol)
  1551. }
  1552. return nil
  1553. }
  1554. func (sc *serverConn) processPriority(f *PriorityFrame) error {
  1555. if sc.inGoAway {
  1556. return nil
  1557. }
  1558. if err := checkPriority(f.StreamID, f.PriorityParam); err != nil {
  1559. return err
  1560. }
  1561. sc.writeSched.AdjustStream(f.StreamID, f.PriorityParam)
  1562. return nil
  1563. }
  1564. func (sc *serverConn) newStream(id, pusherID uint32, state streamState) *stream {
  1565. sc.serveG.check()
  1566. if id == 0 {
  1567. panic("internal error: cannot create stream with id 0")
  1568. }
  1569. ctx, cancelCtx := contextWithCancel(sc.baseCtx)
  1570. st := &stream{
  1571. sc: sc,
  1572. id: id,
  1573. state: state,
  1574. ctx: ctx,
  1575. cancelCtx: cancelCtx,
  1576. }
  1577. st.cw.Init()
  1578. st.flow.conn = &sc.flow // link to conn-level counter
  1579. st.flow.add(sc.initialWindowSize)
  1580. st.inflow.conn = &sc.inflow // link to conn-level counter
  1581. st.inflow.add(initialWindowSize) // TODO: update this when we send a higher initial window size in the initial settings
  1582. sc.streams[id] = st
  1583. sc.writeSched.OpenStream(st.id, OpenStreamOptions{PusherID: pusherID})
  1584. if st.isPushed() {
  1585. sc.curPushedStreams++
  1586. } else {
  1587. sc.curClientStreams++
  1588. }
  1589. if sc.curOpenStreams() == 1 {
  1590. sc.setConnState(http.StateActive)
  1591. }
  1592. return st
  1593. }
  1594. func (sc *serverConn) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*responseWriter, *http.Request, error) {
  1595. sc.serveG.check()
  1596. rp := requestParam{
  1597. method: f.PseudoValue("method"),
  1598. scheme: f.PseudoValue("scheme"),
  1599. authority: f.PseudoValue("authority"),
  1600. path: f.PseudoValue("path"),
  1601. }
  1602. isConnect := rp.method == "CONNECT"
  1603. if isConnect {
  1604. if rp.path != "" || rp.scheme != "" || rp.authority == "" {
  1605. return nil, nil, streamError(f.StreamID, ErrCodeProtocol)
  1606. }
  1607. } else if rp.method == "" || rp.path == "" || (rp.scheme != "https" && rp.scheme != "http") {
  1608. // See 8.1.2.6 Malformed Requests and Responses:
  1609. //
  1610. // Malformed requests or responses that are detected
  1611. // MUST be treated as a stream error (Section 5.4.2)
  1612. // of type PROTOCOL_ERROR."
  1613. //
  1614. // 8.1.2.3 Request Pseudo-Header Fields
  1615. // "All HTTP/2 requests MUST include exactly one valid
  1616. // value for the :method, :scheme, and :path
  1617. // pseudo-header fields"
  1618. return nil, nil, streamError(f.StreamID, ErrCodeProtocol)
  1619. }
  1620. bodyOpen := !f.StreamEnded()
  1621. if rp.method == "HEAD" && bodyOpen {
  1622. // HEAD requests can't have bodies
  1623. return nil, nil, streamError(f.StreamID, ErrCodeProtocol)
  1624. }
  1625. rp.header = make(http.Header)
  1626. for _, hf := range f.RegularFields() {
  1627. rp.header.Add(sc.canonicalHeader(hf.Name), hf.Value)
  1628. }
  1629. if rp.authority == "" {
  1630. rp.authority = rp.header.Get("Host")
  1631. }
  1632. rw, req, err := sc.newWriterAndRequestNoBody(st, rp)
  1633. if err != nil {
  1634. return nil, nil, err
  1635. }
  1636. if bodyOpen {
  1637. st.reqBuf = getRequestBodyBuf()
  1638. req.Body.(*requestBody).pipe = &pipe{
  1639. b: &fixedBuffer{buf: st.reqBuf},
  1640. }
  1641. if vv, ok := rp.header["Content-Length"]; ok {
  1642. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  1643. } else {
  1644. req.ContentLength = -1
  1645. }
  1646. }
  1647. return rw, req, nil
  1648. }
  1649. type requestParam struct {
  1650. method string
  1651. scheme, authority, path string
  1652. header http.Header
  1653. }
  1654. func (sc *serverConn) newWriterAndRequestNoBody(st *stream, rp requestParam) (*responseWriter, *http.Request, error) {
  1655. sc.serveG.check()
  1656. var tlsState *tls.ConnectionState // nil if not scheme https
  1657. if rp.scheme == "https" {
  1658. tlsState = sc.tlsState
  1659. }
  1660. needsContinue := rp.header.Get("Expect") == "100-continue"
  1661. if needsContinue {
  1662. rp.header.Del("Expect")
  1663. }
  1664. // Merge Cookie headers into one "; "-delimited value.
  1665. if cookies := rp.header["Cookie"]; len(cookies) > 1 {
  1666. rp.header.Set("Cookie", strings.Join(cookies, "; "))
  1667. }
  1668. // Setup Trailers
  1669. var trailer http.Header
  1670. for _, v := range rp.header["Trailer"] {
  1671. for _, key := range strings.Split(v, ",") {
  1672. key = http.CanonicalHeaderKey(strings.TrimSpace(key))
  1673. switch key {
  1674. case "Transfer-Encoding", "Trailer", "Content-Length":
  1675. // Bogus. (copy of http1 rules)
  1676. // Ignore.
  1677. default:
  1678. if trailer == nil {
  1679. trailer = make(http.Header)
  1680. }
  1681. trailer[key] = nil
  1682. }
  1683. }
  1684. }
  1685. delete(rp.header, "Trailer")
  1686. var url_ *url.URL
  1687. var requestURI string
  1688. if rp.method == "CONNECT" {
  1689. url_ = &url.URL{Host: rp.authority}
  1690. requestURI = rp.authority // mimic HTTP/1 server behavior
  1691. } else {
  1692. var err error
  1693. url_, err = url.ParseRequestURI(rp.path)
  1694. if err != nil {
  1695. return nil, nil, streamError(st.id, ErrCodeProtocol)
  1696. }
  1697. requestURI = rp.path
  1698. }
  1699. body := &requestBody{
  1700. conn: sc,
  1701. stream: st,
  1702. needsContinue: needsContinue,
  1703. }
  1704. req := &http.Request{
  1705. Method: rp.method,
  1706. URL: url_,
  1707. RemoteAddr: sc.remoteAddrStr,
  1708. Header: rp.header,
  1709. RequestURI: requestURI,
  1710. Proto: "HTTP/2.0",
  1711. ProtoMajor: 2,
  1712. ProtoMinor: 0,
  1713. TLS: tlsState,
  1714. Host: rp.authority,
  1715. Body: body,
  1716. Trailer: trailer,
  1717. }
  1718. req = requestWithContext(req, st.ctx)
  1719. rws := responseWriterStatePool.Get().(*responseWriterState)
  1720. bwSave := rws.bw
  1721. *rws = responseWriterState{} // zero all the fields
  1722. rws.conn = sc
  1723. rws.bw = bwSave
  1724. rws.bw.Reset(chunkWriter{rws})
  1725. rws.stream = st
  1726. rws.req = req
  1727. rws.body = body
  1728. rw := &responseWriter{rws: rws}
  1729. return rw, req, nil
  1730. }
  1731. var reqBodyCache = make(chan []byte, 8)
  1732. func getRequestBodyBuf() []byte {
  1733. select {
  1734. case b := <-reqBodyCache:
  1735. return b
  1736. default:
  1737. return make([]byte, initialWindowSize)
  1738. }
  1739. }
  1740. func putRequestBodyBuf(b []byte) {
  1741. select {
  1742. case reqBodyCache <- b:
  1743. default:
  1744. }
  1745. }
  1746. // Run on its own goroutine.
  1747. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) {
  1748. didPanic := true
  1749. defer func() {
  1750. rw.rws.stream.cancelCtx()
  1751. if didPanic {
  1752. e := recover()
  1753. sc.writeFrameFromHandler(FrameWriteRequest{
  1754. write: handlerPanicRST{rw.rws.stream.id},
  1755. stream: rw.rws.stream,
  1756. })
  1757. // Same as net/http:
  1758. if shouldLogPanic(e) {
  1759. const size = 64 << 10
  1760. buf := make([]byte, size)
  1761. buf = buf[:runtime.Stack(buf, false)]
  1762. sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf)
  1763. }
  1764. return
  1765. }
  1766. rw.handlerDone()
  1767. }()
  1768. handler(rw, req)
  1769. didPanic = false
  1770. }
  1771. func handleHeaderListTooLong(w http.ResponseWriter, r *http.Request) {
  1772. // 10.5.1 Limits on Header Block Size:
  1773. // .. "A server that receives a larger header block than it is
  1774. // willing to handle can send an HTTP 431 (Request Header Fields Too
  1775. // Large) status code"
  1776. const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+
  1777. w.WriteHeader(statusRequestHeaderFieldsTooLarge)
  1778. io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
  1779. }
  1780. // called from handler goroutines.
  1781. // h may be nil.
  1782. func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error {
  1783. sc.serveG.checkNotOn() // NOT on
  1784. var errc chan error
  1785. if headerData.h != nil {
  1786. // If there's a header map (which we don't own), so we have to block on
  1787. // waiting for this frame to be written, so an http.Flush mid-handler
  1788. // writes out the correct value of keys, before a handler later potentially
  1789. // mutates it.
  1790. errc = errChanPool.Get().(chan error)
  1791. }
  1792. if err := sc.writeFrameFromHandler(FrameWriteRequest{
  1793. write: headerData,
  1794. stream: st,
  1795. done: errc,
  1796. }); err != nil {
  1797. return err
  1798. }
  1799. if errc != nil {
  1800. select {
  1801. case err := <-errc:
  1802. errChanPool.Put(errc)
  1803. return err
  1804. case <-sc.doneServing:
  1805. return errClientDisconnected
  1806. case <-st.cw:
  1807. return errStreamClosed
  1808. }
  1809. }
  1810. return nil
  1811. }
  1812. // called from handler goroutines.
  1813. func (sc *serverConn) write100ContinueHeaders(st *stream) {
  1814. sc.writeFrameFromHandler(FrameWriteRequest{
  1815. write: write100ContinueHeadersFrame{st.id},
  1816. stream: st,
  1817. })
  1818. }
  1819. // A bodyReadMsg tells the server loop that the http.Handler read n
  1820. // bytes of the DATA from the client on the given stream.
  1821. type bodyReadMsg struct {
  1822. st *stream
  1823. n int
  1824. }
  1825. // called from handler goroutines.
  1826. // Notes that the handler for the given stream ID read n bytes of its body
  1827. // and schedules flow control tokens to be sent.
  1828. func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int, err error) {
  1829. sc.serveG.checkNotOn() // NOT on
  1830. if n > 0 {
  1831. select {
  1832. case sc.bodyReadCh <- bodyReadMsg{st, n}:
  1833. case <-sc.doneServing:
  1834. }
  1835. }
  1836. if err == io.EOF {
  1837. if buf := st.reqBuf; buf != nil {
  1838. st.reqBuf = nil // shouldn't matter; field unused by other
  1839. putRequestBodyBuf(buf)
  1840. }
  1841. }
  1842. }
  1843. func (sc *serverConn) noteBodyRead(st *stream, n int) {
  1844. sc.serveG.check()
  1845. sc.sendWindowUpdate(nil, n) // conn-level
  1846. if st.state != stateHalfClosedRemote && st.state != stateClosed {
  1847. // Don't send this WINDOW_UPDATE if the stream is closed
  1848. // remotely.
  1849. sc.sendWindowUpdate(st, n)
  1850. }
  1851. }
  1852. // st may be nil for conn-level
  1853. func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
  1854. sc.serveG.check()
  1855. // "The legal range for the increment to the flow control
  1856. // window is 1 to 2^31-1 (2,147,483,647) octets."
  1857. // A Go Read call on 64-bit machines could in theory read
  1858. // a larger Read than this. Very unlikely, but we handle it here
  1859. // rather than elsewhere for now.
  1860. const maxUint31 = 1<<31 - 1
  1861. for n >= maxUint31 {
  1862. sc.sendWindowUpdate32(st, maxUint31)
  1863. n -= maxUint31
  1864. }
  1865. sc.sendWindowUpdate32(st, int32(n))
  1866. }
  1867. // st may be nil for conn-level
  1868. func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) {
  1869. sc.serveG.check()
  1870. if n == 0 {
  1871. return
  1872. }
  1873. if n < 0 {
  1874. panic("negative update")
  1875. }
  1876. var streamID uint32
  1877. if st != nil {
  1878. streamID = st.id
  1879. }
  1880. sc.writeFrame(FrameWriteRequest{
  1881. write: writeWindowUpdate{streamID: streamID, n: uint32(n)},
  1882. stream: st,
  1883. })
  1884. var ok bool
  1885. if st == nil {
  1886. ok = sc.inflow.add(n)
  1887. } else {
  1888. ok = st.inflow.add(n)
  1889. }
  1890. if !ok {
  1891. panic("internal error; sent too many window updates without decrements?")
  1892. }
  1893. }
  1894. // requestBody is the Handler's Request.Body type.
  1895. // Read and Close may be called concurrently.
  1896. type requestBody struct {
  1897. stream *stream
  1898. conn *serverConn
  1899. closed bool // for use by Close only
  1900. sawEOF bool // for use by Read only
  1901. pipe *pipe // non-nil if we have a HTTP entity message body
  1902. needsContinue bool // need to send a 100-continue
  1903. }
  1904. func (b *requestBody) Close() error {
  1905. if b.pipe != nil && !b.closed {
  1906. b.pipe.BreakWithError(errClosedBody)
  1907. }
  1908. b.closed = true
  1909. return nil
  1910. }
  1911. func (b *requestBody) Read(p []byte) (n int, err error) {
  1912. if b.needsContinue {
  1913. b.needsContinue = false
  1914. b.conn.write100ContinueHeaders(b.stream)
  1915. }
  1916. if b.pipe == nil || b.sawEOF {
  1917. return 0, io.EOF
  1918. }
  1919. n, err = b.pipe.Read(p)
  1920. if err == io.EOF {
  1921. b.sawEOF = true
  1922. }
  1923. if b.conn == nil && inTests {
  1924. return
  1925. }
  1926. b.conn.noteBodyReadFromHandler(b.stream, n, err)
  1927. return
  1928. }
  1929. // responseWriter is the http.ResponseWriter implementation. It's
  1930. // intentionally small (1 pointer wide) to minimize garbage. The
  1931. // responseWriterState pointer inside is zeroed at the end of a
  1932. // request (in handlerDone) and calls on the responseWriter thereafter
  1933. // simply crash (caller's mistake), but the much larger responseWriterState
  1934. // and buffers are reused between multiple requests.
  1935. type responseWriter struct {
  1936. rws *responseWriterState
  1937. }
  1938. // Optional http.ResponseWriter interfaces implemented.
  1939. var (
  1940. _ http.CloseNotifier = (*responseWriter)(nil)
  1941. _ http.Flusher = (*responseWriter)(nil)
  1942. _ stringWriter = (*responseWriter)(nil)
  1943. )
  1944. type responseWriterState struct {
  1945. // immutable within a request:
  1946. stream *stream
  1947. req *http.Request
  1948. body *requestBody // to close at end of request, if DATA frames didn't
  1949. conn *serverConn
  1950. // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
  1951. bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
  1952. // mutated by http.Handler goroutine:
  1953. handlerHeader http.Header // nil until called
  1954. snapHeader http.Header // snapshot of handlerHeader at WriteHeader time
  1955. trailers []string // set in writeChunk
  1956. status int // status code passed to WriteHeader
  1957. wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
  1958. sentHeader bool // have we sent the header frame?
  1959. handlerDone bool // handler has finished
  1960. sentContentLen int64 // non-zero if handler set a Content-Length header
  1961. wroteBytes int64
  1962. closeNotifierMu sync.Mutex // guards closeNotifierCh
  1963. closeNotifierCh chan bool // nil until first used
  1964. }
  1965. type chunkWriter struct{ rws *responseWriterState }
  1966. func (cw chunkWriter) Write(p []byte) (n int, err error) { return cw.rws.writeChunk(p) }
  1967. func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) != 0 }
  1968. // declareTrailer is called for each Trailer header when the
  1969. // response header is written. It notes that a header will need to be
  1970. // written in the trailers at the end of the response.
  1971. func (rws *responseWriterState) declareTrailer(k string) {
  1972. k = http.CanonicalHeaderKey(k)
  1973. if !ValidTrailerHeader(k) {
  1974. // Forbidden by RFC 2616 14.40.
  1975. rws.conn.logf("ignoring invalid trailer %q", k)
  1976. return
  1977. }
  1978. if !strSliceContains(rws.trailers, k) {
  1979. rws.trailers = append(rws.trailers, k)
  1980. }
  1981. }
  1982. // writeChunk writes chunks from the bufio.Writer. But because
  1983. // bufio.Writer may bypass its chunking, sometimes p may be
  1984. // arbitrarily large.
  1985. //
  1986. // writeChunk is also responsible (on the first chunk) for sending the
  1987. // HEADER response.
  1988. func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
  1989. if !rws.wroteHeader {
  1990. rws.writeHeader(200)
  1991. }
  1992. isHeadResp := rws.req.Method == "HEAD"
  1993. if !rws.sentHeader {
  1994. rws.sentHeader = true
  1995. var ctype, clen string
  1996. if clen = rws.snapHeader.Get("Content-Length"); clen != "" {
  1997. rws.snapHeader.Del("Content-Length")
  1998. clen64, err := strconv.ParseInt(clen, 10, 64)
  1999. if err == nil && clen64 >= 0 {
  2000. rws.sentContentLen = clen64
  2001. } else {
  2002. clen = ""
  2003. }
  2004. }
  2005. if clen == "" && rws.handlerDone && bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) {
  2006. clen = strconv.Itoa(len(p))
  2007. }
  2008. _, hasContentType := rws.snapHeader["Content-Type"]
  2009. if !hasContentType && bodyAllowedForStatus(rws.status) {
  2010. ctype = http.DetectContentType(p)
  2011. }
  2012. var date string
  2013. if _, ok := rws.snapHeader["Date"]; !ok {
  2014. // TODO(bradfitz): be faster here, like net/http? measure.
  2015. date = time.Now().UTC().Format(http.TimeFormat)
  2016. }
  2017. for _, v := range rws.snapHeader["Trailer"] {
  2018. foreachHeaderElement(v, rws.declareTrailer)
  2019. }
  2020. endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp
  2021. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  2022. streamID: rws.stream.id,
  2023. httpResCode: rws.status,
  2024. h: rws.snapHeader,
  2025. endStream: endStream,
  2026. contentType: ctype,
  2027. contentLength: clen,
  2028. date: date,
  2029. })
  2030. if err != nil {
  2031. return 0, err
  2032. }
  2033. if endStream {
  2034. return 0, nil
  2035. }
  2036. }
  2037. if isHeadResp {
  2038. return len(p), nil
  2039. }
  2040. if len(p) == 0 && !rws.handlerDone {
  2041. return 0, nil
  2042. }
  2043. if rws.handlerDone {
  2044. rws.promoteUndeclaredTrailers()
  2045. }
  2046. endStream := rws.handlerDone && !rws.hasTrailers()
  2047. if len(p) > 0 || endStream {
  2048. // only send a 0 byte DATA frame if we're ending the stream.
  2049. if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil {
  2050. return 0, err
  2051. }
  2052. }
  2053. if rws.handlerDone && rws.hasTrailers() {
  2054. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  2055. streamID: rws.stream.id,
  2056. h: rws.handlerHeader,
  2057. trailers: rws.trailers,
  2058. endStream: true,
  2059. })
  2060. return len(p), err
  2061. }
  2062. return len(p), nil
  2063. }
  2064. // TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
  2065. // that, if present, signals that the map entry is actually for
  2066. // the response trailers, and not the response headers. The prefix
  2067. // is stripped after the ServeHTTP call finishes and the values are
  2068. // sent in the trailers.
  2069. //
  2070. // This mechanism is intended only for trailers that are not known
  2071. // prior to the headers being written. If the set of trailers is fixed
  2072. // or known before the header is written, the normal Go trailers mechanism
  2073. // is preferred:
  2074. // https://golang.org/pkg/net/http/#ResponseWriter
  2075. // https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
  2076. const TrailerPrefix = "Trailer:"
  2077. // promoteUndeclaredTrailers permits http.Handlers to set trailers
  2078. // after the header has already been flushed. Because the Go
  2079. // ResponseWriter interface has no way to set Trailers (only the
  2080. // Header), and because we didn't want to expand the ResponseWriter
  2081. // interface, and because nobody used trailers, and because RFC 2616
  2082. // says you SHOULD (but not must) predeclare any trailers in the
  2083. // header, the official ResponseWriter rules said trailers in Go must
  2084. // be predeclared, and then we reuse the same ResponseWriter.Header()
  2085. // map to mean both Headers and Trailers. When it's time to write the
  2086. // Trailers, we pick out the fields of Headers that were declared as
  2087. // trailers. That worked for a while, until we found the first major
  2088. // user of Trailers in the wild: gRPC (using them only over http2),
  2089. // and gRPC libraries permit setting trailers mid-stream without
  2090. // predeclarnig them. So: change of plans. We still permit the old
  2091. // way, but we also permit this hack: if a Header() key begins with
  2092. // "Trailer:", the suffix of that key is a Trailer. Because ':' is an
  2093. // invalid token byte anyway, there is no ambiguity. (And it's already
  2094. // filtered out) It's mildly hacky, but not terrible.
  2095. //
  2096. // This method runs after the Handler is done and promotes any Header
  2097. // fields to be trailers.
  2098. func (rws *responseWriterState) promoteUndeclaredTrailers() {
  2099. for k, vv := range rws.handlerHeader {
  2100. if !strings.HasPrefix(k, TrailerPrefix) {
  2101. continue
  2102. }
  2103. trailerKey := strings.TrimPrefix(k, TrailerPrefix)
  2104. rws.declareTrailer(trailerKey)
  2105. rws.handlerHeader[http.CanonicalHeaderKey(trailerKey)] = vv
  2106. }
  2107. if len(rws.trailers) > 1 {
  2108. sorter := sorterPool.Get().(*sorter)
  2109. sorter.SortStrings(rws.trailers)
  2110. sorterPool.Put(sorter)
  2111. }
  2112. }
  2113. func (w *responseWriter) Flush() {
  2114. rws := w.rws
  2115. if rws == nil {
  2116. panic("Header called after Handler finished")
  2117. }
  2118. if rws.bw.Buffered() > 0 {
  2119. if err := rws.bw.Flush(); err != nil {
  2120. // Ignore the error. The frame writer already knows.
  2121. return
  2122. }
  2123. } else {
  2124. // The bufio.Writer won't call chunkWriter.Write
  2125. // (writeChunk with zero bytes, so we have to do it
  2126. // ourselves to force the HTTP response header and/or
  2127. // final DATA frame (with END_STREAM) to be sent.
  2128. rws.writeChunk(nil)
  2129. }
  2130. }
  2131. func (w *responseWriter) CloseNotify() <-chan bool {
  2132. rws := w.rws
  2133. if rws == nil {
  2134. panic("CloseNotify called after Handler finished")
  2135. }
  2136. rws.closeNotifierMu.Lock()
  2137. ch := rws.closeNotifierCh
  2138. if ch == nil {
  2139. ch = make(chan bool, 1)
  2140. rws.closeNotifierCh = ch
  2141. cw := rws.stream.cw
  2142. go func() {
  2143. cw.Wait() // wait for close
  2144. ch <- true
  2145. }()
  2146. }
  2147. rws.closeNotifierMu.Unlock()
  2148. return ch
  2149. }
  2150. func (w *responseWriter) Header() http.Header {
  2151. rws := w.rws
  2152. if rws == nil {
  2153. panic("Header called after Handler finished")
  2154. }
  2155. if rws.handlerHeader == nil {
  2156. rws.handlerHeader = make(http.Header)
  2157. }
  2158. return rws.handlerHeader
  2159. }
  2160. func (w *responseWriter) WriteHeader(code int) {
  2161. rws := w.rws
  2162. if rws == nil {
  2163. panic("WriteHeader called after Handler finished")
  2164. }
  2165. rws.writeHeader(code)
  2166. }
  2167. func (rws *responseWriterState) writeHeader(code int) {
  2168. if !rws.wroteHeader {
  2169. rws.wroteHeader = true
  2170. rws.status = code
  2171. if len(rws.handlerHeader) > 0 {
  2172. rws.snapHeader = cloneHeader(rws.handlerHeader)
  2173. }
  2174. }
  2175. }
  2176. func cloneHeader(h http.Header) http.Header {
  2177. h2 := make(http.Header, len(h))
  2178. for k, vv := range h {
  2179. vv2 := make([]string, len(vv))
  2180. copy(vv2, vv)
  2181. h2[k] = vv2
  2182. }
  2183. return h2
  2184. }
  2185. // The Life Of A Write is like this:
  2186. //
  2187. // * Handler calls w.Write or w.WriteString ->
  2188. // * -> rws.bw (*bufio.Writer) ->
  2189. // * (Handler migth call Flush)
  2190. // * -> chunkWriter{rws}
  2191. // * -> responseWriterState.writeChunk(p []byte)
  2192. // * -> responseWriterState.writeChunk (most of the magic; see comment there)
  2193. func (w *responseWriter) Write(p []byte) (n int, err error) {
  2194. return w.write(len(p), p, "")
  2195. }
  2196. func (w *responseWriter) WriteString(s string) (n int, err error) {
  2197. return w.write(len(s), nil, s)
  2198. }
  2199. // either dataB or dataS is non-zero.
  2200. func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  2201. rws := w.rws
  2202. if rws == nil {
  2203. panic("Write called after Handler finished")
  2204. }
  2205. if !rws.wroteHeader {
  2206. w.WriteHeader(200)
  2207. }
  2208. if !bodyAllowedForStatus(rws.status) {
  2209. return 0, http.ErrBodyNotAllowed
  2210. }
  2211. rws.wroteBytes += int64(len(dataB)) + int64(len(dataS)) // only one can be set
  2212. if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen {
  2213. // TODO: send a RST_STREAM
  2214. return 0, errors.New("http2: handler wrote more than declared Content-Length")
  2215. }
  2216. if dataB != nil {
  2217. return rws.bw.Write(dataB)
  2218. } else {
  2219. return rws.bw.WriteString(dataS)
  2220. }
  2221. }
  2222. func (w *responseWriter) handlerDone() {
  2223. rws := w.rws
  2224. rws.handlerDone = true
  2225. w.Flush()
  2226. w.rws = nil
  2227. responseWriterStatePool.Put(rws)
  2228. }
  2229. // Push errors.
  2230. var (
  2231. ErrRecursivePush = errors.New("http2: recursive push not allowed")
  2232. ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS")
  2233. )
  2234. // pushOptions is the internal version of http.PushOptions, which we
  2235. // cannot include here because it's only defined in Go 1.8 and later.
  2236. type pushOptions struct {
  2237. Method string
  2238. Header http.Header
  2239. }
  2240. func (w *responseWriter) push(target string, opts pushOptions) error {
  2241. st := w.rws.stream
  2242. sc := st.sc
  2243. sc.serveG.checkNotOn()
  2244. // No recursive pushes: "PUSH_PROMISE frames MUST only be sent on a peer-initiated stream."
  2245. // http://tools.ietf.org/html/rfc7540#section-6.6
  2246. if st.isPushed() {
  2247. return ErrRecursivePush
  2248. }
  2249. // Default options.
  2250. if opts.Method == "" {
  2251. opts.Method = "GET"
  2252. }
  2253. if opts.Header == nil {
  2254. opts.Header = http.Header{}
  2255. }
  2256. wantScheme := "http"
  2257. if w.rws.req.TLS != nil {
  2258. wantScheme = "https"
  2259. }
  2260. // Validate the request.
  2261. u, err := url.Parse(target)
  2262. if err != nil {
  2263. return err
  2264. }
  2265. if u.Scheme == "" {
  2266. if !strings.HasPrefix(target, "/") {
  2267. return fmt.Errorf("target must be an absolute URL or an absolute path: %q", target)
  2268. }
  2269. u.Scheme = wantScheme
  2270. u.Host = w.rws.req.Host
  2271. } else {
  2272. if u.Scheme != wantScheme {
  2273. return fmt.Errorf("cannot push URL with scheme %q from request with scheme %q", u.Scheme, wantScheme)
  2274. }
  2275. if u.Host == "" {
  2276. return errors.New("URL must have a host")
  2277. }
  2278. }
  2279. for k := range opts.Header {
  2280. if strings.HasPrefix(k, ":") {
  2281. return fmt.Errorf("promised request headers cannot include pseudo header %q", k)
  2282. }
  2283. // These headers are meaningful only if the request has a body,
  2284. // but PUSH_PROMISE requests cannot have a body.
  2285. // http://tools.ietf.org/html/rfc7540#section-8.2
  2286. // Also disallow Host, since the promised URL must be absolute.
  2287. switch strings.ToLower(k) {
  2288. case "content-length", "content-encoding", "trailer", "te", "expect", "host":
  2289. return fmt.Errorf("promised request headers cannot include %q", k)
  2290. }
  2291. }
  2292. if err := checkValidHTTP2RequestHeaders(opts.Header); err != nil {
  2293. return err
  2294. }
  2295. // The RFC effectively limits promised requests to GET and HEAD:
  2296. // "Promised requests MUST be cacheable [GET, HEAD, or POST], and MUST be safe [GET or HEAD]"
  2297. // http://tools.ietf.org/html/rfc7540#section-8.2
  2298. if opts.Method != "GET" && opts.Method != "HEAD" {
  2299. return fmt.Errorf("method %q must be GET or HEAD", opts.Method)
  2300. }
  2301. msg := startPushRequest{
  2302. parent: st,
  2303. method: opts.Method,
  2304. url: u,
  2305. header: cloneHeader(opts.Header),
  2306. done: errChanPool.Get().(chan error),
  2307. }
  2308. select {
  2309. case <-sc.doneServing:
  2310. return errClientDisconnected
  2311. case <-st.cw:
  2312. return errStreamClosed
  2313. case sc.wantStartPushCh <- msg:
  2314. }
  2315. select {
  2316. case <-sc.doneServing:
  2317. return errClientDisconnected
  2318. case <-st.cw:
  2319. return errStreamClosed
  2320. case err := <-msg.done:
  2321. errChanPool.Put(msg.done)
  2322. return err
  2323. }
  2324. }
  2325. type startPushRequest struct {
  2326. parent *stream
  2327. method string
  2328. url *url.URL
  2329. header http.Header
  2330. done chan error
  2331. }
  2332. func (sc *serverConn) startPush(msg startPushRequest) {
  2333. sc.serveG.check()
  2334. // http://tools.ietf.org/html/rfc7540#section-6.6.
  2335. // PUSH_PROMISE frames MUST only be sent on a peer-initiated stream that
  2336. // is in either the "open" or "half-closed (remote)" state.
  2337. if msg.parent.state != stateOpen && msg.parent.state != stateHalfClosedRemote {
  2338. // responseWriter.Push checks that the stream is peer-initiaed.
  2339. msg.done <- errStreamClosed
  2340. return
  2341. }
  2342. // http://tools.ietf.org/html/rfc7540#section-6.6.
  2343. if !sc.pushEnabled {
  2344. msg.done <- http.ErrNotSupported
  2345. return
  2346. }
  2347. // PUSH_PROMISE frames must be sent in increasing order by stream ID, so
  2348. // we allocate an ID for the promised stream lazily, when the PUSH_PROMISE
  2349. // is written. Once the ID is allocated, we start the request handler.
  2350. allocatePromisedID := func() (uint32, error) {
  2351. sc.serveG.check()
  2352. // Check this again, just in case. Technically, we might have received
  2353. // an updated SETTINGS by the time we got around to writing this frame.
  2354. if !sc.pushEnabled {
  2355. return 0, http.ErrNotSupported
  2356. }
  2357. // http://tools.ietf.org/html/rfc7540#section-6.5.2.
  2358. if sc.curPushedStreams+1 > sc.clientMaxStreams {
  2359. return 0, ErrPushLimitReached
  2360. }
  2361. // http://tools.ietf.org/html/rfc7540#section-5.1.1.
  2362. // Streams initiated by the server MUST use even-numbered identifiers.
  2363. // A server that is unable to establish a new stream identifier can send a GOAWAY
  2364. // frame so that the client is forced to open a new connection for new streams.
  2365. if sc.maxPushPromiseID+2 >= 1<<31 {
  2366. sc.startGracefulShutdown()
  2367. return 0, ErrPushLimitReached
  2368. }
  2369. sc.maxPushPromiseID += 2
  2370. promisedID := sc.maxPushPromiseID
  2371. // http://tools.ietf.org/html/rfc7540#section-8.2.
  2372. // Strictly speaking, the new stream should start in "reserved (local)", then
  2373. // transition to "half closed (remote)" after sending the initial HEADERS, but
  2374. // we start in "half closed (remote)" for simplicity.
  2375. // See further comments at the definition of stateHalfClosedRemote.
  2376. promised := sc.newStream(promisedID, msg.parent.id, stateHalfClosedRemote)
  2377. rw, req, err := sc.newWriterAndRequestNoBody(promised, requestParam{
  2378. method: msg.method,
  2379. scheme: msg.url.Scheme,
  2380. authority: msg.url.Host,
  2381. path: msg.url.RequestURI(),
  2382. header: cloneHeader(msg.header), // clone since handler runs concurrently with writing the PUSH_PROMISE
  2383. })
  2384. if err != nil {
  2385. // Should not happen, since we've already validated msg.url.
  2386. panic(fmt.Sprintf("newWriterAndRequestNoBody(%+v): %v", msg.url, err))
  2387. }
  2388. go sc.runHandler(rw, req, sc.handler.ServeHTTP)
  2389. return promisedID, nil
  2390. }
  2391. sc.writeFrame(FrameWriteRequest{
  2392. write: &writePushPromise{
  2393. streamID: msg.parent.id,
  2394. method: msg.method,
  2395. url: msg.url,
  2396. h: msg.header,
  2397. allocatePromisedID: allocatePromisedID,
  2398. },
  2399. stream: msg.parent,
  2400. done: msg.done,
  2401. })
  2402. }
  2403. // foreachHeaderElement splits v according to the "#rule" construction
  2404. // in RFC 2616 section 2.1 and calls fn for each non-empty element.
  2405. func foreachHeaderElement(v string, fn func(string)) {
  2406. v = textproto.TrimString(v)
  2407. if v == "" {
  2408. return
  2409. }
  2410. if !strings.Contains(v, ",") {
  2411. fn(v)
  2412. return
  2413. }
  2414. for _, f := range strings.Split(v, ",") {
  2415. if f = textproto.TrimString(f); f != "" {
  2416. fn(f)
  2417. }
  2418. }
  2419. }
  2420. // From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2
  2421. var connHeaders = []string{
  2422. "Connection",
  2423. "Keep-Alive",
  2424. "Proxy-Connection",
  2425. "Transfer-Encoding",
  2426. "Upgrade",
  2427. }
  2428. // checkValidHTTP2RequestHeaders checks whether h is a valid HTTP/2 request,
  2429. // per RFC 7540 Section 8.1.2.2.
  2430. // The returned error is reported to users.
  2431. func checkValidHTTP2RequestHeaders(h http.Header) error {
  2432. for _, k := range connHeaders {
  2433. if _, ok := h[k]; ok {
  2434. return fmt.Errorf("request header %q is not valid in HTTP/2", k)
  2435. }
  2436. }
  2437. te := h["Te"]
  2438. if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) {
  2439. return errors.New(`request header "TE" may only be "trailers" in HTTP/2`)
  2440. }
  2441. return nil
  2442. }
  2443. func new400Handler(err error) http.HandlerFunc {
  2444. return func(w http.ResponseWriter, r *http.Request) {
  2445. http.Error(w, err.Error(), http.StatusBadRequest)
  2446. }
  2447. }
  2448. // ValidTrailerHeader reports whether name is a valid header field name to appear
  2449. // in trailers.
  2450. // See: http://tools.ietf.org/html/rfc7230#section-4.1.2
  2451. func ValidTrailerHeader(name string) bool {
  2452. name = http.CanonicalHeaderKey(name)
  2453. if strings.HasPrefix(name, "If-") || badTrailer[name] {
  2454. return false
  2455. }
  2456. return true
  2457. }
  2458. var badTrailer = map[string]bool{
  2459. "Authorization": true,
  2460. "Cache-Control": true,
  2461. "Connection": true,
  2462. "Content-Encoding": true,
  2463. "Content-Length": true,
  2464. "Content-Range": true,
  2465. "Content-Type": true,
  2466. "Expect": true,
  2467. "Host": true,
  2468. "Keep-Alive": true,
  2469. "Max-Forwards": true,
  2470. "Pragma": true,
  2471. "Proxy-Authenticate": true,
  2472. "Proxy-Authorization": true,
  2473. "Proxy-Connection": true,
  2474. "Range": true,
  2475. "Realm": true,
  2476. "Te": true,
  2477. "Trailer": true,
  2478. "Transfer-Encoding": true,
  2479. "Www-Authenticate": true,
  2480. }
  2481. // h1ServerShutdownChan returns a channel that will be closed when the
  2482. // provided *http.Server wants to shut down.
  2483. //
  2484. // This is a somewhat hacky way to get at http1 innards. It works
  2485. // when the http2 code is bundled into the net/http package in the
  2486. // standard library. The alternatives ended up making the cmd/go tool
  2487. // depend on http Servers. This is the lightest option for now.
  2488. // This is tested via the TestServeShutdown* tests in net/http.
  2489. func h1ServerShutdownChan(hs *http.Server) <-chan struct{} {
  2490. if fn := testh1ServerShutdownChan; fn != nil {
  2491. return fn(hs)
  2492. }
  2493. var x interface{} = hs
  2494. type I interface {
  2495. getDoneChan() <-chan struct{}
  2496. }
  2497. if hs, ok := x.(I); ok {
  2498. return hs.getDoneChan()
  2499. }
  2500. return nil
  2501. }
  2502. // optional test hook for h1ServerShutdownChan.
  2503. var testh1ServerShutdownChan func(hs *http.Server) <-chan struct{}
  2504. // h1ServerKeepAlivesDisabled reports whether hs has its keep-alives
  2505. // disabled. See comments on h1ServerShutdownChan above for why
  2506. // the code is written this way.
  2507. func h1ServerKeepAlivesDisabled(hs *http.Server) bool {
  2508. var x interface{} = hs
  2509. type I interface {
  2510. doKeepAlives() bool
  2511. }
  2512. if hs, ok := x.(I); ok {
  2513. return !hs.doKeepAlives()
  2514. }
  2515. return false
  2516. }