server.go 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270
  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: replace all <-sc.doneServing with reads from the stream's cw
  5. // instead, and make sure that on close we close all open
  6. // streams. then remove doneServing?
  7. // TODO: re-audit GOAWAY support. Consider each incoming frame type and
  8. // whether it should be ignored during graceful shutdown.
  9. // TODO: disconnect idle clients. GFE seems to do 4 minutes. make
  10. // configurable? or maximum number of idle clients and remove the
  11. // oldest?
  12. // TODO: turn off the serve goroutine when idle, so
  13. // an idle conn only has the readFrames goroutine active. (which could
  14. // also be optimized probably to pin less memory in crypto/tls). This
  15. // would involve tracking when the serve goroutine is active (atomic
  16. // int32 read/CAS probably?) and starting it up when frames arrive,
  17. // and shutting it down when all handlers exit. the occasional PING
  18. // packets could use time.AfterFunc to call sc.wakeStartServeLoop()
  19. // (which is a no-op if already running) and then queue the PING write
  20. // as normal. The serve loop would then exit in most cases (if no
  21. // Handlers running) and not be woken up again until the PING packet
  22. // returns.
  23. // TODO (maybe): add a mechanism for Handlers to going into
  24. // half-closed-local mode (rw.(io.Closer) test?) but not exit their
  25. // handler, and continue to be able to read from the
  26. // Request.Body. This would be a somewhat semantic change from HTTP/1
  27. // (or at least what we expose in net/http), so I'd probably want to
  28. // add it there too. For now, this package says that returning from
  29. // the Handler ServeHTTP function means you're both done reading and
  30. // done writing, without a way to stop just one or the other.
  31. package http2
  32. import (
  33. "bufio"
  34. "bytes"
  35. "crypto/tls"
  36. "errors"
  37. "fmt"
  38. "io"
  39. "log"
  40. "net"
  41. "net/http"
  42. "net/textproto"
  43. "net/url"
  44. "os"
  45. "reflect"
  46. "runtime"
  47. "strconv"
  48. "strings"
  49. "sync"
  50. "time"
  51. "golang.org/x/net/http2/hpack"
  52. )
  53. const (
  54. prefaceTimeout = 10 * time.Second
  55. firstSettingsTimeout = 2 * time.Second // should be in-flight with preface anyway
  56. handlerChunkWriteSize = 4 << 10
  57. defaultMaxStreams = 250 // TODO: make this 100 as the GFE seems to?
  58. )
  59. var (
  60. errClientDisconnected = errors.New("client disconnected")
  61. errClosedBody = errors.New("body closed by handler")
  62. errHandlerComplete = errors.New("http2: request body closed due to handler exiting")
  63. errStreamClosed = errors.New("http2: stream closed")
  64. )
  65. var responseWriterStatePool = sync.Pool{
  66. New: func() interface{} {
  67. rws := &responseWriterState{}
  68. rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize)
  69. return rws
  70. },
  71. }
  72. // Test hooks.
  73. var (
  74. testHookOnConn func()
  75. testHookGetServerConn func(*serverConn)
  76. testHookOnPanicMu *sync.Mutex // nil except in tests
  77. testHookOnPanic func(sc *serverConn, panicVal interface{}) (rePanic bool)
  78. )
  79. // Server is an HTTP/2 server.
  80. type Server struct {
  81. // MaxHandlers limits the number of http.Handler ServeHTTP goroutines
  82. // which may run at a time over all connections.
  83. // Negative or zero no limit.
  84. // TODO: implement
  85. MaxHandlers int
  86. // MaxConcurrentStreams optionally specifies the number of
  87. // concurrent streams that each client may have open at a
  88. // time. This is unrelated to the number of http.Handler goroutines
  89. // which may be active globally, which is MaxHandlers.
  90. // If zero, MaxConcurrentStreams defaults to at least 100, per
  91. // the HTTP/2 spec's recommendations.
  92. MaxConcurrentStreams uint32
  93. // MaxReadFrameSize optionally specifies the largest frame
  94. // this server is willing to read. A valid value is between
  95. // 16k and 16M, inclusive. If zero or otherwise invalid, a
  96. // default value is used.
  97. MaxReadFrameSize uint32
  98. // PermitProhibitedCipherSuites, if true, permits the use of
  99. // cipher suites prohibited by the HTTP/2 spec.
  100. PermitProhibitedCipherSuites bool
  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 conf == nil {
  121. conf = new(Server)
  122. }
  123. if s.TLSConfig == nil {
  124. s.TLSConfig = new(tls.Config)
  125. } else if s.TLSConfig.CipherSuites != nil {
  126. // If they already provided a CipherSuite list, return
  127. // an error if it has a bad order or is missing
  128. // ECDHE_RSA_WITH_AES_128_GCM_SHA256.
  129. const requiredCipher = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  130. haveRequired := false
  131. sawBad := false
  132. for i, cs := range s.TLSConfig.CipherSuites {
  133. if cs == requiredCipher {
  134. haveRequired = true
  135. }
  136. if isBadCipher(cs) {
  137. sawBad = true
  138. } else if sawBad {
  139. 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)
  140. }
  141. }
  142. if !haveRequired {
  143. return fmt.Errorf("http2: TLSConfig.CipherSuites is missing HTTP/2-required TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256")
  144. }
  145. }
  146. // Note: not setting MinVersion to tls.VersionTLS12,
  147. // as we don't want to interfere with HTTP/1.1 traffic
  148. // on the user's server. We enforce TLS 1.2 later once
  149. // we accept a connection. Ideally this should be done
  150. // during next-proto selection, but using TLS <1.2 with
  151. // HTTP/2 is still the client's bug.
  152. s.TLSConfig.PreferServerCipherSuites = true
  153. haveNPN := false
  154. for _, p := range s.TLSConfig.NextProtos {
  155. if p == NextProtoTLS {
  156. haveNPN = true
  157. break
  158. }
  159. }
  160. if !haveNPN {
  161. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, NextProtoTLS)
  162. }
  163. // h2-14 is temporary (as of 2015-03-05) while we wait for all browsers
  164. // to switch to "h2".
  165. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, "h2-14")
  166. if s.TLSNextProto == nil {
  167. s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
  168. }
  169. protoHandler := func(hs *http.Server, c *tls.Conn, h http.Handler) {
  170. if testHookOnConn != nil {
  171. testHookOnConn()
  172. }
  173. conf.ServeConn(c, &ServeConnOpts{
  174. Handler: h,
  175. BaseConfig: hs,
  176. })
  177. }
  178. s.TLSNextProto[NextProtoTLS] = protoHandler
  179. s.TLSNextProto["h2-14"] = protoHandler // temporary; see above.
  180. return nil
  181. }
  182. // ServeConnOpts are options for the Server.ServeConn method.
  183. type ServeConnOpts struct {
  184. // BaseConfig optionally sets the base configuration
  185. // for values. If nil, defaults are used.
  186. BaseConfig *http.Server
  187. // Handler specifies which handler to use for processing
  188. // requests. If nil, BaseConfig.Handler is used. If BaseConfig
  189. // or BaseConfig.Handler is nil, http.DefaultServeMux is used.
  190. Handler http.Handler
  191. }
  192. func (o *ServeConnOpts) baseConfig() *http.Server {
  193. if o != nil && o.BaseConfig != nil {
  194. return o.BaseConfig
  195. }
  196. return new(http.Server)
  197. }
  198. func (o *ServeConnOpts) handler() http.Handler {
  199. if o != nil {
  200. if o.Handler != nil {
  201. return o.Handler
  202. }
  203. if o.BaseConfig != nil && o.BaseConfig.Handler != nil {
  204. return o.BaseConfig.Handler
  205. }
  206. }
  207. return http.DefaultServeMux
  208. }
  209. // ServeConn serves HTTP/2 requests on the provided connection and
  210. // blocks until the connection is no longer readable.
  211. //
  212. // ServeConn starts speaking HTTP/2 assuming that c has not had any
  213. // reads or writes. It writes its initial settings frame and expects
  214. // to be able to read the preface and settings frame from the
  215. // client. If c has a ConnectionState method like a *tls.Conn, the
  216. // ConnectionState is used to verify the TLS ciphersuite and to set
  217. // the Request.TLS field in Handlers.
  218. //
  219. // ServeConn does not support h2c by itself. Any h2c support must be
  220. // implemented in terms of providing a suitably-behaving net.Conn.
  221. //
  222. // The opts parameter is optional. If nil, default values are used.
  223. func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) {
  224. baseCtx, cancel := serverConnBaseContext(c, opts)
  225. defer cancel()
  226. sc := &serverConn{
  227. srv: s,
  228. hs: opts.baseConfig(),
  229. conn: c,
  230. baseCtx: baseCtx,
  231. remoteAddrStr: c.RemoteAddr().String(),
  232. bw: newBufferedWriter(c),
  233. handler: opts.handler(),
  234. streams: make(map[uint32]*stream),
  235. readFrameCh: make(chan readFrameResult),
  236. wantWriteFrameCh: make(chan frameWriteMsg, 8),
  237. wroteFrameCh: make(chan frameWriteResult, 1), // buffered; one send in writeFrameAsync
  238. bodyReadCh: make(chan bodyReadMsg), // buffering doesn't matter either way
  239. doneServing: make(chan struct{}),
  240. advMaxStreams: s.maxConcurrentStreams(),
  241. writeSched: writeScheduler{
  242. maxFrameSize: initialMaxFrameSize,
  243. },
  244. initialWindowSize: initialWindowSize,
  245. headerTableSize: initialHeaderTableSize,
  246. serveG: newGoroutineLock(),
  247. pushEnabled: true,
  248. }
  249. sc.flow.add(initialWindowSize)
  250. sc.inflow.add(initialWindowSize)
  251. sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
  252. fr := NewFramer(sc.bw, c)
  253. fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil)
  254. fr.MaxHeaderListSize = sc.maxHeaderListSize()
  255. fr.SetMaxReadFrameSize(s.maxReadFrameSize())
  256. sc.framer = fr
  257. if tc, ok := c.(connectionStater); ok {
  258. sc.tlsState = new(tls.ConnectionState)
  259. *sc.tlsState = tc.ConnectionState()
  260. // 9.2 Use of TLS Features
  261. // An implementation of HTTP/2 over TLS MUST use TLS
  262. // 1.2 or higher with the restrictions on feature set
  263. // and cipher suite described in this section. Due to
  264. // implementation limitations, it might not be
  265. // possible to fail TLS negotiation. An endpoint MUST
  266. // immediately terminate an HTTP/2 connection that
  267. // does not meet the TLS requirements described in
  268. // this section with a connection error (Section
  269. // 5.4.1) of type INADEQUATE_SECURITY.
  270. if sc.tlsState.Version < tls.VersionTLS12 {
  271. sc.rejectConn(ErrCodeInadequateSecurity, "TLS version too low")
  272. return
  273. }
  274. if sc.tlsState.ServerName == "" {
  275. // Client must use SNI, but we don't enforce that anymore,
  276. // since it was causing problems when connecting to bare IP
  277. // addresses during development.
  278. //
  279. // TODO: optionally enforce? Or enforce at the time we receive
  280. // a new request, and verify the the ServerName matches the :authority?
  281. // But that precludes proxy situations, perhaps.
  282. //
  283. // So for now, do nothing here again.
  284. }
  285. if !s.PermitProhibitedCipherSuites && isBadCipher(sc.tlsState.CipherSuite) {
  286. // "Endpoints MAY choose to generate a connection error
  287. // (Section 5.4.1) of type INADEQUATE_SECURITY if one of
  288. // the prohibited cipher suites are negotiated."
  289. //
  290. // We choose that. In my opinion, the spec is weak
  291. // here. It also says both parties must support at least
  292. // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 so there's no
  293. // excuses here. If we really must, we could allow an
  294. // "AllowInsecureWeakCiphers" option on the server later.
  295. // Let's see how it plays out first.
  296. sc.rejectConn(ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite))
  297. return
  298. }
  299. }
  300. if hook := testHookGetServerConn; hook != nil {
  301. hook(sc)
  302. }
  303. sc.serve()
  304. }
  305. // isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec.
  306. func isBadCipher(cipher uint16) bool {
  307. switch cipher {
  308. case tls.TLS_RSA_WITH_RC4_128_SHA,
  309. tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  310. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  311. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  312. tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
  313. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  314. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  315. tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
  316. tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  317. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  318. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
  319. // Reject cipher suites from Appendix A.
  320. // "This list includes those cipher suites that do not
  321. // offer an ephemeral key exchange and those that are
  322. // based on the TLS null, stream or block cipher type"
  323. return true
  324. default:
  325. return false
  326. }
  327. }
  328. func (sc *serverConn) rejectConn(err ErrCode, debug string) {
  329. sc.vlogf("http2: server rejecting conn: %v, %s", err, debug)
  330. // ignoring errors. hanging up anyway.
  331. sc.framer.WriteGoAway(0, err, []byte(debug))
  332. sc.bw.Flush()
  333. sc.conn.Close()
  334. }
  335. type serverConn struct {
  336. // Immutable:
  337. srv *Server
  338. hs *http.Server
  339. conn net.Conn
  340. bw *bufferedWriter // writing to conn
  341. handler http.Handler
  342. baseCtx contextContext
  343. framer *Framer
  344. doneServing chan struct{} // closed when serverConn.serve ends
  345. readFrameCh chan readFrameResult // written by serverConn.readFrames
  346. wantWriteFrameCh chan frameWriteMsg // from handlers -> serve
  347. wroteFrameCh chan frameWriteResult // from writeFrameAsync -> serve, tickles more frame writes
  348. bodyReadCh chan bodyReadMsg // from handlers -> serve
  349. testHookCh chan func(int) // code to run on the serve loop
  350. flow flow // conn-wide (not stream-specific) outbound flow control
  351. inflow flow // conn-wide inbound flow control
  352. tlsState *tls.ConnectionState // shared by all handlers, like net/http
  353. remoteAddrStr string
  354. // Everything following is owned by the serve loop; use serveG.check():
  355. serveG goroutineLock // used to verify funcs are on serve()
  356. pushEnabled bool
  357. sawFirstSettings bool // got the initial SETTINGS frame after the preface
  358. needToSendSettingsAck bool
  359. unackedSettings int // how many SETTINGS have we sent without ACKs?
  360. clientMaxStreams uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)
  361. advMaxStreams uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client
  362. curOpenStreams uint32 // client's number of open streams
  363. maxStreamID uint32 // max ever seen
  364. streams map[uint32]*stream
  365. initialWindowSize int32
  366. headerTableSize uint32
  367. peerMaxHeaderListSize uint32 // zero means unknown (default)
  368. canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case
  369. writingFrame bool // started write goroutine but haven't heard back on wroteFrameCh
  370. needsFrameFlush bool // last frame write wasn't a flush
  371. writeSched writeScheduler
  372. inGoAway bool // we've started to or sent GOAWAY
  373. needToSendGoAway bool // we need to schedule a GOAWAY frame write
  374. goAwayCode ErrCode
  375. shutdownTimerCh <-chan time.Time // nil until used
  376. shutdownTimer *time.Timer // nil until used
  377. freeRequestBodyBuf []byte // if non-nil, a free initialWindowSize buffer for getRequestBodyBuf
  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. // stream represents a stream. This is the minimal metadata needed by
  394. // the serve goroutine. Most of the actual stream state is owned by
  395. // the http.Handler's goroutine in the responseWriter. Because the
  396. // responseWriter's responseWriterState is recycled at the end of a
  397. // handler, this struct intentionally has no pointer to the
  398. // *responseWriter{,State} itself, as the Handler ending nils out the
  399. // responseWriter's state field.
  400. type stream struct {
  401. // immutable:
  402. sc *serverConn
  403. id uint32
  404. body *pipe // non-nil if expecting DATA frames
  405. cw closeWaiter // closed wait stream transitions to closed state
  406. ctx contextContext
  407. cancelCtx func()
  408. // owned by serverConn's serve loop:
  409. bodyBytes int64 // body bytes seen so far
  410. declBodyBytes int64 // or -1 if undeclared
  411. flow flow // limits writing from Handler to client
  412. inflow flow // what the client is allowed to POST/etc to us
  413. parent *stream // or nil
  414. numTrailerValues int64
  415. weight uint8
  416. state streamState
  417. sentReset bool // only true once detached from streams map
  418. gotReset bool // only true once detacted from streams map
  419. gotTrailerHeader bool // HEADER frame for trailers was seen
  420. reqBuf []byte
  421. trailer http.Header // accumulated trailers
  422. reqTrailer http.Header // handler's Request.Trailer
  423. }
  424. func (sc *serverConn) Framer() *Framer { return sc.framer }
  425. func (sc *serverConn) CloseConn() error { return sc.conn.Close() }
  426. func (sc *serverConn) Flush() error { return sc.bw.Flush() }
  427. func (sc *serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) {
  428. return sc.hpackEncoder, &sc.headerWriteBuf
  429. }
  430. func (sc *serverConn) state(streamID uint32) (streamState, *stream) {
  431. sc.serveG.check()
  432. // http://http2.github.io/http2-spec/#rfc.section.5.1
  433. if st, ok := sc.streams[streamID]; ok {
  434. return st.state, st
  435. }
  436. // "The first use of a new stream identifier implicitly closes all
  437. // streams in the "idle" state that might have been initiated by
  438. // that peer with a lower-valued stream identifier. For example, if
  439. // a client sends a HEADERS frame on stream 7 without ever sending a
  440. // frame on stream 5, then stream 5 transitions to the "closed"
  441. // state when the first frame for stream 7 is sent or received."
  442. if streamID <= sc.maxStreamID {
  443. return stateClosed, nil
  444. }
  445. return stateIdle, nil
  446. }
  447. // setConnState calls the net/http ConnState hook for this connection, if configured.
  448. // Note that the net/http package does StateNew and StateClosed for us.
  449. // There is currently no plan for StateHijacked or hijacking HTTP/2 connections.
  450. func (sc *serverConn) setConnState(state http.ConnState) {
  451. if sc.hs.ConnState != nil {
  452. sc.hs.ConnState(sc.conn, state)
  453. }
  454. }
  455. func (sc *serverConn) vlogf(format string, args ...interface{}) {
  456. if VerboseLogs {
  457. sc.logf(format, args...)
  458. }
  459. }
  460. func (sc *serverConn) logf(format string, args ...interface{}) {
  461. if lg := sc.hs.ErrorLog; lg != nil {
  462. lg.Printf(format, args...)
  463. } else {
  464. log.Printf(format, args...)
  465. }
  466. }
  467. // errno returns v's underlying uintptr, else 0.
  468. //
  469. // TODO: remove this helper function once http2 can use build
  470. // tags. See comment in isClosedConnError.
  471. func errno(v error) uintptr {
  472. if rv := reflect.ValueOf(v); rv.Kind() == reflect.Uintptr {
  473. return uintptr(rv.Uint())
  474. }
  475. return 0
  476. }
  477. // isClosedConnError reports whether err is an error from use of a closed
  478. // network connection.
  479. func isClosedConnError(err error) bool {
  480. if err == nil {
  481. return false
  482. }
  483. // TODO: remove this string search and be more like the Windows
  484. // case below. That might involve modifying the standard library
  485. // to return better error types.
  486. str := err.Error()
  487. if strings.Contains(str, "use of closed network connection") {
  488. return true
  489. }
  490. // TODO(bradfitz): x/tools/cmd/bundle doesn't really support
  491. // build tags, so I can't make an http2_windows.go file with
  492. // Windows-specific stuff. Fix that and move this, once we
  493. // have a way to bundle this into std's net/http somehow.
  494. if runtime.GOOS == "windows" {
  495. if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
  496. if se, ok := oe.Err.(*os.SyscallError); ok && se.Syscall == "wsarecv" {
  497. const WSAECONNABORTED = 10053
  498. const WSAECONNRESET = 10054
  499. if n := errno(se.Err); n == WSAECONNRESET || n == WSAECONNABORTED {
  500. return true
  501. }
  502. }
  503. }
  504. }
  505. return false
  506. }
  507. func (sc *serverConn) condlogf(err error, format string, args ...interface{}) {
  508. if err == nil {
  509. return
  510. }
  511. if err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) {
  512. // Boring, expected errors.
  513. sc.vlogf(format, args...)
  514. } else {
  515. sc.logf(format, args...)
  516. }
  517. }
  518. func (sc *serverConn) canonicalHeader(v string) string {
  519. sc.serveG.check()
  520. cv, ok := commonCanonHeader[v]
  521. if ok {
  522. return cv
  523. }
  524. cv, ok = sc.canonHeader[v]
  525. if ok {
  526. return cv
  527. }
  528. if sc.canonHeader == nil {
  529. sc.canonHeader = make(map[string]string)
  530. }
  531. cv = http.CanonicalHeaderKey(v)
  532. sc.canonHeader[v] = cv
  533. return cv
  534. }
  535. type readFrameResult struct {
  536. f Frame // valid until readMore is called
  537. err error
  538. // readMore should be called once the consumer no longer needs or
  539. // retains f. After readMore, f is invalid and more frames can be
  540. // read.
  541. readMore func()
  542. }
  543. // readFrames is the loop that reads incoming frames.
  544. // It takes care to only read one frame at a time, blocking until the
  545. // consumer is done with the frame.
  546. // It's run on its own goroutine.
  547. func (sc *serverConn) readFrames() {
  548. gate := make(gate)
  549. gateDone := gate.Done
  550. for {
  551. f, err := sc.framer.ReadFrame()
  552. select {
  553. case sc.readFrameCh <- readFrameResult{f, err, gateDone}:
  554. case <-sc.doneServing:
  555. return
  556. }
  557. select {
  558. case <-gate:
  559. case <-sc.doneServing:
  560. return
  561. }
  562. if terminalReadFrameError(err) {
  563. return
  564. }
  565. }
  566. }
  567. // frameWriteResult is the message passed from writeFrameAsync to the serve goroutine.
  568. type frameWriteResult struct {
  569. wm frameWriteMsg // what was written (or attempted)
  570. err error // result of the writeFrame call
  571. }
  572. // writeFrameAsync runs in its own goroutine and writes a single frame
  573. // and then reports when it's done.
  574. // At most one goroutine can be running writeFrameAsync at a time per
  575. // serverConn.
  576. func (sc *serverConn) writeFrameAsync(wm frameWriteMsg) {
  577. err := wm.write.writeFrame(sc)
  578. sc.wroteFrameCh <- frameWriteResult{wm, err}
  579. }
  580. func (sc *serverConn) closeAllStreamsOnConnClose() {
  581. sc.serveG.check()
  582. for _, st := range sc.streams {
  583. sc.closeStream(st, errClientDisconnected)
  584. }
  585. }
  586. func (sc *serverConn) stopShutdownTimer() {
  587. sc.serveG.check()
  588. if t := sc.shutdownTimer; t != nil {
  589. t.Stop()
  590. }
  591. }
  592. func (sc *serverConn) notePanic() {
  593. // Note: this is for serverConn.serve panicking, not http.Handler code.
  594. if testHookOnPanicMu != nil {
  595. testHookOnPanicMu.Lock()
  596. defer testHookOnPanicMu.Unlock()
  597. }
  598. if testHookOnPanic != nil {
  599. if e := recover(); e != nil {
  600. if testHookOnPanic(sc, e) {
  601. panic(e)
  602. }
  603. }
  604. }
  605. }
  606. func (sc *serverConn) serve() {
  607. sc.serveG.check()
  608. defer sc.notePanic()
  609. defer sc.conn.Close()
  610. defer sc.closeAllStreamsOnConnClose()
  611. defer sc.stopShutdownTimer()
  612. defer close(sc.doneServing) // unblocks handlers trying to send
  613. if VerboseLogs {
  614. sc.vlogf("http2: server connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
  615. }
  616. sc.writeFrame(frameWriteMsg{
  617. write: writeSettings{
  618. {SettingMaxFrameSize, sc.srv.maxReadFrameSize()},
  619. {SettingMaxConcurrentStreams, sc.advMaxStreams},
  620. {SettingMaxHeaderListSize, sc.maxHeaderListSize()},
  621. // TODO: more actual settings, notably
  622. // SettingInitialWindowSize, but then we also
  623. // want to bump up the conn window size the
  624. // same amount here right after the settings
  625. },
  626. })
  627. sc.unackedSettings++
  628. if err := sc.readPreface(); err != nil {
  629. sc.condlogf(err, "http2: server: error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
  630. return
  631. }
  632. // Now that we've got the preface, get us out of the
  633. // "StateNew" state. We can't go directly to idle, though.
  634. // Active means we read some data and anticipate a request. We'll
  635. // do another Active when we get a HEADERS frame.
  636. sc.setConnState(http.StateActive)
  637. sc.setConnState(http.StateIdle)
  638. go sc.readFrames() // closed by defer sc.conn.Close above
  639. settingsTimer := time.NewTimer(firstSettingsTimeout)
  640. loopNum := 0
  641. for {
  642. loopNum++
  643. select {
  644. case wm := <-sc.wantWriteFrameCh:
  645. sc.writeFrame(wm)
  646. case res := <-sc.wroteFrameCh:
  647. sc.wroteFrame(res)
  648. case res := <-sc.readFrameCh:
  649. if !sc.processFrameFromReader(res) {
  650. return
  651. }
  652. res.readMore()
  653. if settingsTimer.C != nil {
  654. settingsTimer.Stop()
  655. settingsTimer.C = nil
  656. }
  657. case m := <-sc.bodyReadCh:
  658. sc.noteBodyRead(m.st, m.n)
  659. case <-settingsTimer.C:
  660. sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
  661. return
  662. case <-sc.shutdownTimerCh:
  663. sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
  664. return
  665. case fn := <-sc.testHookCh:
  666. fn(loopNum)
  667. }
  668. }
  669. }
  670. // readPreface reads the ClientPreface greeting from the peer
  671. // or returns an error on timeout or an invalid greeting.
  672. func (sc *serverConn) readPreface() error {
  673. errc := make(chan error, 1)
  674. go func() {
  675. // Read the client preface
  676. buf := make([]byte, len(ClientPreface))
  677. if _, err := io.ReadFull(sc.conn, buf); err != nil {
  678. errc <- err
  679. } else if !bytes.Equal(buf, clientPreface) {
  680. errc <- fmt.Errorf("bogus greeting %q", buf)
  681. } else {
  682. errc <- nil
  683. }
  684. }()
  685. timer := time.NewTimer(prefaceTimeout) // TODO: configurable on *Server?
  686. defer timer.Stop()
  687. select {
  688. case <-timer.C:
  689. return errors.New("timeout waiting for client preface")
  690. case err := <-errc:
  691. if err == nil {
  692. if VerboseLogs {
  693. sc.vlogf("http2: server: client %v said hello", sc.conn.RemoteAddr())
  694. }
  695. }
  696. return err
  697. }
  698. }
  699. var errChanPool = sync.Pool{
  700. New: func() interface{} { return make(chan error, 1) },
  701. }
  702. var writeDataPool = sync.Pool{
  703. New: func() interface{} { return new(writeData) },
  704. }
  705. // writeDataFromHandler writes DATA response frames from a handler on
  706. // the given stream.
  707. func (sc *serverConn) writeDataFromHandler(stream *stream, data []byte, endStream bool) error {
  708. ch := errChanPool.Get().(chan error)
  709. writeArg := writeDataPool.Get().(*writeData)
  710. *writeArg = writeData{stream.id, data, endStream}
  711. err := sc.writeFrameFromHandler(frameWriteMsg{
  712. write: writeArg,
  713. stream: stream,
  714. done: ch,
  715. })
  716. if err != nil {
  717. return err
  718. }
  719. var frameWriteDone bool // the frame write is done (successfully or not)
  720. select {
  721. case err = <-ch:
  722. frameWriteDone = true
  723. case <-sc.doneServing:
  724. return errClientDisconnected
  725. case <-stream.cw:
  726. // If both ch and stream.cw were ready (as might
  727. // happen on the final Write after an http.Handler
  728. // ends), prefer the write result. Otherwise this
  729. // might just be us successfully closing the stream.
  730. // The writeFrameAsync and serve goroutines guarantee
  731. // that the ch send will happen before the stream.cw
  732. // close.
  733. select {
  734. case err = <-ch:
  735. frameWriteDone = true
  736. default:
  737. return errStreamClosed
  738. }
  739. }
  740. errChanPool.Put(ch)
  741. if frameWriteDone {
  742. writeDataPool.Put(writeArg)
  743. }
  744. return err
  745. }
  746. // writeFrameFromHandler sends wm to sc.wantWriteFrameCh, but aborts
  747. // if the connection has gone away.
  748. //
  749. // This must not be run from the serve goroutine itself, else it might
  750. // deadlock writing to sc.wantWriteFrameCh (which is only mildly
  751. // buffered and is read by serve itself). If you're on the serve
  752. // goroutine, call writeFrame instead.
  753. func (sc *serverConn) writeFrameFromHandler(wm frameWriteMsg) error {
  754. sc.serveG.checkNotOn() // NOT
  755. select {
  756. case sc.wantWriteFrameCh <- wm:
  757. return nil
  758. case <-sc.doneServing:
  759. // Serve loop is gone.
  760. // Client has closed their connection to the server.
  761. return errClientDisconnected
  762. }
  763. }
  764. // writeFrame schedules a frame to write and sends it if there's nothing
  765. // already being written.
  766. //
  767. // There is no pushback here (the serve goroutine never blocks). It's
  768. // the http.Handlers that block, waiting for their previous frames to
  769. // make it onto the wire
  770. //
  771. // If you're not on the serve goroutine, use writeFrameFromHandler instead.
  772. func (sc *serverConn) writeFrame(wm frameWriteMsg) {
  773. sc.serveG.check()
  774. sc.writeSched.add(wm)
  775. sc.scheduleFrameWrite()
  776. }
  777. // startFrameWrite starts a goroutine to write wm (in a separate
  778. // goroutine since that might block on the network), and updates the
  779. // serve goroutine's state about the world, updated from info in wm.
  780. func (sc *serverConn) startFrameWrite(wm frameWriteMsg) {
  781. sc.serveG.check()
  782. if sc.writingFrame {
  783. panic("internal error: can only be writing one frame at a time")
  784. }
  785. st := wm.stream
  786. if st != nil {
  787. switch st.state {
  788. case stateHalfClosedLocal:
  789. panic("internal error: attempt to send frame on half-closed-local stream")
  790. case stateClosed:
  791. if st.sentReset || st.gotReset {
  792. // Skip this frame.
  793. sc.scheduleFrameWrite()
  794. return
  795. }
  796. panic(fmt.Sprintf("internal error: attempt to send a write %v on a closed stream", wm))
  797. }
  798. }
  799. sc.writingFrame = true
  800. sc.needsFrameFlush = true
  801. go sc.writeFrameAsync(wm)
  802. }
  803. // errHandlerPanicked is the error given to any callers blocked in a read from
  804. // Request.Body when the main goroutine panics. Since most handlers read in the
  805. // the main ServeHTTP goroutine, this will show up rarely.
  806. var errHandlerPanicked = errors.New("http2: handler panicked")
  807. // wroteFrame is called on the serve goroutine with the result of
  808. // whatever happened on writeFrameAsync.
  809. func (sc *serverConn) wroteFrame(res frameWriteResult) {
  810. sc.serveG.check()
  811. if !sc.writingFrame {
  812. panic("internal error: expected to be already writing a frame")
  813. }
  814. sc.writingFrame = false
  815. wm := res.wm
  816. st := wm.stream
  817. closeStream := endsStream(wm.write)
  818. if _, ok := wm.write.(handlerPanicRST); ok {
  819. sc.closeStream(st, errHandlerPanicked)
  820. }
  821. // Reply (if requested) to the blocked ServeHTTP goroutine.
  822. if ch := wm.done; ch != nil {
  823. select {
  824. case ch <- res.err:
  825. default:
  826. panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wm.write))
  827. }
  828. }
  829. wm.write = nil // prevent use (assume it's tainted after wm.done send)
  830. if closeStream {
  831. if st == nil {
  832. panic("internal error: expecting non-nil stream")
  833. }
  834. switch st.state {
  835. case stateOpen:
  836. // Here we would go to stateHalfClosedLocal in
  837. // theory, but since our handler is done and
  838. // the net/http package provides no mechanism
  839. // for finishing writing to a ResponseWriter
  840. // while still reading data (see possible TODO
  841. // at top of this file), we go into closed
  842. // state here anyway, after telling the peer
  843. // we're hanging up on them.
  844. st.state = stateHalfClosedLocal // won't last long, but necessary for closeStream via resetStream
  845. errCancel := StreamError{st.id, ErrCodeCancel}
  846. sc.resetStream(errCancel)
  847. case stateHalfClosedRemote:
  848. sc.closeStream(st, errHandlerComplete)
  849. }
  850. }
  851. sc.scheduleFrameWrite()
  852. }
  853. // scheduleFrameWrite tickles the frame writing scheduler.
  854. //
  855. // If a frame is already being written, nothing happens. This will be called again
  856. // when the frame is done being written.
  857. //
  858. // If a frame isn't being written we need to send one, the best frame
  859. // to send is selected, preferring first things that aren't
  860. // stream-specific (e.g. ACKing settings), and then finding the
  861. // highest priority stream.
  862. //
  863. // If a frame isn't being written and there's nothing else to send, we
  864. // flush the write buffer.
  865. func (sc *serverConn) scheduleFrameWrite() {
  866. sc.serveG.check()
  867. if sc.writingFrame {
  868. return
  869. }
  870. if sc.needToSendGoAway {
  871. sc.needToSendGoAway = false
  872. sc.startFrameWrite(frameWriteMsg{
  873. write: &writeGoAway{
  874. maxStreamID: sc.maxStreamID,
  875. code: sc.goAwayCode,
  876. },
  877. })
  878. return
  879. }
  880. if sc.needToSendSettingsAck {
  881. sc.needToSendSettingsAck = false
  882. sc.startFrameWrite(frameWriteMsg{write: writeSettingsAck{}})
  883. return
  884. }
  885. if !sc.inGoAway {
  886. if wm, ok := sc.writeSched.take(); ok {
  887. sc.startFrameWrite(wm)
  888. return
  889. }
  890. }
  891. if sc.needsFrameFlush {
  892. sc.startFrameWrite(frameWriteMsg{write: flushFrameWriter{}})
  893. sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
  894. return
  895. }
  896. }
  897. func (sc *serverConn) goAway(code ErrCode) {
  898. sc.serveG.check()
  899. if sc.inGoAway {
  900. return
  901. }
  902. if code != ErrCodeNo {
  903. sc.shutDownIn(250 * time.Millisecond)
  904. } else {
  905. // TODO: configurable
  906. sc.shutDownIn(1 * time.Second)
  907. }
  908. sc.inGoAway = true
  909. sc.needToSendGoAway = true
  910. sc.goAwayCode = code
  911. sc.scheduleFrameWrite()
  912. }
  913. func (sc *serverConn) shutDownIn(d time.Duration) {
  914. sc.serveG.check()
  915. sc.shutdownTimer = time.NewTimer(d)
  916. sc.shutdownTimerCh = sc.shutdownTimer.C
  917. }
  918. func (sc *serverConn) resetStream(se StreamError) {
  919. sc.serveG.check()
  920. sc.writeFrame(frameWriteMsg{write: se})
  921. if st, ok := sc.streams[se.StreamID]; ok {
  922. st.sentReset = true
  923. sc.closeStream(st, se)
  924. }
  925. }
  926. // processFrameFromReader processes the serve loop's read from readFrameCh from the
  927. // frame-reading goroutine.
  928. // processFrameFromReader returns whether the connection should be kept open.
  929. func (sc *serverConn) processFrameFromReader(res readFrameResult) bool {
  930. sc.serveG.check()
  931. err := res.err
  932. if err != nil {
  933. if err == ErrFrameTooLarge {
  934. sc.goAway(ErrCodeFrameSize)
  935. return true // goAway will close the loop
  936. }
  937. clientGone := err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err)
  938. if clientGone {
  939. // TODO: could we also get into this state if
  940. // the peer does a half close
  941. // (e.g. CloseWrite) because they're done
  942. // sending frames but they're still wanting
  943. // our open replies? Investigate.
  944. // TODO: add CloseWrite to crypto/tls.Conn first
  945. // so we have a way to test this? I suppose
  946. // just for testing we could have a non-TLS mode.
  947. return false
  948. }
  949. } else {
  950. f := res.f
  951. if VerboseLogs {
  952. sc.vlogf("http2: server read frame %v", summarizeFrame(f))
  953. }
  954. err = sc.processFrame(f)
  955. if err == nil {
  956. return true
  957. }
  958. }
  959. switch ev := err.(type) {
  960. case StreamError:
  961. sc.resetStream(ev)
  962. return true
  963. case goAwayFlowError:
  964. sc.goAway(ErrCodeFlowControl)
  965. return true
  966. case ConnectionError:
  967. sc.logf("http2: server connection error from %v: %v", sc.conn.RemoteAddr(), ev)
  968. sc.goAway(ErrCode(ev))
  969. return true // goAway will handle shutdown
  970. default:
  971. if res.err != nil {
  972. sc.vlogf("http2: server closing client connection; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
  973. } else {
  974. sc.logf("http2: server closing client connection: %v", err)
  975. }
  976. return false
  977. }
  978. }
  979. func (sc *serverConn) processFrame(f Frame) error {
  980. sc.serveG.check()
  981. // First frame received must be SETTINGS.
  982. if !sc.sawFirstSettings {
  983. if _, ok := f.(*SettingsFrame); !ok {
  984. return ConnectionError(ErrCodeProtocol)
  985. }
  986. sc.sawFirstSettings = true
  987. }
  988. switch f := f.(type) {
  989. case *SettingsFrame:
  990. return sc.processSettings(f)
  991. case *MetaHeadersFrame:
  992. return sc.processHeaders(f)
  993. case *WindowUpdateFrame:
  994. return sc.processWindowUpdate(f)
  995. case *PingFrame:
  996. return sc.processPing(f)
  997. case *DataFrame:
  998. return sc.processData(f)
  999. case *RSTStreamFrame:
  1000. return sc.processResetStream(f)
  1001. case *PriorityFrame:
  1002. return sc.processPriority(f)
  1003. case *PushPromiseFrame:
  1004. // A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE
  1005. // frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1006. return ConnectionError(ErrCodeProtocol)
  1007. default:
  1008. sc.vlogf("http2: server ignoring frame: %v", f.Header())
  1009. return nil
  1010. }
  1011. }
  1012. func (sc *serverConn) processPing(f *PingFrame) error {
  1013. sc.serveG.check()
  1014. if f.IsAck() {
  1015. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  1016. // containing this flag."
  1017. return nil
  1018. }
  1019. if f.StreamID != 0 {
  1020. // "PING frames are not associated with any individual
  1021. // stream. If a PING frame is received with a stream
  1022. // identifier field value other than 0x0, the recipient MUST
  1023. // respond with a connection error (Section 5.4.1) of type
  1024. // PROTOCOL_ERROR."
  1025. return ConnectionError(ErrCodeProtocol)
  1026. }
  1027. sc.writeFrame(frameWriteMsg{write: writePingAck{f}})
  1028. return nil
  1029. }
  1030. func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  1031. sc.serveG.check()
  1032. switch {
  1033. case f.StreamID != 0: // stream-level flow control
  1034. st := sc.streams[f.StreamID]
  1035. if st == nil {
  1036. // "WINDOW_UPDATE can be sent by a peer that has sent a
  1037. // frame bearing the END_STREAM flag. This means that a
  1038. // receiver could receive a WINDOW_UPDATE frame on a "half
  1039. // closed (remote)" or "closed" stream. A receiver MUST
  1040. // NOT treat this as an error, see Section 5.1."
  1041. return nil
  1042. }
  1043. if !st.flow.add(int32(f.Increment)) {
  1044. return StreamError{f.StreamID, ErrCodeFlowControl}
  1045. }
  1046. default: // connection-level flow control
  1047. if !sc.flow.add(int32(f.Increment)) {
  1048. return goAwayFlowError{}
  1049. }
  1050. }
  1051. sc.scheduleFrameWrite()
  1052. return nil
  1053. }
  1054. func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
  1055. sc.serveG.check()
  1056. state, st := sc.state(f.StreamID)
  1057. if state == stateIdle {
  1058. // 6.4 "RST_STREAM frames MUST NOT be sent for a
  1059. // stream in the "idle" state. If a RST_STREAM frame
  1060. // identifying an idle stream is received, the
  1061. // recipient MUST treat this as a connection error
  1062. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1063. return ConnectionError(ErrCodeProtocol)
  1064. }
  1065. if st != nil {
  1066. st.gotReset = true
  1067. st.cancelCtx()
  1068. sc.closeStream(st, StreamError{f.StreamID, f.ErrCode})
  1069. }
  1070. return nil
  1071. }
  1072. func (sc *serverConn) closeStream(st *stream, err error) {
  1073. sc.serveG.check()
  1074. if st.state == stateIdle || st.state == stateClosed {
  1075. panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
  1076. }
  1077. st.state = stateClosed
  1078. sc.curOpenStreams--
  1079. if sc.curOpenStreams == 0 {
  1080. sc.setConnState(http.StateIdle)
  1081. }
  1082. delete(sc.streams, st.id)
  1083. if p := st.body; p != nil {
  1084. p.CloseWithError(err)
  1085. }
  1086. st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc
  1087. sc.writeSched.forgetStream(st.id)
  1088. if st.reqBuf != nil {
  1089. // Stash this request body buffer (64k) away for reuse
  1090. // by a future POST/PUT/etc.
  1091. //
  1092. // TODO(bradfitz): share on the server? sync.Pool?
  1093. // Server requires locks and might hurt contention.
  1094. // sync.Pool might work, or might be worse, depending
  1095. // on goroutine CPU migrations. (get and put on
  1096. // separate CPUs). Maybe a mix of strategies. But
  1097. // this is an easy win for now.
  1098. sc.freeRequestBodyBuf = st.reqBuf
  1099. }
  1100. }
  1101. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  1102. sc.serveG.check()
  1103. if f.IsAck() {
  1104. sc.unackedSettings--
  1105. if sc.unackedSettings < 0 {
  1106. // Why is the peer ACKing settings we never sent?
  1107. // The spec doesn't mention this case, but
  1108. // hang up on them anyway.
  1109. return ConnectionError(ErrCodeProtocol)
  1110. }
  1111. return nil
  1112. }
  1113. if err := f.ForeachSetting(sc.processSetting); err != nil {
  1114. return err
  1115. }
  1116. sc.needToSendSettingsAck = true
  1117. sc.scheduleFrameWrite()
  1118. return nil
  1119. }
  1120. func (sc *serverConn) processSetting(s Setting) error {
  1121. sc.serveG.check()
  1122. if err := s.Valid(); err != nil {
  1123. return err
  1124. }
  1125. if VerboseLogs {
  1126. sc.vlogf("http2: server processing setting %v", s)
  1127. }
  1128. switch s.ID {
  1129. case SettingHeaderTableSize:
  1130. sc.headerTableSize = s.Val
  1131. sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
  1132. case SettingEnablePush:
  1133. sc.pushEnabled = s.Val != 0
  1134. case SettingMaxConcurrentStreams:
  1135. sc.clientMaxStreams = s.Val
  1136. case SettingInitialWindowSize:
  1137. return sc.processSettingInitialWindowSize(s.Val)
  1138. case SettingMaxFrameSize:
  1139. sc.writeSched.maxFrameSize = s.Val
  1140. case SettingMaxHeaderListSize:
  1141. sc.peerMaxHeaderListSize = s.Val
  1142. default:
  1143. // Unknown setting: "An endpoint that receives a SETTINGS
  1144. // frame with any unknown or unsupported identifier MUST
  1145. // ignore that setting."
  1146. if VerboseLogs {
  1147. sc.vlogf("http2: server ignoring unknown setting %v", s)
  1148. }
  1149. }
  1150. return nil
  1151. }
  1152. func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  1153. sc.serveG.check()
  1154. // Note: val already validated to be within range by
  1155. // processSetting's Valid call.
  1156. // "A SETTINGS frame can alter the initial flow control window
  1157. // size for all current streams. When the value of
  1158. // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  1159. // adjust the size of all stream flow control windows that it
  1160. // maintains by the difference between the new value and the
  1161. // old value."
  1162. old := sc.initialWindowSize
  1163. sc.initialWindowSize = int32(val)
  1164. growth := sc.initialWindowSize - old // may be negative
  1165. for _, st := range sc.streams {
  1166. if !st.flow.add(growth) {
  1167. // 6.9.2 Initial Flow Control Window Size
  1168. // "An endpoint MUST treat a change to
  1169. // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  1170. // control window to exceed the maximum size as a
  1171. // connection error (Section 5.4.1) of type
  1172. // FLOW_CONTROL_ERROR."
  1173. return ConnectionError(ErrCodeFlowControl)
  1174. }
  1175. }
  1176. return nil
  1177. }
  1178. func (sc *serverConn) processData(f *DataFrame) error {
  1179. sc.serveG.check()
  1180. // "If a DATA frame is received whose stream is not in "open"
  1181. // or "half closed (local)" state, the recipient MUST respond
  1182. // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  1183. id := f.Header().StreamID
  1184. st, ok := sc.streams[id]
  1185. if !ok || st.state != stateOpen || st.gotTrailerHeader {
  1186. // This includes sending a RST_STREAM if the stream is
  1187. // in stateHalfClosedLocal (which currently means that
  1188. // the http.Handler returned, so it's done reading &
  1189. // done writing). Try to stop the client from sending
  1190. // more DATA.
  1191. return StreamError{id, ErrCodeStreamClosed}
  1192. }
  1193. if st.body == nil {
  1194. panic("internal error: should have a body in this state")
  1195. }
  1196. data := f.Data()
  1197. // Sender sending more than they'd declared?
  1198. if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  1199. st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  1200. return StreamError{id, ErrCodeStreamClosed}
  1201. }
  1202. if len(data) > 0 {
  1203. // Check whether the client has flow control quota.
  1204. if int(st.inflow.available()) < len(data) {
  1205. return StreamError{id, ErrCodeFlowControl}
  1206. }
  1207. st.inflow.take(int32(len(data)))
  1208. wrote, err := st.body.Write(data)
  1209. if err != nil {
  1210. return StreamError{id, ErrCodeStreamClosed}
  1211. }
  1212. if wrote != len(data) {
  1213. panic("internal error: bad Writer")
  1214. }
  1215. st.bodyBytes += int64(len(data))
  1216. }
  1217. if f.StreamEnded() {
  1218. st.endStream()
  1219. }
  1220. return nil
  1221. }
  1222. // endStream closes a Request.Body's pipe. It is called when a DATA
  1223. // frame says a request body is over (or after trailers).
  1224. func (st *stream) endStream() {
  1225. sc := st.sc
  1226. sc.serveG.check()
  1227. if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  1228. st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
  1229. st.declBodyBytes, st.bodyBytes))
  1230. } else {
  1231. st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest)
  1232. st.body.CloseWithError(io.EOF)
  1233. }
  1234. st.state = stateHalfClosedRemote
  1235. }
  1236. // copyTrailersToHandlerRequest is run in the Handler's goroutine in
  1237. // its Request.Body.Read just before it gets io.EOF.
  1238. func (st *stream) copyTrailersToHandlerRequest() {
  1239. for k, vv := range st.trailer {
  1240. if _, ok := st.reqTrailer[k]; ok {
  1241. // Only copy it over it was pre-declared.
  1242. st.reqTrailer[k] = vv
  1243. }
  1244. }
  1245. }
  1246. func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error {
  1247. sc.serveG.check()
  1248. id := f.Header().StreamID
  1249. if sc.inGoAway {
  1250. // Ignore.
  1251. return nil
  1252. }
  1253. // http://http2.github.io/http2-spec/#rfc.section.5.1.1
  1254. // Streams initiated by a client MUST use odd-numbered stream
  1255. // identifiers. [...] An endpoint that receives an unexpected
  1256. // stream identifier MUST respond with a connection error
  1257. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1258. if id%2 != 1 {
  1259. return ConnectionError(ErrCodeProtocol)
  1260. }
  1261. // A HEADERS frame can be used to create a new stream or
  1262. // send a trailer for an open one. If we already have a stream
  1263. // open, let it process its own HEADERS frame (trailers at this
  1264. // point, if it's valid).
  1265. st := sc.streams[f.Header().StreamID]
  1266. if st != nil {
  1267. return st.processTrailerHeaders(f)
  1268. }
  1269. // [...] The identifier of a newly established stream MUST be
  1270. // numerically greater than all streams that the initiating
  1271. // endpoint has opened or reserved. [...] An endpoint that
  1272. // receives an unexpected stream identifier MUST respond with
  1273. // a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1274. if id <= sc.maxStreamID {
  1275. return ConnectionError(ErrCodeProtocol)
  1276. }
  1277. sc.maxStreamID = id
  1278. ctx, cancelCtx := contextWithCancel(sc.baseCtx)
  1279. st = &stream{
  1280. sc: sc,
  1281. id: id,
  1282. state: stateOpen,
  1283. ctx: ctx,
  1284. cancelCtx: cancelCtx,
  1285. }
  1286. if f.StreamEnded() {
  1287. st.state = stateHalfClosedRemote
  1288. }
  1289. st.cw.Init()
  1290. st.flow.conn = &sc.flow // link to conn-level counter
  1291. st.flow.add(sc.initialWindowSize)
  1292. st.inflow.conn = &sc.inflow // link to conn-level counter
  1293. st.inflow.add(initialWindowSize) // TODO: update this when we send a higher initial window size in the initial settings
  1294. sc.streams[id] = st
  1295. if f.HasPriority() {
  1296. adjustStreamPriority(sc.streams, st.id, f.Priority)
  1297. }
  1298. sc.curOpenStreams++
  1299. if sc.curOpenStreams == 1 {
  1300. sc.setConnState(http.StateActive)
  1301. }
  1302. if sc.curOpenStreams > sc.advMaxStreams {
  1303. // "Endpoints MUST NOT exceed the limit set by their
  1304. // peer. An endpoint that receives a HEADERS frame
  1305. // that causes their advertised concurrent stream
  1306. // limit to be exceeded MUST treat this as a stream
  1307. // error (Section 5.4.2) of type PROTOCOL_ERROR or
  1308. // REFUSED_STREAM."
  1309. if sc.unackedSettings == 0 {
  1310. // They should know better.
  1311. return StreamError{st.id, ErrCodeProtocol}
  1312. }
  1313. // Assume it's a network race, where they just haven't
  1314. // received our last SETTINGS update. But actually
  1315. // this can't happen yet, because we don't yet provide
  1316. // a way for users to adjust server parameters at
  1317. // runtime.
  1318. return StreamError{st.id, ErrCodeRefusedStream}
  1319. }
  1320. rw, req, err := sc.newWriterAndRequest(st, f)
  1321. if err != nil {
  1322. return err
  1323. }
  1324. st.reqTrailer = req.Trailer
  1325. if st.reqTrailer != nil {
  1326. st.trailer = make(http.Header)
  1327. }
  1328. st.body = req.Body.(*requestBody).pipe // may be nil
  1329. st.declBodyBytes = req.ContentLength
  1330. handler := sc.handler.ServeHTTP
  1331. if f.Truncated {
  1332. // Their header list was too long. Send a 431 error.
  1333. handler = handleHeaderListTooLong
  1334. } else if err := checkValidHTTP2Request(req); err != nil {
  1335. handler = new400Handler(err)
  1336. }
  1337. go sc.runHandler(rw, req, handler)
  1338. return nil
  1339. }
  1340. func (st *stream) processTrailerHeaders(f *MetaHeadersFrame) error {
  1341. sc := st.sc
  1342. sc.serveG.check()
  1343. if st.gotTrailerHeader {
  1344. return ConnectionError(ErrCodeProtocol)
  1345. }
  1346. st.gotTrailerHeader = true
  1347. if !f.StreamEnded() {
  1348. return StreamError{st.id, ErrCodeProtocol}
  1349. }
  1350. if len(f.PseudoFields()) > 0 {
  1351. return StreamError{st.id, ErrCodeProtocol}
  1352. }
  1353. if st.trailer != nil {
  1354. for _, hf := range f.RegularFields() {
  1355. key := sc.canonicalHeader(hf.Name)
  1356. if !ValidTrailerHeader(key) {
  1357. // TODO: send more details to the peer somehow. But http2 has
  1358. // no way to send debug data at a stream level. Discuss with
  1359. // HTTP folk.
  1360. return StreamError{st.id, ErrCodeProtocol}
  1361. }
  1362. st.trailer[key] = append(st.trailer[key], hf.Value)
  1363. }
  1364. }
  1365. st.endStream()
  1366. return nil
  1367. }
  1368. func (sc *serverConn) processPriority(f *PriorityFrame) error {
  1369. adjustStreamPriority(sc.streams, f.StreamID, f.PriorityParam)
  1370. return nil
  1371. }
  1372. func adjustStreamPriority(streams map[uint32]*stream, streamID uint32, priority PriorityParam) {
  1373. st, ok := streams[streamID]
  1374. if !ok {
  1375. // TODO: not quite correct (this streamID might
  1376. // already exist in the dep tree, but be closed), but
  1377. // close enough for now.
  1378. return
  1379. }
  1380. st.weight = priority.Weight
  1381. parent := streams[priority.StreamDep] // might be nil
  1382. if parent == st {
  1383. // if client tries to set this stream to be the parent of itself
  1384. // ignore and keep going
  1385. return
  1386. }
  1387. // section 5.3.3: If a stream is made dependent on one of its
  1388. // own dependencies, the formerly dependent stream is first
  1389. // moved to be dependent on the reprioritized stream's previous
  1390. // parent. The moved dependency retains its weight.
  1391. for piter := parent; piter != nil; piter = piter.parent {
  1392. if piter == st {
  1393. parent.parent = st.parent
  1394. break
  1395. }
  1396. }
  1397. st.parent = parent
  1398. if priority.Exclusive && (st.parent != nil || priority.StreamDep == 0) {
  1399. for _, openStream := range streams {
  1400. if openStream != st && openStream.parent == st.parent {
  1401. openStream.parent = st
  1402. }
  1403. }
  1404. }
  1405. }
  1406. func (sc *serverConn) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*responseWriter, *http.Request, error) {
  1407. sc.serveG.check()
  1408. method := f.PseudoValue("method")
  1409. path := f.PseudoValue("path")
  1410. scheme := f.PseudoValue("scheme")
  1411. authority := f.PseudoValue("authority")
  1412. isConnect := method == "CONNECT"
  1413. if isConnect {
  1414. if path != "" || scheme != "" || authority == "" {
  1415. return nil, nil, StreamError{f.StreamID, ErrCodeProtocol}
  1416. }
  1417. } else if method == "" || path == "" ||
  1418. (scheme != "https" && scheme != "http") {
  1419. // See 8.1.2.6 Malformed Requests and Responses:
  1420. //
  1421. // Malformed requests or responses that are detected
  1422. // MUST be treated as a stream error (Section 5.4.2)
  1423. // of type PROTOCOL_ERROR."
  1424. //
  1425. // 8.1.2.3 Request Pseudo-Header Fields
  1426. // "All HTTP/2 requests MUST include exactly one valid
  1427. // value for the :method, :scheme, and :path
  1428. // pseudo-header fields"
  1429. return nil, nil, StreamError{f.StreamID, ErrCodeProtocol}
  1430. }
  1431. bodyOpen := !f.StreamEnded()
  1432. if method == "HEAD" && bodyOpen {
  1433. // HEAD requests can't have bodies
  1434. return nil, nil, StreamError{f.StreamID, ErrCodeProtocol}
  1435. }
  1436. var tlsState *tls.ConnectionState // nil if not scheme https
  1437. if scheme == "https" {
  1438. tlsState = sc.tlsState
  1439. }
  1440. header := make(http.Header)
  1441. for _, hf := range f.RegularFields() {
  1442. header.Add(sc.canonicalHeader(hf.Name), hf.Value)
  1443. }
  1444. if authority == "" {
  1445. authority = header.Get("Host")
  1446. }
  1447. needsContinue := header.Get("Expect") == "100-continue"
  1448. if needsContinue {
  1449. header.Del("Expect")
  1450. }
  1451. // Merge Cookie headers into one "; "-delimited value.
  1452. if cookies := header["Cookie"]; len(cookies) > 1 {
  1453. header.Set("Cookie", strings.Join(cookies, "; "))
  1454. }
  1455. // Setup Trailers
  1456. var trailer http.Header
  1457. for _, v := range header["Trailer"] {
  1458. for _, key := range strings.Split(v, ",") {
  1459. key = http.CanonicalHeaderKey(strings.TrimSpace(key))
  1460. switch key {
  1461. case "Transfer-Encoding", "Trailer", "Content-Length":
  1462. // Bogus. (copy of http1 rules)
  1463. // Ignore.
  1464. default:
  1465. if trailer == nil {
  1466. trailer = make(http.Header)
  1467. }
  1468. trailer[key] = nil
  1469. }
  1470. }
  1471. }
  1472. delete(header, "Trailer")
  1473. body := &requestBody{
  1474. conn: sc,
  1475. stream: st,
  1476. needsContinue: needsContinue,
  1477. }
  1478. var url_ *url.URL
  1479. var requestURI string
  1480. if isConnect {
  1481. url_ = &url.URL{Host: authority}
  1482. requestURI = authority // mimic HTTP/1 server behavior
  1483. } else {
  1484. var err error
  1485. url_, err = url.ParseRequestURI(path)
  1486. if err != nil {
  1487. return nil, nil, StreamError{f.StreamID, ErrCodeProtocol}
  1488. }
  1489. requestURI = path
  1490. }
  1491. req := &http.Request{
  1492. Method: method,
  1493. URL: url_,
  1494. RemoteAddr: sc.remoteAddrStr,
  1495. Header: header,
  1496. RequestURI: requestURI,
  1497. Proto: "HTTP/2.0",
  1498. ProtoMajor: 2,
  1499. ProtoMinor: 0,
  1500. TLS: tlsState,
  1501. Host: authority,
  1502. Body: body,
  1503. Trailer: trailer,
  1504. }
  1505. req = requestWithContext(req, st.ctx)
  1506. if bodyOpen {
  1507. // Disabled, per golang.org/issue/14960:
  1508. // st.reqBuf = sc.getRequestBodyBuf()
  1509. // TODO: remove this 64k of garbage per request (again, but without a data race):
  1510. buf := make([]byte, initialWindowSize)
  1511. body.pipe = &pipe{
  1512. b: &fixedBuffer{buf: buf},
  1513. }
  1514. if vv, ok := header["Content-Length"]; ok {
  1515. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  1516. } else {
  1517. req.ContentLength = -1
  1518. }
  1519. }
  1520. rws := responseWriterStatePool.Get().(*responseWriterState)
  1521. bwSave := rws.bw
  1522. *rws = responseWriterState{} // zero all the fields
  1523. rws.conn = sc
  1524. rws.bw = bwSave
  1525. rws.bw.Reset(chunkWriter{rws})
  1526. rws.stream = st
  1527. rws.req = req
  1528. rws.body = body
  1529. rw := &responseWriter{rws: rws}
  1530. return rw, req, nil
  1531. }
  1532. func (sc *serverConn) getRequestBodyBuf() []byte {
  1533. sc.serveG.check()
  1534. if buf := sc.freeRequestBodyBuf; buf != nil {
  1535. sc.freeRequestBodyBuf = nil
  1536. return buf
  1537. }
  1538. return make([]byte, initialWindowSize)
  1539. }
  1540. // Run on its own goroutine.
  1541. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) {
  1542. didPanic := true
  1543. defer func() {
  1544. rw.rws.stream.cancelCtx()
  1545. if didPanic {
  1546. e := recover()
  1547. // Same as net/http:
  1548. const size = 64 << 10
  1549. buf := make([]byte, size)
  1550. buf = buf[:runtime.Stack(buf, false)]
  1551. sc.writeFrameFromHandler(frameWriteMsg{
  1552. write: handlerPanicRST{rw.rws.stream.id},
  1553. stream: rw.rws.stream,
  1554. })
  1555. sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf)
  1556. return
  1557. }
  1558. rw.handlerDone()
  1559. }()
  1560. handler(rw, req)
  1561. didPanic = false
  1562. }
  1563. func handleHeaderListTooLong(w http.ResponseWriter, r *http.Request) {
  1564. // 10.5.1 Limits on Header Block Size:
  1565. // .. "A server that receives a larger header block than it is
  1566. // willing to handle can send an HTTP 431 (Request Header Fields Too
  1567. // Large) status code"
  1568. const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+
  1569. w.WriteHeader(statusRequestHeaderFieldsTooLarge)
  1570. io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
  1571. }
  1572. // called from handler goroutines.
  1573. // h may be nil.
  1574. func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error {
  1575. sc.serveG.checkNotOn() // NOT on
  1576. var errc chan error
  1577. if headerData.h != nil {
  1578. // If there's a header map (which we don't own), so we have to block on
  1579. // waiting for this frame to be written, so an http.Flush mid-handler
  1580. // writes out the correct value of keys, before a handler later potentially
  1581. // mutates it.
  1582. errc = errChanPool.Get().(chan error)
  1583. }
  1584. if err := sc.writeFrameFromHandler(frameWriteMsg{
  1585. write: headerData,
  1586. stream: st,
  1587. done: errc,
  1588. }); err != nil {
  1589. return err
  1590. }
  1591. if errc != nil {
  1592. select {
  1593. case err := <-errc:
  1594. errChanPool.Put(errc)
  1595. return err
  1596. case <-sc.doneServing:
  1597. return errClientDisconnected
  1598. case <-st.cw:
  1599. return errStreamClosed
  1600. }
  1601. }
  1602. return nil
  1603. }
  1604. // called from handler goroutines.
  1605. func (sc *serverConn) write100ContinueHeaders(st *stream) {
  1606. sc.writeFrameFromHandler(frameWriteMsg{
  1607. write: write100ContinueHeadersFrame{st.id},
  1608. stream: st,
  1609. })
  1610. }
  1611. // A bodyReadMsg tells the server loop that the http.Handler read n
  1612. // bytes of the DATA from the client on the given stream.
  1613. type bodyReadMsg struct {
  1614. st *stream
  1615. n int
  1616. }
  1617. // called from handler goroutines.
  1618. // Notes that the handler for the given stream ID read n bytes of its body
  1619. // and schedules flow control tokens to be sent.
  1620. func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int) {
  1621. sc.serveG.checkNotOn() // NOT on
  1622. select {
  1623. case sc.bodyReadCh <- bodyReadMsg{st, n}:
  1624. case <-sc.doneServing:
  1625. }
  1626. }
  1627. func (sc *serverConn) noteBodyRead(st *stream, n int) {
  1628. sc.serveG.check()
  1629. sc.sendWindowUpdate(nil, n) // conn-level
  1630. if st.state != stateHalfClosedRemote && st.state != stateClosed {
  1631. // Don't send this WINDOW_UPDATE if the stream is closed
  1632. // remotely.
  1633. sc.sendWindowUpdate(st, n)
  1634. }
  1635. }
  1636. // st may be nil for conn-level
  1637. func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
  1638. sc.serveG.check()
  1639. // "The legal range for the increment to the flow control
  1640. // window is 1 to 2^31-1 (2,147,483,647) octets."
  1641. // A Go Read call on 64-bit machines could in theory read
  1642. // a larger Read than this. Very unlikely, but we handle it here
  1643. // rather than elsewhere for now.
  1644. const maxUint31 = 1<<31 - 1
  1645. for n >= maxUint31 {
  1646. sc.sendWindowUpdate32(st, maxUint31)
  1647. n -= maxUint31
  1648. }
  1649. sc.sendWindowUpdate32(st, int32(n))
  1650. }
  1651. // st may be nil for conn-level
  1652. func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) {
  1653. sc.serveG.check()
  1654. if n == 0 {
  1655. return
  1656. }
  1657. if n < 0 {
  1658. panic("negative update")
  1659. }
  1660. var streamID uint32
  1661. if st != nil {
  1662. streamID = st.id
  1663. }
  1664. sc.writeFrame(frameWriteMsg{
  1665. write: writeWindowUpdate{streamID: streamID, n: uint32(n)},
  1666. stream: st,
  1667. })
  1668. var ok bool
  1669. if st == nil {
  1670. ok = sc.inflow.add(n)
  1671. } else {
  1672. ok = st.inflow.add(n)
  1673. }
  1674. if !ok {
  1675. panic("internal error; sent too many window updates without decrements?")
  1676. }
  1677. }
  1678. type requestBody struct {
  1679. stream *stream
  1680. conn *serverConn
  1681. closed bool
  1682. pipe *pipe // non-nil if we have a HTTP entity message body
  1683. needsContinue bool // need to send a 100-continue
  1684. }
  1685. func (b *requestBody) Close() error {
  1686. if b.pipe != nil {
  1687. b.pipe.CloseWithError(errClosedBody)
  1688. }
  1689. b.closed = true
  1690. return nil
  1691. }
  1692. func (b *requestBody) Read(p []byte) (n int, err error) {
  1693. if b.needsContinue {
  1694. b.needsContinue = false
  1695. b.conn.write100ContinueHeaders(b.stream)
  1696. }
  1697. if b.pipe == nil {
  1698. return 0, io.EOF
  1699. }
  1700. n, err = b.pipe.Read(p)
  1701. if n > 0 {
  1702. b.conn.noteBodyReadFromHandler(b.stream, n)
  1703. }
  1704. return
  1705. }
  1706. // responseWriter is the http.ResponseWriter implementation. It's
  1707. // intentionally small (1 pointer wide) to minimize garbage. The
  1708. // responseWriterState pointer inside is zeroed at the end of a
  1709. // request (in handlerDone) and calls on the responseWriter thereafter
  1710. // simply crash (caller's mistake), but the much larger responseWriterState
  1711. // and buffers are reused between multiple requests.
  1712. type responseWriter struct {
  1713. rws *responseWriterState
  1714. }
  1715. // Optional http.ResponseWriter interfaces implemented.
  1716. var (
  1717. _ http.CloseNotifier = (*responseWriter)(nil)
  1718. _ http.Flusher = (*responseWriter)(nil)
  1719. _ stringWriter = (*responseWriter)(nil)
  1720. )
  1721. type responseWriterState struct {
  1722. // immutable within a request:
  1723. stream *stream
  1724. req *http.Request
  1725. body *requestBody // to close at end of request, if DATA frames didn't
  1726. conn *serverConn
  1727. // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
  1728. bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
  1729. // mutated by http.Handler goroutine:
  1730. handlerHeader http.Header // nil until called
  1731. snapHeader http.Header // snapshot of handlerHeader at WriteHeader time
  1732. trailers []string // set in writeChunk
  1733. status int // status code passed to WriteHeader
  1734. wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
  1735. sentHeader bool // have we sent the header frame?
  1736. handlerDone bool // handler has finished
  1737. sentContentLen int64 // non-zero if handler set a Content-Length header
  1738. wroteBytes int64
  1739. closeNotifierMu sync.Mutex // guards closeNotifierCh
  1740. closeNotifierCh chan bool // nil until first used
  1741. }
  1742. type chunkWriter struct{ rws *responseWriterState }
  1743. func (cw chunkWriter) Write(p []byte) (n int, err error) { return cw.rws.writeChunk(p) }
  1744. func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) != 0 }
  1745. // declareTrailer is called for each Trailer header when the
  1746. // response header is written. It notes that a header will need to be
  1747. // written in the trailers at the end of the response.
  1748. func (rws *responseWriterState) declareTrailer(k string) {
  1749. k = http.CanonicalHeaderKey(k)
  1750. if !ValidTrailerHeader(k) {
  1751. // Forbidden by RFC 2616 14.40.
  1752. rws.conn.logf("ignoring invalid trailer %q", k)
  1753. return
  1754. }
  1755. if !strSliceContains(rws.trailers, k) {
  1756. rws.trailers = append(rws.trailers, k)
  1757. }
  1758. }
  1759. // writeChunk writes chunks from the bufio.Writer. But because
  1760. // bufio.Writer may bypass its chunking, sometimes p may be
  1761. // arbitrarily large.
  1762. //
  1763. // writeChunk is also responsible (on the first chunk) for sending the
  1764. // HEADER response.
  1765. func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
  1766. if !rws.wroteHeader {
  1767. rws.writeHeader(200)
  1768. }
  1769. isHeadResp := rws.req.Method == "HEAD"
  1770. if !rws.sentHeader {
  1771. rws.sentHeader = true
  1772. var ctype, clen string
  1773. if clen = rws.snapHeader.Get("Content-Length"); clen != "" {
  1774. rws.snapHeader.Del("Content-Length")
  1775. clen64, err := strconv.ParseInt(clen, 10, 64)
  1776. if err == nil && clen64 >= 0 {
  1777. rws.sentContentLen = clen64
  1778. } else {
  1779. clen = ""
  1780. }
  1781. }
  1782. if clen == "" && rws.handlerDone && bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) {
  1783. clen = strconv.Itoa(len(p))
  1784. }
  1785. _, hasContentType := rws.snapHeader["Content-Type"]
  1786. if !hasContentType && bodyAllowedForStatus(rws.status) {
  1787. ctype = http.DetectContentType(p)
  1788. }
  1789. var date string
  1790. if _, ok := rws.snapHeader["Date"]; !ok {
  1791. // TODO(bradfitz): be faster here, like net/http? measure.
  1792. date = time.Now().UTC().Format(http.TimeFormat)
  1793. }
  1794. for _, v := range rws.snapHeader["Trailer"] {
  1795. foreachHeaderElement(v, rws.declareTrailer)
  1796. }
  1797. endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp
  1798. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  1799. streamID: rws.stream.id,
  1800. httpResCode: rws.status,
  1801. h: rws.snapHeader,
  1802. endStream: endStream,
  1803. contentType: ctype,
  1804. contentLength: clen,
  1805. date: date,
  1806. })
  1807. if err != nil {
  1808. return 0, err
  1809. }
  1810. if endStream {
  1811. return 0, nil
  1812. }
  1813. }
  1814. if isHeadResp {
  1815. return len(p), nil
  1816. }
  1817. if len(p) == 0 && !rws.handlerDone {
  1818. return 0, nil
  1819. }
  1820. if rws.handlerDone {
  1821. rws.promoteUndeclaredTrailers()
  1822. }
  1823. endStream := rws.handlerDone && !rws.hasTrailers()
  1824. if len(p) > 0 || endStream {
  1825. // only send a 0 byte DATA frame if we're ending the stream.
  1826. if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil {
  1827. return 0, err
  1828. }
  1829. }
  1830. if rws.handlerDone && rws.hasTrailers() {
  1831. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  1832. streamID: rws.stream.id,
  1833. h: rws.handlerHeader,
  1834. trailers: rws.trailers,
  1835. endStream: true,
  1836. })
  1837. return len(p), err
  1838. }
  1839. return len(p), nil
  1840. }
  1841. // TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
  1842. // that, if present, signals that the map entry is actually for
  1843. // the response trailers, and not the response headers. The prefix
  1844. // is stripped after the ServeHTTP call finishes and the values are
  1845. // sent in the trailers.
  1846. //
  1847. // This mechanism is intended only for trailers that are not known
  1848. // prior to the headers being written. If the set of trailers is fixed
  1849. // or known before the header is written, the normal Go trailers mechanism
  1850. // is preferred:
  1851. // https://golang.org/pkg/net/http/#ResponseWriter
  1852. // https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
  1853. const TrailerPrefix = "Trailer:"
  1854. // promoteUndeclaredTrailers permits http.Handlers to set trailers
  1855. // after the header has already been flushed. Because the Go
  1856. // ResponseWriter interface has no way to set Trailers (only the
  1857. // Header), and because we didn't want to expand the ResponseWriter
  1858. // interface, and because nobody used trailers, and because RFC 2616
  1859. // says you SHOULD (but not must) predeclare any trailers in the
  1860. // header, the official ResponseWriter rules said trailers in Go must
  1861. // be predeclared, and then we reuse the same ResponseWriter.Header()
  1862. // map to mean both Headers and Trailers. When it's time to write the
  1863. // Trailers, we pick out the fields of Headers that were declared as
  1864. // trailers. That worked for a while, until we found the first major
  1865. // user of Trailers in the wild: gRPC (using them only over http2),
  1866. // and gRPC libraries permit setting trailers mid-stream without
  1867. // predeclarnig them. So: change of plans. We still permit the old
  1868. // way, but we also permit this hack: if a Header() key begins with
  1869. // "Trailer:", the suffix of that key is a Trailer. Because ':' is an
  1870. // invalid token byte anyway, there is no ambiguity. (And it's already
  1871. // filtered out) It's mildly hacky, but not terrible.
  1872. //
  1873. // This method runs after the Handler is done and promotes any Header
  1874. // fields to be trailers.
  1875. func (rws *responseWriterState) promoteUndeclaredTrailers() {
  1876. for k, vv := range rws.handlerHeader {
  1877. if !strings.HasPrefix(k, TrailerPrefix) {
  1878. continue
  1879. }
  1880. trailerKey := strings.TrimPrefix(k, TrailerPrefix)
  1881. rws.declareTrailer(trailerKey)
  1882. rws.handlerHeader[http.CanonicalHeaderKey(trailerKey)] = vv
  1883. }
  1884. if len(rws.trailers) > 1 {
  1885. sorter := sorterPool.Get().(*sorter)
  1886. sorter.SortStrings(rws.trailers)
  1887. sorterPool.Put(sorter)
  1888. }
  1889. }
  1890. func (w *responseWriter) Flush() {
  1891. rws := w.rws
  1892. if rws == nil {
  1893. panic("Header called after Handler finished")
  1894. }
  1895. if rws.bw.Buffered() > 0 {
  1896. if err := rws.bw.Flush(); err != nil {
  1897. // Ignore the error. The frame writer already knows.
  1898. return
  1899. }
  1900. } else {
  1901. // The bufio.Writer won't call chunkWriter.Write
  1902. // (writeChunk with zero bytes, so we have to do it
  1903. // ourselves to force the HTTP response header and/or
  1904. // final DATA frame (with END_STREAM) to be sent.
  1905. rws.writeChunk(nil)
  1906. }
  1907. }
  1908. func (w *responseWriter) CloseNotify() <-chan bool {
  1909. rws := w.rws
  1910. if rws == nil {
  1911. panic("CloseNotify called after Handler finished")
  1912. }
  1913. rws.closeNotifierMu.Lock()
  1914. ch := rws.closeNotifierCh
  1915. if ch == nil {
  1916. ch = make(chan bool, 1)
  1917. rws.closeNotifierCh = ch
  1918. go func() {
  1919. rws.stream.cw.Wait() // wait for close
  1920. ch <- true
  1921. }()
  1922. }
  1923. rws.closeNotifierMu.Unlock()
  1924. return ch
  1925. }
  1926. func (w *responseWriter) Header() http.Header {
  1927. rws := w.rws
  1928. if rws == nil {
  1929. panic("Header called after Handler finished")
  1930. }
  1931. if rws.handlerHeader == nil {
  1932. rws.handlerHeader = make(http.Header)
  1933. }
  1934. return rws.handlerHeader
  1935. }
  1936. func (w *responseWriter) WriteHeader(code int) {
  1937. rws := w.rws
  1938. if rws == nil {
  1939. panic("WriteHeader called after Handler finished")
  1940. }
  1941. rws.writeHeader(code)
  1942. }
  1943. func (rws *responseWriterState) writeHeader(code int) {
  1944. if !rws.wroteHeader {
  1945. rws.wroteHeader = true
  1946. rws.status = code
  1947. if len(rws.handlerHeader) > 0 {
  1948. rws.snapHeader = cloneHeader(rws.handlerHeader)
  1949. }
  1950. }
  1951. }
  1952. func cloneHeader(h http.Header) http.Header {
  1953. h2 := make(http.Header, len(h))
  1954. for k, vv := range h {
  1955. vv2 := make([]string, len(vv))
  1956. copy(vv2, vv)
  1957. h2[k] = vv2
  1958. }
  1959. return h2
  1960. }
  1961. // The Life Of A Write is like this:
  1962. //
  1963. // * Handler calls w.Write or w.WriteString ->
  1964. // * -> rws.bw (*bufio.Writer) ->
  1965. // * (Handler migth call Flush)
  1966. // * -> chunkWriter{rws}
  1967. // * -> responseWriterState.writeChunk(p []byte)
  1968. // * -> responseWriterState.writeChunk (most of the magic; see comment there)
  1969. func (w *responseWriter) Write(p []byte) (n int, err error) {
  1970. return w.write(len(p), p, "")
  1971. }
  1972. func (w *responseWriter) WriteString(s string) (n int, err error) {
  1973. return w.write(len(s), nil, s)
  1974. }
  1975. // either dataB or dataS is non-zero.
  1976. func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  1977. rws := w.rws
  1978. if rws == nil {
  1979. panic("Write called after Handler finished")
  1980. }
  1981. if !rws.wroteHeader {
  1982. w.WriteHeader(200)
  1983. }
  1984. if !bodyAllowedForStatus(rws.status) {
  1985. return 0, http.ErrBodyNotAllowed
  1986. }
  1987. rws.wroteBytes += int64(len(dataB)) + int64(len(dataS)) // only one can be set
  1988. if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen {
  1989. // TODO: send a RST_STREAM
  1990. return 0, errors.New("http2: handler wrote more than declared Content-Length")
  1991. }
  1992. if dataB != nil {
  1993. return rws.bw.Write(dataB)
  1994. } else {
  1995. return rws.bw.WriteString(dataS)
  1996. }
  1997. }
  1998. func (w *responseWriter) handlerDone() {
  1999. rws := w.rws
  2000. rws.handlerDone = true
  2001. w.Flush()
  2002. w.rws = nil
  2003. responseWriterStatePool.Put(rws)
  2004. }
  2005. // foreachHeaderElement splits v according to the "#rule" construction
  2006. // in RFC 2616 section 2.1 and calls fn for each non-empty element.
  2007. func foreachHeaderElement(v string, fn func(string)) {
  2008. v = textproto.TrimString(v)
  2009. if v == "" {
  2010. return
  2011. }
  2012. if !strings.Contains(v, ",") {
  2013. fn(v)
  2014. return
  2015. }
  2016. for _, f := range strings.Split(v, ",") {
  2017. if f = textproto.TrimString(f); f != "" {
  2018. fn(f)
  2019. }
  2020. }
  2021. }
  2022. // From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2
  2023. var connHeaders = []string{
  2024. "Connection",
  2025. "Keep-Alive",
  2026. "Proxy-Connection",
  2027. "Transfer-Encoding",
  2028. "Upgrade",
  2029. }
  2030. // checkValidHTTP2Request checks whether req is a valid HTTP/2 request,
  2031. // per RFC 7540 Section 8.1.2.2.
  2032. // The returned error is reported to users.
  2033. func checkValidHTTP2Request(req *http.Request) error {
  2034. for _, h := range connHeaders {
  2035. if _, ok := req.Header[h]; ok {
  2036. return fmt.Errorf("request header %q is not valid in HTTP/2", h)
  2037. }
  2038. }
  2039. te := req.Header["Te"]
  2040. if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) {
  2041. return errors.New(`request header "TE" may only be "trailers" in HTTP/2`)
  2042. }
  2043. return nil
  2044. }
  2045. func new400Handler(err error) http.HandlerFunc {
  2046. return func(w http.ResponseWriter, r *http.Request) {
  2047. http.Error(w, err.Error(), http.StatusBadRequest)
  2048. }
  2049. }
  2050. // ValidTrailerHeader reports whether name is a valid header field name to appear
  2051. // in trailers.
  2052. // See: http://tools.ietf.org/html/rfc7230#section-4.1.2
  2053. func ValidTrailerHeader(name string) bool {
  2054. name = http.CanonicalHeaderKey(name)
  2055. if strings.HasPrefix(name, "If-") || badTrailer[name] {
  2056. return false
  2057. }
  2058. return true
  2059. }
  2060. var badTrailer = map[string]bool{
  2061. "Authorization": true,
  2062. "Cache-Control": true,
  2063. "Connection": true,
  2064. "Content-Encoding": true,
  2065. "Content-Length": true,
  2066. "Content-Range": true,
  2067. "Content-Type": true,
  2068. "Expect": true,
  2069. "Host": true,
  2070. "Keep-Alive": true,
  2071. "Max-Forwards": true,
  2072. "Pragma": true,
  2073. "Proxy-Authenticate": true,
  2074. "Proxy-Authorization": true,
  2075. "Proxy-Connection": true,
  2076. "Range": true,
  2077. "Realm": true,
  2078. "Te": true,
  2079. "Trailer": true,
  2080. "Transfer-Encoding": true,
  2081. "Www-Authenticate": true,
  2082. }