server.go 68 KB

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