server.go 82 KB

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