server.go 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893
  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: finish GOAWAY support. Consider each incoming frame type and
  8. // whether it should be ignored during a shutdown race.
  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/url"
  43. "strconv"
  44. "strings"
  45. "sync"
  46. "time"
  47. "golang.org/x/net/http2/hpack"
  48. )
  49. const (
  50. prefaceTimeout = 10 * time.Second
  51. firstSettingsTimeout = 2 * time.Second // should be in-flight with preface anyway
  52. handlerChunkWriteSize = 4 << 10
  53. defaultMaxStreams = 250 // TODO: make this 100 as the GFE seems to?
  54. )
  55. var (
  56. errClientDisconnected = errors.New("client disconnected")
  57. errClosedBody = errors.New("body closed by handler")
  58. errHandlerComplete = errors.New("http2: request body closed due to handler exiting")
  59. errStreamClosed = errors.New("http2: stream closed")
  60. )
  61. var responseWriterStatePool = sync.Pool{
  62. New: func() interface{} {
  63. rws := &responseWriterState{}
  64. rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize)
  65. return rws
  66. },
  67. }
  68. // Test hooks.
  69. var (
  70. testHookOnConn func()
  71. testHookGetServerConn func(*serverConn)
  72. testHookOnPanicMu *sync.Mutex // nil except in tests
  73. testHookOnPanic func(sc *serverConn, panicVal interface{}) (rePanic bool)
  74. )
  75. // Server is an HTTP/2 server.
  76. type Server struct {
  77. // MaxHandlers limits the number of http.Handler ServeHTTP goroutines
  78. // which may run at a time over all connections.
  79. // Negative or zero no limit.
  80. // TODO: implement
  81. MaxHandlers int
  82. // MaxConcurrentStreams optionally specifies the number of
  83. // concurrent streams that each client may have open at a
  84. // time. This is unrelated to the number of http.Handler goroutines
  85. // which may be active globally, which is MaxHandlers.
  86. // If zero, MaxConcurrentStreams defaults to at least 100, per
  87. // the HTTP/2 spec's recommendations.
  88. MaxConcurrentStreams uint32
  89. // MaxReadFrameSize optionally specifies the largest frame
  90. // this server is willing to read. A valid value is between
  91. // 16k and 16M, inclusive. If zero or otherwise invalid, a
  92. // default value is used.
  93. MaxReadFrameSize uint32
  94. // PermitProhibitedCipherSuites, if true, permits the use of
  95. // cipher suites prohibited by the HTTP/2 spec.
  96. PermitProhibitedCipherSuites bool
  97. }
  98. func (s *Server) maxReadFrameSize() uint32 {
  99. if v := s.MaxReadFrameSize; v >= minMaxFrameSize && v <= maxFrameSize {
  100. return v
  101. }
  102. return defaultMaxReadFrameSize
  103. }
  104. func (s *Server) maxConcurrentStreams() uint32 {
  105. if v := s.MaxConcurrentStreams; v > 0 {
  106. return v
  107. }
  108. return defaultMaxStreams
  109. }
  110. // ConfigureServer adds HTTP/2 support to a net/http Server.
  111. //
  112. // The configuration conf may be nil.
  113. //
  114. // ConfigureServer must be called before s begins serving.
  115. func ConfigureServer(s *http.Server, conf *Server) error {
  116. if conf == nil {
  117. conf = new(Server)
  118. }
  119. if s.TLSConfig == nil {
  120. s.TLSConfig = new(tls.Config)
  121. } else if s.TLSConfig.CipherSuites != nil {
  122. // If they already provided a CipherSuite list, return
  123. // an error if it has a bad order or is missing
  124. // ECDHE_RSA_WITH_AES_128_GCM_SHA256.
  125. const requiredCipher = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  126. haveRequired := false
  127. sawBad := false
  128. for i, cs := range s.TLSConfig.CipherSuites {
  129. if cs == requiredCipher {
  130. haveRequired = true
  131. }
  132. if isBadCipher(cs) {
  133. sawBad = true
  134. } else if sawBad {
  135. 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)
  136. }
  137. }
  138. if !haveRequired {
  139. return fmt.Errorf("http2: TLSConfig.CipherSuites is missing HTTP/2-required TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256")
  140. }
  141. }
  142. // Note: not setting MinVersion to tls.VersionTLS12,
  143. // as we don't want to interfere with HTTP/1.1 traffic
  144. // on the user's server. We enforce TLS 1.2 later once
  145. // we accept a connection. Ideally this should be done
  146. // during next-proto selection, but using TLS <1.2 with
  147. // HTTP/2 is still the client's bug.
  148. s.TLSConfig.PreferServerCipherSuites = true
  149. haveNPN := false
  150. for _, p := range s.TLSConfig.NextProtos {
  151. if p == NextProtoTLS {
  152. haveNPN = true
  153. break
  154. }
  155. }
  156. if !haveNPN {
  157. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, NextProtoTLS)
  158. }
  159. // h2-14 is temporary (as of 2015-03-05) while we wait for all browsers
  160. // to switch to "h2".
  161. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, "h2-14")
  162. if s.TLSNextProto == nil {
  163. s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
  164. }
  165. protoHandler := func(hs *http.Server, c *tls.Conn, h http.Handler) {
  166. if testHookOnConn != nil {
  167. testHookOnConn()
  168. }
  169. conf.handleConn(hs, c, h)
  170. }
  171. s.TLSNextProto[NextProtoTLS] = protoHandler
  172. s.TLSNextProto["h2-14"] = protoHandler // temporary; see above.
  173. return nil
  174. }
  175. func (srv *Server) handleConn(hs *http.Server, c net.Conn, h http.Handler) {
  176. sc := &serverConn{
  177. srv: srv,
  178. hs: hs,
  179. conn: c,
  180. remoteAddrStr: c.RemoteAddr().String(),
  181. bw: newBufferedWriter(c),
  182. handler: h,
  183. streams: make(map[uint32]*stream),
  184. readFrameCh: make(chan readFrameResult),
  185. wantWriteFrameCh: make(chan frameWriteMsg, 8),
  186. wroteFrameCh: make(chan frameWriteResult, 1), // buffered; one send in writeFrameAsync
  187. bodyReadCh: make(chan bodyReadMsg), // buffering doesn't matter either way
  188. doneServing: make(chan struct{}),
  189. advMaxStreams: srv.maxConcurrentStreams(),
  190. writeSched: writeScheduler{
  191. maxFrameSize: initialMaxFrameSize,
  192. },
  193. initialWindowSize: initialWindowSize,
  194. headerTableSize: initialHeaderTableSize,
  195. serveG: newGoroutineLock(),
  196. pushEnabled: true,
  197. }
  198. sc.flow.add(initialWindowSize)
  199. sc.inflow.add(initialWindowSize)
  200. sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
  201. sc.hpackDecoder = hpack.NewDecoder(initialHeaderTableSize, sc.onNewHeaderField)
  202. sc.hpackDecoder.SetMaxStringLength(sc.maxHeaderStringLen())
  203. fr := NewFramer(sc.bw, c)
  204. fr.SetMaxReadFrameSize(srv.maxReadFrameSize())
  205. sc.framer = fr
  206. if tc, ok := c.(*tls.Conn); ok {
  207. sc.tlsState = new(tls.ConnectionState)
  208. *sc.tlsState = tc.ConnectionState()
  209. // 9.2 Use of TLS Features
  210. // An implementation of HTTP/2 over TLS MUST use TLS
  211. // 1.2 or higher with the restrictions on feature set
  212. // and cipher suite described in this section. Due to
  213. // implementation limitations, it might not be
  214. // possible to fail TLS negotiation. An endpoint MUST
  215. // immediately terminate an HTTP/2 connection that
  216. // does not meet the TLS requirements described in
  217. // this section with a connection error (Section
  218. // 5.4.1) of type INADEQUATE_SECURITY.
  219. if sc.tlsState.Version < tls.VersionTLS12 {
  220. sc.rejectConn(ErrCodeInadequateSecurity, "TLS version too low")
  221. return
  222. }
  223. if sc.tlsState.ServerName == "" {
  224. // Client must use SNI, but we don't enforce that anymore,
  225. // since it was causing problems when connecting to bare IP
  226. // addresses during development.
  227. //
  228. // TODO: optionally enforce? Or enforce at the time we receive
  229. // a new request, and verify the the ServerName matches the :authority?
  230. // But that precludes proxy situations, perhaps.
  231. //
  232. // So for now, do nothing here again.
  233. }
  234. if !srv.PermitProhibitedCipherSuites && isBadCipher(sc.tlsState.CipherSuite) {
  235. // "Endpoints MAY choose to generate a connection error
  236. // (Section 5.4.1) of type INADEQUATE_SECURITY if one of
  237. // the prohibited cipher suites are negotiated."
  238. //
  239. // We choose that. In my opinion, the spec is weak
  240. // here. It also says both parties must support at least
  241. // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 so there's no
  242. // excuses here. If we really must, we could allow an
  243. // "AllowInsecureWeakCiphers" option on the server later.
  244. // Let's see how it plays out first.
  245. sc.rejectConn(ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite))
  246. return
  247. }
  248. }
  249. if hook := testHookGetServerConn; hook != nil {
  250. hook(sc)
  251. }
  252. sc.serve()
  253. }
  254. // isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec.
  255. func isBadCipher(cipher uint16) bool {
  256. switch cipher {
  257. case tls.TLS_RSA_WITH_RC4_128_SHA,
  258. tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  259. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  260. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  261. tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
  262. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  263. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  264. tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
  265. tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  266. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  267. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
  268. // Reject cipher suites from Appendix A.
  269. // "This list includes those cipher suites that do not
  270. // offer an ephemeral key exchange and those that are
  271. // based on the TLS null, stream or block cipher type"
  272. return true
  273. default:
  274. return false
  275. }
  276. }
  277. func (sc *serverConn) rejectConn(err ErrCode, debug string) {
  278. sc.vlogf("REJECTING conn: %v, %s", err, debug)
  279. // ignoring errors. hanging up anyway.
  280. sc.framer.WriteGoAway(0, err, []byte(debug))
  281. sc.bw.Flush()
  282. sc.conn.Close()
  283. }
  284. type serverConn struct {
  285. // Immutable:
  286. srv *Server
  287. hs *http.Server
  288. conn net.Conn
  289. bw *bufferedWriter // writing to conn
  290. handler http.Handler
  291. framer *Framer
  292. hpackDecoder *hpack.Decoder
  293. doneServing chan struct{} // closed when serverConn.serve ends
  294. readFrameCh chan readFrameResult // written by serverConn.readFrames
  295. wantWriteFrameCh chan frameWriteMsg // from handlers -> serve
  296. wroteFrameCh chan frameWriteResult // from writeFrameAsync -> serve, tickles more frame writes
  297. bodyReadCh chan bodyReadMsg // from handlers -> serve
  298. testHookCh chan func(int) // code to run on the serve loop
  299. flow flow // conn-wide (not stream-specific) outbound flow control
  300. inflow flow // conn-wide inbound flow control
  301. tlsState *tls.ConnectionState // shared by all handlers, like net/http
  302. remoteAddrStr string
  303. // Everything following is owned by the serve loop; use serveG.check():
  304. serveG goroutineLock // used to verify funcs are on serve()
  305. pushEnabled bool
  306. sawFirstSettings bool // got the initial SETTINGS frame after the preface
  307. needToSendSettingsAck bool
  308. unackedSettings int // how many SETTINGS have we sent without ACKs?
  309. clientMaxStreams uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)
  310. advMaxStreams uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client
  311. curOpenStreams uint32 // client's number of open streams
  312. maxStreamID uint32 // max ever seen
  313. streams map[uint32]*stream
  314. initialWindowSize int32
  315. headerTableSize uint32
  316. peerMaxHeaderListSize uint32 // zero means unknown (default)
  317. canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case
  318. req requestParam // non-zero while reading request headers
  319. writingFrame bool // started write goroutine but haven't heard back on wroteFrameCh
  320. needsFrameFlush bool // last frame write wasn't a flush
  321. writeSched writeScheduler
  322. inGoAway bool // we've started to or sent GOAWAY
  323. needToSendGoAway bool // we need to schedule a GOAWAY frame write
  324. goAwayCode ErrCode
  325. shutdownTimerCh <-chan time.Time // nil until used
  326. shutdownTimer *time.Timer // nil until used
  327. // Owned by the writeFrameAsync goroutine:
  328. headerWriteBuf bytes.Buffer
  329. hpackEncoder *hpack.Encoder
  330. }
  331. func (sc *serverConn) maxHeaderStringLen() int {
  332. v := sc.maxHeaderListSize()
  333. if uint32(int(v)) == v {
  334. return int(v)
  335. }
  336. // They had a crazy big number for MaxHeaderBytes anyway,
  337. // so give them unlimited header lengths:
  338. return 0
  339. }
  340. func (sc *serverConn) maxHeaderListSize() uint32 {
  341. n := sc.hs.MaxHeaderBytes
  342. if n <= 0 {
  343. n = http.DefaultMaxHeaderBytes
  344. }
  345. // http2's count is in a slightly different unit and includes 32 bytes per pair.
  346. // So, take the net/http.Server value and pad it up a bit, assuming 10 headers.
  347. const perFieldOverhead = 32 // per http2 spec
  348. const typicalHeaders = 10 // conservative
  349. return uint32(n + typicalHeaders*perFieldOverhead)
  350. }
  351. // requestParam is the state of the next request, initialized over
  352. // potentially several frames HEADERS + zero or more CONTINUATION
  353. // frames.
  354. type requestParam struct {
  355. // stream is non-nil if we're reading (HEADER or CONTINUATION)
  356. // frames for a request (but not DATA).
  357. stream *stream
  358. header http.Header
  359. method, path string
  360. scheme, authority string
  361. sawRegularHeader bool // saw a non-pseudo header already
  362. invalidHeader bool // an invalid header was seen
  363. headerListSize int64 // actually uint32, but easier math this way
  364. }
  365. // stream represents a stream. This is the minimal metadata needed by
  366. // the serve goroutine. Most of the actual stream state is owned by
  367. // the http.Handler's goroutine in the responseWriter. Because the
  368. // responseWriter's responseWriterState is recycled at the end of a
  369. // handler, this struct intentionally has no pointer to the
  370. // *responseWriter{,State} itself, as the Handler ending nils out the
  371. // responseWriter's state field.
  372. type stream struct {
  373. // immutable:
  374. id uint32
  375. body *pipe // non-nil if expecting DATA frames
  376. cw closeWaiter // closed wait stream transitions to closed state
  377. // owned by serverConn's serve loop:
  378. bodyBytes int64 // body bytes seen so far
  379. declBodyBytes int64 // or -1 if undeclared
  380. flow flow // limits writing from Handler to client
  381. inflow flow // what the client is allowed to POST/etc to us
  382. parent *stream // or nil
  383. weight uint8
  384. state streamState
  385. sentReset bool // only true once detached from streams map
  386. gotReset bool // only true once detacted from streams map
  387. }
  388. func (sc *serverConn) Framer() *Framer { return sc.framer }
  389. func (sc *serverConn) CloseConn() error { return sc.conn.Close() }
  390. func (sc *serverConn) Flush() error { return sc.bw.Flush() }
  391. func (sc *serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) {
  392. return sc.hpackEncoder, &sc.headerWriteBuf
  393. }
  394. func (sc *serverConn) state(streamID uint32) (streamState, *stream) {
  395. sc.serveG.check()
  396. // http://http2.github.io/http2-spec/#rfc.section.5.1
  397. if st, ok := sc.streams[streamID]; ok {
  398. return st.state, st
  399. }
  400. // "The first use of a new stream identifier implicitly closes all
  401. // streams in the "idle" state that might have been initiated by
  402. // that peer with a lower-valued stream identifier. For example, if
  403. // a client sends a HEADERS frame on stream 7 without ever sending a
  404. // frame on stream 5, then stream 5 transitions to the "closed"
  405. // state when the first frame for stream 7 is sent or received."
  406. if streamID <= sc.maxStreamID {
  407. return stateClosed, nil
  408. }
  409. return stateIdle, nil
  410. }
  411. // setConnState calls the net/http ConnState hook for this connection, if configured.
  412. // Note that the net/http package does StateNew and StateClosed for us.
  413. // There is currently no plan for StateHijacked or hijacking HTTP/2 connections.
  414. func (sc *serverConn) setConnState(state http.ConnState) {
  415. if sc.hs.ConnState != nil {
  416. sc.hs.ConnState(sc.conn, state)
  417. }
  418. }
  419. func (sc *serverConn) vlogf(format string, args ...interface{}) {
  420. if VerboseLogs {
  421. sc.logf(format, args...)
  422. }
  423. }
  424. func (sc *serverConn) logf(format string, args ...interface{}) {
  425. if lg := sc.hs.ErrorLog; lg != nil {
  426. lg.Printf(format, args...)
  427. } else {
  428. log.Printf(format, args...)
  429. }
  430. }
  431. func (sc *serverConn) condlogf(err error, format string, args ...interface{}) {
  432. if err == nil {
  433. return
  434. }
  435. str := err.Error()
  436. if err == io.EOF || strings.Contains(str, "use of closed network connection") {
  437. // Boring, expected errors.
  438. sc.vlogf(format, args...)
  439. } else {
  440. sc.logf(format, args...)
  441. }
  442. }
  443. func (sc *serverConn) onNewHeaderField(f hpack.HeaderField) {
  444. sc.serveG.check()
  445. sc.vlogf("got header field %+v", f)
  446. switch {
  447. case !validHeader(f.Name):
  448. sc.req.invalidHeader = true
  449. case strings.HasPrefix(f.Name, ":"):
  450. if sc.req.sawRegularHeader {
  451. sc.logf("pseudo-header after regular header")
  452. sc.req.invalidHeader = true
  453. return
  454. }
  455. var dst *string
  456. switch f.Name {
  457. case ":method":
  458. dst = &sc.req.method
  459. case ":path":
  460. dst = &sc.req.path
  461. case ":scheme":
  462. dst = &sc.req.scheme
  463. case ":authority":
  464. dst = &sc.req.authority
  465. default:
  466. // 8.1.2.1 Pseudo-Header Fields
  467. // "Endpoints MUST treat a request or response
  468. // that contains undefined or invalid
  469. // pseudo-header fields as malformed (Section
  470. // 8.1.2.6)."
  471. sc.logf("invalid pseudo-header %q", f.Name)
  472. sc.req.invalidHeader = true
  473. return
  474. }
  475. if *dst != "" {
  476. sc.logf("duplicate pseudo-header %q sent", f.Name)
  477. sc.req.invalidHeader = true
  478. return
  479. }
  480. *dst = f.Value
  481. default:
  482. sc.req.sawRegularHeader = true
  483. sc.req.header.Add(sc.canonicalHeader(f.Name), f.Value)
  484. const headerFieldOverhead = 32 // per spec
  485. sc.req.headerListSize += int64(len(f.Name)) + int64(len(f.Value)) + headerFieldOverhead
  486. if sc.req.headerListSize > int64(sc.maxHeaderListSize()) {
  487. sc.hpackDecoder.SetEmitEnabled(false)
  488. }
  489. }
  490. }
  491. func (sc *serverConn) canonicalHeader(v string) string {
  492. sc.serveG.check()
  493. cv, ok := commonCanonHeader[v]
  494. if ok {
  495. return cv
  496. }
  497. cv, ok = sc.canonHeader[v]
  498. if ok {
  499. return cv
  500. }
  501. if sc.canonHeader == nil {
  502. sc.canonHeader = make(map[string]string)
  503. }
  504. cv = http.CanonicalHeaderKey(v)
  505. sc.canonHeader[v] = cv
  506. return cv
  507. }
  508. type readFrameResult struct {
  509. f Frame // valid until readMore is called
  510. err error
  511. // readMore should be called once the consumer no longer needs or
  512. // retains f. After readMore, f is invalid and more frames can be
  513. // read.
  514. readMore func()
  515. }
  516. // readFrames is the loop that reads incoming frames.
  517. // It takes care to only read one frame at a time, blocking until the
  518. // consumer is done with the frame.
  519. // It's run on its own goroutine.
  520. func (sc *serverConn) readFrames() {
  521. gate := make(gate)
  522. for {
  523. f, err := sc.framer.ReadFrame()
  524. select {
  525. case sc.readFrameCh <- readFrameResult{f, err, gate.Done}:
  526. case <-sc.doneServing:
  527. return
  528. }
  529. select {
  530. case <-gate:
  531. case <-sc.doneServing:
  532. return
  533. }
  534. }
  535. }
  536. // frameWriteResult is the message passed from writeFrameAsync to the serve goroutine.
  537. type frameWriteResult struct {
  538. wm frameWriteMsg // what was written (or attempted)
  539. err error // result of the writeFrame call
  540. }
  541. // writeFrameAsync runs in its own goroutine and writes a single frame
  542. // and then reports when it's done.
  543. // At most one goroutine can be running writeFrameAsync at a time per
  544. // serverConn.
  545. func (sc *serverConn) writeFrameAsync(wm frameWriteMsg) {
  546. err := wm.write.writeFrame(sc)
  547. sc.wroteFrameCh <- frameWriteResult{wm, err}
  548. }
  549. func (sc *serverConn) closeAllStreamsOnConnClose() {
  550. sc.serveG.check()
  551. for _, st := range sc.streams {
  552. sc.closeStream(st, errClientDisconnected)
  553. }
  554. }
  555. func (sc *serverConn) stopShutdownTimer() {
  556. sc.serveG.check()
  557. if t := sc.shutdownTimer; t != nil {
  558. t.Stop()
  559. }
  560. }
  561. func (sc *serverConn) notePanic() {
  562. if testHookOnPanicMu != nil {
  563. testHookOnPanicMu.Lock()
  564. defer testHookOnPanicMu.Unlock()
  565. }
  566. if testHookOnPanic != nil {
  567. if e := recover(); e != nil {
  568. if testHookOnPanic(sc, e) {
  569. panic(e)
  570. }
  571. }
  572. }
  573. }
  574. func (sc *serverConn) serve() {
  575. sc.serveG.check()
  576. defer sc.notePanic()
  577. defer sc.conn.Close()
  578. defer sc.closeAllStreamsOnConnClose()
  579. defer sc.stopShutdownTimer()
  580. defer close(sc.doneServing) // unblocks handlers trying to send
  581. sc.vlogf("HTTP/2 connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
  582. sc.writeFrame(frameWriteMsg{
  583. write: writeSettings{
  584. {SettingMaxFrameSize, sc.srv.maxReadFrameSize()},
  585. {SettingMaxConcurrentStreams, sc.advMaxStreams},
  586. {SettingMaxHeaderListSize, sc.maxHeaderListSize()},
  587. // TODO: more actual settings, notably
  588. // SettingInitialWindowSize, but then we also
  589. // want to bump up the conn window size the
  590. // same amount here right after the settings
  591. },
  592. })
  593. sc.unackedSettings++
  594. if err := sc.readPreface(); err != nil {
  595. sc.condlogf(err, "error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
  596. return
  597. }
  598. // Now that we've got the preface, get us out of the
  599. // "StateNew" state. We can't go directly to idle, though.
  600. // Active means we read some data and anticipate a request. We'll
  601. // do another Active when we get a HEADERS frame.
  602. sc.setConnState(http.StateActive)
  603. sc.setConnState(http.StateIdle)
  604. go sc.readFrames() // closed by defer sc.conn.Close above
  605. settingsTimer := time.NewTimer(firstSettingsTimeout)
  606. loopNum := 0
  607. for {
  608. loopNum++
  609. select {
  610. case wm := <-sc.wantWriteFrameCh:
  611. sc.writeFrame(wm)
  612. case res := <-sc.wroteFrameCh:
  613. sc.wroteFrame(res)
  614. case res := <-sc.readFrameCh:
  615. if !sc.processFrameFromReader(res) {
  616. return
  617. }
  618. res.readMore()
  619. if settingsTimer.C != nil {
  620. settingsTimer.Stop()
  621. settingsTimer.C = nil
  622. }
  623. case m := <-sc.bodyReadCh:
  624. sc.noteBodyRead(m.st, m.n)
  625. case <-settingsTimer.C:
  626. sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
  627. return
  628. case <-sc.shutdownTimerCh:
  629. sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
  630. return
  631. case fn := <-sc.testHookCh:
  632. fn(loopNum)
  633. }
  634. }
  635. }
  636. // readPreface reads the ClientPreface greeting from the peer
  637. // or returns an error on timeout or an invalid greeting.
  638. func (sc *serverConn) readPreface() error {
  639. errc := make(chan error, 1)
  640. go func() {
  641. // Read the client preface
  642. buf := make([]byte, len(ClientPreface))
  643. if _, err := io.ReadFull(sc.conn, buf); err != nil {
  644. errc <- err
  645. } else if !bytes.Equal(buf, clientPreface) {
  646. errc <- fmt.Errorf("bogus greeting %q", buf)
  647. } else {
  648. errc <- nil
  649. }
  650. }()
  651. timer := time.NewTimer(prefaceTimeout) // TODO: configurable on *Server?
  652. defer timer.Stop()
  653. select {
  654. case <-timer.C:
  655. return errors.New("timeout waiting for client preface")
  656. case err := <-errc:
  657. if err == nil {
  658. sc.vlogf("client %v said hello", sc.conn.RemoteAddr())
  659. }
  660. return err
  661. }
  662. }
  663. var errChanPool = sync.Pool{
  664. New: func() interface{} { return make(chan error, 1) },
  665. }
  666. // writeDataFromHandler writes the data described in req to stream.id.
  667. //
  668. // The flow control currently happens in the Handler where it waits
  669. // for 1 or more bytes to be available to then write here. So at this
  670. // point we know that we have flow control. But this might have to
  671. // change when priority is implemented, so the serve goroutine knows
  672. // the total amount of bytes waiting to be sent and can can have more
  673. // scheduling decisions available.
  674. func (sc *serverConn) writeDataFromHandler(stream *stream, writeData *writeData) error {
  675. ch := errChanPool.Get().(chan error)
  676. err := sc.writeFrameFromHandler(frameWriteMsg{
  677. write: writeData,
  678. stream: stream,
  679. done: ch,
  680. })
  681. if err != nil {
  682. return err
  683. }
  684. select {
  685. case err = <-ch:
  686. case <-sc.doneServing:
  687. return errClientDisconnected
  688. case <-stream.cw:
  689. // If both ch and stream.cw were ready (as might
  690. // happen on the final Write after an http.Handler
  691. // ends), prefer the write result. Otherwise this
  692. // might just be us successfully closing the stream.
  693. // The writeFrameAsync and serve goroutines guarantee
  694. // that the ch send will happen before the stream.cw
  695. // close.
  696. select {
  697. case err = <-ch:
  698. default:
  699. return errStreamClosed
  700. }
  701. }
  702. errChanPool.Put(ch)
  703. return err
  704. }
  705. // writeFrameFromHandler sends wm to sc.wantWriteFrameCh, but aborts
  706. // if the connection has gone away.
  707. //
  708. // This must not be run from the serve goroutine itself, else it might
  709. // deadlock writing to sc.wantWriteFrameCh (which is only mildly
  710. // buffered and is read by serve itself). If you're on the serve
  711. // goroutine, call writeFrame instead.
  712. func (sc *serverConn) writeFrameFromHandler(wm frameWriteMsg) error {
  713. sc.serveG.checkNotOn() // NOT
  714. select {
  715. case sc.wantWriteFrameCh <- wm:
  716. return nil
  717. case <-sc.doneServing:
  718. // Serve loop is gone.
  719. // Client has closed their connection to the server.
  720. return errClientDisconnected
  721. }
  722. }
  723. // writeFrame schedules a frame to write and sends it if there's nothing
  724. // already being written.
  725. //
  726. // There is no pushback here (the serve goroutine never blocks). It's
  727. // the http.Handlers that block, waiting for their previous frames to
  728. // make it onto the wire
  729. //
  730. // If you're not on the serve goroutine, use writeFrameFromHandler instead.
  731. func (sc *serverConn) writeFrame(wm frameWriteMsg) {
  732. sc.serveG.check()
  733. sc.writeSched.add(wm)
  734. sc.scheduleFrameWrite()
  735. }
  736. // startFrameWrite starts a goroutine to write wm (in a separate
  737. // goroutine since that might block on the network), and updates the
  738. // serve goroutine's state about the world, updated from info in wm.
  739. func (sc *serverConn) startFrameWrite(wm frameWriteMsg) {
  740. sc.serveG.check()
  741. if sc.writingFrame {
  742. panic("internal error: can only be writing one frame at a time")
  743. }
  744. st := wm.stream
  745. if st != nil {
  746. switch st.state {
  747. case stateHalfClosedLocal:
  748. panic("internal error: attempt to send frame on half-closed-local stream")
  749. case stateClosed:
  750. if st.sentReset || st.gotReset {
  751. // Skip this frame.
  752. sc.scheduleFrameWrite()
  753. return
  754. }
  755. panic(fmt.Sprintf("internal error: attempt to send a write %v on a closed stream", wm))
  756. }
  757. }
  758. sc.writingFrame = true
  759. sc.needsFrameFlush = true
  760. go sc.writeFrameAsync(wm)
  761. }
  762. // wroteFrame is called on the serve goroutine with the result of
  763. // whatever happened on writeFrameAsync.
  764. func (sc *serverConn) wroteFrame(res frameWriteResult) {
  765. sc.serveG.check()
  766. if !sc.writingFrame {
  767. panic("internal error: expected to be already writing a frame")
  768. }
  769. sc.writingFrame = false
  770. wm := res.wm
  771. st := wm.stream
  772. closeStream := endsStream(wm.write)
  773. // Reply (if requested) to the blocked ServeHTTP goroutine.
  774. if ch := wm.done; ch != nil {
  775. select {
  776. case ch <- res.err:
  777. default:
  778. panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wm.write))
  779. }
  780. }
  781. wm.write = nil // prevent use (assume it's tainted after wm.done send)
  782. if closeStream {
  783. if st == nil {
  784. panic("internal error: expecting non-nil stream")
  785. }
  786. switch st.state {
  787. case stateOpen:
  788. // Here we would go to stateHalfClosedLocal in
  789. // theory, but since our handler is done and
  790. // the net/http package provides no mechanism
  791. // for finishing writing to a ResponseWriter
  792. // while still reading data (see possible TODO
  793. // at top of this file), we go into closed
  794. // state here anyway, after telling the peer
  795. // we're hanging up on them.
  796. st.state = stateHalfClosedLocal // won't last long, but necessary for closeStream via resetStream
  797. errCancel := StreamError{st.id, ErrCodeCancel}
  798. sc.resetStream(errCancel)
  799. case stateHalfClosedRemote:
  800. sc.closeStream(st, errHandlerComplete)
  801. }
  802. }
  803. sc.scheduleFrameWrite()
  804. }
  805. // scheduleFrameWrite tickles the frame writing scheduler.
  806. //
  807. // If a frame is already being written, nothing happens. This will be called again
  808. // when the frame is done being written.
  809. //
  810. // If a frame isn't being written we need to send one, the best frame
  811. // to send is selected, preferring first things that aren't
  812. // stream-specific (e.g. ACKing settings), and then finding the
  813. // highest priority stream.
  814. //
  815. // If a frame isn't being written and there's nothing else to send, we
  816. // flush the write buffer.
  817. func (sc *serverConn) scheduleFrameWrite() {
  818. sc.serveG.check()
  819. if sc.writingFrame {
  820. return
  821. }
  822. if sc.needToSendGoAway {
  823. sc.needToSendGoAway = false
  824. sc.startFrameWrite(frameWriteMsg{
  825. write: &writeGoAway{
  826. maxStreamID: sc.maxStreamID,
  827. code: sc.goAwayCode,
  828. },
  829. })
  830. return
  831. }
  832. if sc.needToSendSettingsAck {
  833. sc.needToSendSettingsAck = false
  834. sc.startFrameWrite(frameWriteMsg{write: writeSettingsAck{}})
  835. return
  836. }
  837. if !sc.inGoAway {
  838. if wm, ok := sc.writeSched.take(); ok {
  839. sc.startFrameWrite(wm)
  840. return
  841. }
  842. }
  843. if sc.needsFrameFlush {
  844. sc.startFrameWrite(frameWriteMsg{write: flushFrameWriter{}})
  845. sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
  846. return
  847. }
  848. }
  849. func (sc *serverConn) goAway(code ErrCode) {
  850. sc.serveG.check()
  851. if sc.inGoAway {
  852. return
  853. }
  854. if code != ErrCodeNo {
  855. sc.shutDownIn(250 * time.Millisecond)
  856. } else {
  857. // TODO: configurable
  858. sc.shutDownIn(1 * time.Second)
  859. }
  860. sc.inGoAway = true
  861. sc.needToSendGoAway = true
  862. sc.goAwayCode = code
  863. sc.scheduleFrameWrite()
  864. }
  865. func (sc *serverConn) shutDownIn(d time.Duration) {
  866. sc.serveG.check()
  867. sc.shutdownTimer = time.NewTimer(d)
  868. sc.shutdownTimerCh = sc.shutdownTimer.C
  869. }
  870. func (sc *serverConn) resetStream(se StreamError) {
  871. sc.serveG.check()
  872. sc.writeFrame(frameWriteMsg{write: se})
  873. if st, ok := sc.streams[se.StreamID]; ok {
  874. st.sentReset = true
  875. sc.closeStream(st, se)
  876. }
  877. }
  878. // curHeaderStreamID returns the stream ID of the header block we're
  879. // currently in the middle of reading. If this returns non-zero, the
  880. // next frame must be a CONTINUATION with this stream id.
  881. func (sc *serverConn) curHeaderStreamID() uint32 {
  882. sc.serveG.check()
  883. st := sc.req.stream
  884. if st == nil {
  885. return 0
  886. }
  887. return st.id
  888. }
  889. // processFrameFromReader processes the serve loop's read from readFrameCh from the
  890. // frame-reading goroutine.
  891. // processFrameFromReader returns whether the connection should be kept open.
  892. func (sc *serverConn) processFrameFromReader(res readFrameResult) bool {
  893. sc.serveG.check()
  894. err := res.err
  895. if err != nil {
  896. if err == ErrFrameTooLarge {
  897. sc.goAway(ErrCodeFrameSize)
  898. return true // goAway will close the loop
  899. }
  900. clientGone := err == io.EOF || strings.Contains(err.Error(), "use of closed network connection")
  901. if clientGone {
  902. // TODO: could we also get into this state if
  903. // the peer does a half close
  904. // (e.g. CloseWrite) because they're done
  905. // sending frames but they're still wanting
  906. // our open replies? Investigate.
  907. // TODO: add CloseWrite to crypto/tls.Conn first
  908. // so we have a way to test this? I suppose
  909. // just for testing we could have a non-TLS mode.
  910. return false
  911. }
  912. } else {
  913. f := res.f
  914. sc.vlogf("got %v: %#v", f.Header(), f)
  915. err = sc.processFrame(f)
  916. if err == nil {
  917. return true
  918. }
  919. }
  920. switch ev := err.(type) {
  921. case StreamError:
  922. sc.resetStream(ev)
  923. return true
  924. case goAwayFlowError:
  925. sc.goAway(ErrCodeFlowControl)
  926. return true
  927. case ConnectionError:
  928. sc.logf("%v: %v", sc.conn.RemoteAddr(), ev)
  929. sc.goAway(ErrCode(ev))
  930. return true // goAway will handle shutdown
  931. default:
  932. if res.err != nil {
  933. sc.logf("disconnecting; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
  934. } else {
  935. sc.logf("disconnection due to other error: %v", err)
  936. }
  937. return false
  938. }
  939. }
  940. func (sc *serverConn) processFrame(f Frame) error {
  941. sc.serveG.check()
  942. // First frame received must be SETTINGS.
  943. if !sc.sawFirstSettings {
  944. if _, ok := f.(*SettingsFrame); !ok {
  945. return ConnectionError(ErrCodeProtocol)
  946. }
  947. sc.sawFirstSettings = true
  948. }
  949. if s := sc.curHeaderStreamID(); s != 0 {
  950. if cf, ok := f.(*ContinuationFrame); !ok {
  951. return ConnectionError(ErrCodeProtocol)
  952. } else if cf.Header().StreamID != s {
  953. return ConnectionError(ErrCodeProtocol)
  954. }
  955. }
  956. switch f := f.(type) {
  957. case *SettingsFrame:
  958. return sc.processSettings(f)
  959. case *HeadersFrame:
  960. return sc.processHeaders(f)
  961. case *ContinuationFrame:
  962. return sc.processContinuation(f)
  963. case *WindowUpdateFrame:
  964. return sc.processWindowUpdate(f)
  965. case *PingFrame:
  966. return sc.processPing(f)
  967. case *DataFrame:
  968. return sc.processData(f)
  969. case *RSTStreamFrame:
  970. return sc.processResetStream(f)
  971. case *PriorityFrame:
  972. return sc.processPriority(f)
  973. case *PushPromiseFrame:
  974. // A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE
  975. // frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  976. return ConnectionError(ErrCodeProtocol)
  977. default:
  978. sc.vlogf("Ignoring frame: %v", f.Header())
  979. return nil
  980. }
  981. }
  982. func (sc *serverConn) processPing(f *PingFrame) error {
  983. sc.serveG.check()
  984. if f.Flags.Has(FlagSettingsAck) {
  985. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  986. // containing this flag."
  987. return nil
  988. }
  989. if f.StreamID != 0 {
  990. // "PING frames are not associated with any individual
  991. // stream. If a PING frame is received with a stream
  992. // identifier field value other than 0x0, the recipient MUST
  993. // respond with a connection error (Section 5.4.1) of type
  994. // PROTOCOL_ERROR."
  995. return ConnectionError(ErrCodeProtocol)
  996. }
  997. sc.writeFrame(frameWriteMsg{write: writePingAck{f}})
  998. return nil
  999. }
  1000. func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  1001. sc.serveG.check()
  1002. switch {
  1003. case f.StreamID != 0: // stream-level flow control
  1004. st := sc.streams[f.StreamID]
  1005. if st == nil {
  1006. // "WINDOW_UPDATE can be sent by a peer that has sent a
  1007. // frame bearing the END_STREAM flag. This means that a
  1008. // receiver could receive a WINDOW_UPDATE frame on a "half
  1009. // closed (remote)" or "closed" stream. A receiver MUST
  1010. // NOT treat this as an error, see Section 5.1."
  1011. return nil
  1012. }
  1013. if !st.flow.add(int32(f.Increment)) {
  1014. return StreamError{f.StreamID, ErrCodeFlowControl}
  1015. }
  1016. default: // connection-level flow control
  1017. if !sc.flow.add(int32(f.Increment)) {
  1018. return goAwayFlowError{}
  1019. }
  1020. }
  1021. sc.scheduleFrameWrite()
  1022. return nil
  1023. }
  1024. func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
  1025. sc.serveG.check()
  1026. state, st := sc.state(f.StreamID)
  1027. if state == stateIdle {
  1028. // 6.4 "RST_STREAM frames MUST NOT be sent for a
  1029. // stream in the "idle" state. If a RST_STREAM frame
  1030. // identifying an idle stream is received, the
  1031. // recipient MUST treat this as a connection error
  1032. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1033. return ConnectionError(ErrCodeProtocol)
  1034. }
  1035. if st != nil {
  1036. st.gotReset = true
  1037. sc.closeStream(st, StreamError{f.StreamID, f.ErrCode})
  1038. }
  1039. return nil
  1040. }
  1041. func (sc *serverConn) closeStream(st *stream, err error) {
  1042. sc.serveG.check()
  1043. if st.state == stateIdle || st.state == stateClosed {
  1044. panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
  1045. }
  1046. st.state = stateClosed
  1047. sc.curOpenStreams--
  1048. if sc.curOpenStreams == 0 {
  1049. sc.setConnState(http.StateIdle)
  1050. }
  1051. delete(sc.streams, st.id)
  1052. if p := st.body; p != nil {
  1053. p.CloseWithError(err)
  1054. }
  1055. st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc
  1056. sc.writeSched.forgetStream(st.id)
  1057. }
  1058. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  1059. sc.serveG.check()
  1060. if f.IsAck() {
  1061. sc.unackedSettings--
  1062. if sc.unackedSettings < 0 {
  1063. // Why is the peer ACKing settings we never sent?
  1064. // The spec doesn't mention this case, but
  1065. // hang up on them anyway.
  1066. return ConnectionError(ErrCodeProtocol)
  1067. }
  1068. return nil
  1069. }
  1070. if err := f.ForeachSetting(sc.processSetting); err != nil {
  1071. return err
  1072. }
  1073. sc.needToSendSettingsAck = true
  1074. sc.scheduleFrameWrite()
  1075. return nil
  1076. }
  1077. func (sc *serverConn) processSetting(s Setting) error {
  1078. sc.serveG.check()
  1079. if err := s.Valid(); err != nil {
  1080. return err
  1081. }
  1082. sc.vlogf("processing setting %v", s)
  1083. switch s.ID {
  1084. case SettingHeaderTableSize:
  1085. sc.headerTableSize = s.Val
  1086. sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
  1087. case SettingEnablePush:
  1088. sc.pushEnabled = s.Val != 0
  1089. case SettingMaxConcurrentStreams:
  1090. sc.clientMaxStreams = s.Val
  1091. case SettingInitialWindowSize:
  1092. return sc.processSettingInitialWindowSize(s.Val)
  1093. case SettingMaxFrameSize:
  1094. sc.writeSched.maxFrameSize = s.Val
  1095. case SettingMaxHeaderListSize:
  1096. sc.peerMaxHeaderListSize = s.Val
  1097. default:
  1098. // Unknown setting: "An endpoint that receives a SETTINGS
  1099. // frame with any unknown or unsupported identifier MUST
  1100. // ignore that setting."
  1101. }
  1102. return nil
  1103. }
  1104. func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  1105. sc.serveG.check()
  1106. // Note: val already validated to be within range by
  1107. // processSetting's Valid call.
  1108. // "A SETTINGS frame can alter the initial flow control window
  1109. // size for all current streams. When the value of
  1110. // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  1111. // adjust the size of all stream flow control windows that it
  1112. // maintains by the difference between the new value and the
  1113. // old value."
  1114. old := sc.initialWindowSize
  1115. sc.initialWindowSize = int32(val)
  1116. growth := sc.initialWindowSize - old // may be negative
  1117. for _, st := range sc.streams {
  1118. if !st.flow.add(growth) {
  1119. // 6.9.2 Initial Flow Control Window Size
  1120. // "An endpoint MUST treat a change to
  1121. // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  1122. // control window to exceed the maximum size as a
  1123. // connection error (Section 5.4.1) of type
  1124. // FLOW_CONTROL_ERROR."
  1125. return ConnectionError(ErrCodeFlowControl)
  1126. }
  1127. }
  1128. return nil
  1129. }
  1130. func (sc *serverConn) processData(f *DataFrame) error {
  1131. sc.serveG.check()
  1132. // "If a DATA frame is received whose stream is not in "open"
  1133. // or "half closed (local)" state, the recipient MUST respond
  1134. // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  1135. id := f.Header().StreamID
  1136. st, ok := sc.streams[id]
  1137. if !ok || st.state != stateOpen {
  1138. // This includes sending a RST_STREAM if the stream is
  1139. // in stateHalfClosedLocal (which currently means that
  1140. // the http.Handler returned, so it's done reading &
  1141. // done writing). Try to stop the client from sending
  1142. // more DATA.
  1143. return StreamError{id, ErrCodeStreamClosed}
  1144. }
  1145. if st.body == nil {
  1146. panic("internal error: should have a body in this state")
  1147. }
  1148. data := f.Data()
  1149. // Sender sending more than they'd declared?
  1150. if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  1151. st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  1152. return StreamError{id, ErrCodeStreamClosed}
  1153. }
  1154. if len(data) > 0 {
  1155. // Check whether the client has flow control quota.
  1156. if int(st.inflow.available()) < len(data) {
  1157. return StreamError{id, ErrCodeFlowControl}
  1158. }
  1159. st.inflow.take(int32(len(data)))
  1160. wrote, err := st.body.Write(data)
  1161. if err != nil {
  1162. return StreamError{id, ErrCodeStreamClosed}
  1163. }
  1164. if wrote != len(data) {
  1165. panic("internal error: bad Writer")
  1166. }
  1167. st.bodyBytes += int64(len(data))
  1168. }
  1169. if f.StreamEnded() {
  1170. if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  1171. st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
  1172. st.declBodyBytes, st.bodyBytes))
  1173. } else {
  1174. st.body.CloseWithError(io.EOF)
  1175. }
  1176. st.state = stateHalfClosedRemote
  1177. }
  1178. return nil
  1179. }
  1180. func (sc *serverConn) processHeaders(f *HeadersFrame) error {
  1181. sc.serveG.check()
  1182. id := f.Header().StreamID
  1183. if sc.inGoAway {
  1184. // Ignore.
  1185. return nil
  1186. }
  1187. // http://http2.github.io/http2-spec/#rfc.section.5.1.1
  1188. if id%2 != 1 || id <= sc.maxStreamID || sc.req.stream != nil {
  1189. // Streams initiated by a client MUST use odd-numbered
  1190. // stream identifiers. [...] The identifier of a newly
  1191. // established stream MUST be numerically greater than all
  1192. // streams that the initiating endpoint has opened or
  1193. // reserved. [...] An endpoint that receives an unexpected
  1194. // stream identifier MUST respond with a connection error
  1195. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1196. return ConnectionError(ErrCodeProtocol)
  1197. }
  1198. if id > sc.maxStreamID {
  1199. sc.maxStreamID = id
  1200. }
  1201. st := &stream{
  1202. id: id,
  1203. state: stateOpen,
  1204. }
  1205. if f.StreamEnded() {
  1206. st.state = stateHalfClosedRemote
  1207. }
  1208. st.cw.Init()
  1209. st.flow.conn = &sc.flow // link to conn-level counter
  1210. st.flow.add(sc.initialWindowSize)
  1211. st.inflow.conn = &sc.inflow // link to conn-level counter
  1212. st.inflow.add(initialWindowSize) // TODO: update this when we send a higher initial window size in the initial settings
  1213. sc.streams[id] = st
  1214. if f.HasPriority() {
  1215. adjustStreamPriority(sc.streams, st.id, f.Priority)
  1216. }
  1217. sc.curOpenStreams++
  1218. if sc.curOpenStreams == 1 {
  1219. sc.setConnState(http.StateActive)
  1220. }
  1221. sc.req = requestParam{
  1222. stream: st,
  1223. header: make(http.Header),
  1224. }
  1225. sc.hpackDecoder.SetEmitEnabled(true)
  1226. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  1227. }
  1228. func (sc *serverConn) processContinuation(f *ContinuationFrame) error {
  1229. sc.serveG.check()
  1230. st := sc.streams[f.Header().StreamID]
  1231. if st == nil || sc.curHeaderStreamID() != st.id {
  1232. return ConnectionError(ErrCodeProtocol)
  1233. }
  1234. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  1235. }
  1236. func (sc *serverConn) processHeaderBlockFragment(st *stream, frag []byte, end bool) error {
  1237. sc.serveG.check()
  1238. if _, err := sc.hpackDecoder.Write(frag); err != nil {
  1239. return ConnectionError(ErrCodeCompression)
  1240. }
  1241. if !end {
  1242. return nil
  1243. }
  1244. if err := sc.hpackDecoder.Close(); err != nil {
  1245. return ConnectionError(ErrCodeCompression)
  1246. }
  1247. defer sc.resetPendingRequest()
  1248. if sc.curOpenStreams > sc.advMaxStreams {
  1249. // "Endpoints MUST NOT exceed the limit set by their
  1250. // peer. An endpoint that receives a HEADERS frame
  1251. // that causes their advertised concurrent stream
  1252. // limit to be exceeded MUST treat this as a stream
  1253. // error (Section 5.4.2) of type PROTOCOL_ERROR or
  1254. // REFUSED_STREAM."
  1255. if sc.unackedSettings == 0 {
  1256. // They should know better.
  1257. return StreamError{st.id, ErrCodeProtocol}
  1258. }
  1259. // Assume it's a network race, where they just haven't
  1260. // received our last SETTINGS update. But actually
  1261. // this can't happen yet, because we don't yet provide
  1262. // a way for users to adjust server parameters at
  1263. // runtime.
  1264. return StreamError{st.id, ErrCodeRefusedStream}
  1265. }
  1266. rw, req, err := sc.newWriterAndRequest()
  1267. if err != nil {
  1268. return err
  1269. }
  1270. st.body = req.Body.(*requestBody).pipe // may be nil
  1271. st.declBodyBytes = req.ContentLength
  1272. handler := sc.handler.ServeHTTP
  1273. if !sc.hpackDecoder.EmitEnabled() {
  1274. // Their header list was too long. Send a 431 error.
  1275. handler = handleHeaderListTooLong
  1276. }
  1277. go sc.runHandler(rw, req, handler)
  1278. return nil
  1279. }
  1280. func (sc *serverConn) processPriority(f *PriorityFrame) error {
  1281. adjustStreamPriority(sc.streams, f.StreamID, f.PriorityParam)
  1282. return nil
  1283. }
  1284. func adjustStreamPriority(streams map[uint32]*stream, streamID uint32, priority PriorityParam) {
  1285. st, ok := streams[streamID]
  1286. if !ok {
  1287. // TODO: not quite correct (this streamID might
  1288. // already exist in the dep tree, but be closed), but
  1289. // close enough for now.
  1290. return
  1291. }
  1292. st.weight = priority.Weight
  1293. parent := streams[priority.StreamDep] // might be nil
  1294. if parent == st {
  1295. // if client tries to set this stream to be the parent of itself
  1296. // ignore and keep going
  1297. return
  1298. }
  1299. // section 5.3.3: If a stream is made dependent on one of its
  1300. // own dependencies, the formerly dependent stream is first
  1301. // moved to be dependent on the reprioritized stream's previous
  1302. // parent. The moved dependency retains its weight.
  1303. for piter := parent; piter != nil; piter = piter.parent {
  1304. if piter == st {
  1305. parent.parent = st.parent
  1306. break
  1307. }
  1308. }
  1309. st.parent = parent
  1310. if priority.Exclusive && (st.parent != nil || priority.StreamDep == 0) {
  1311. for _, openStream := range streams {
  1312. if openStream != st && openStream.parent == st.parent {
  1313. openStream.parent = st
  1314. }
  1315. }
  1316. }
  1317. }
  1318. // resetPendingRequest zeros out all state related to a HEADERS frame
  1319. // and its zero or more CONTINUATION frames sent to start a new
  1320. // request.
  1321. func (sc *serverConn) resetPendingRequest() {
  1322. sc.serveG.check()
  1323. sc.req = requestParam{}
  1324. }
  1325. func (sc *serverConn) newWriterAndRequest() (*responseWriter, *http.Request, error) {
  1326. sc.serveG.check()
  1327. rp := &sc.req
  1328. if rp.invalidHeader || rp.method == "" || rp.path == "" ||
  1329. (rp.scheme != "https" && rp.scheme != "http") {
  1330. // See 8.1.2.6 Malformed Requests and Responses:
  1331. //
  1332. // Malformed requests or responses that are detected
  1333. // MUST be treated as a stream error (Section 5.4.2)
  1334. // of type PROTOCOL_ERROR."
  1335. //
  1336. // 8.1.2.3 Request Pseudo-Header Fields
  1337. // "All HTTP/2 requests MUST include exactly one valid
  1338. // value for the :method, :scheme, and :path
  1339. // pseudo-header fields"
  1340. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1341. }
  1342. var tlsState *tls.ConnectionState // nil if not scheme https
  1343. if rp.scheme == "https" {
  1344. tlsState = sc.tlsState
  1345. }
  1346. authority := rp.authority
  1347. if authority == "" {
  1348. authority = rp.header.Get("Host")
  1349. }
  1350. needsContinue := rp.header.Get("Expect") == "100-continue"
  1351. if needsContinue {
  1352. rp.header.Del("Expect")
  1353. }
  1354. // Merge Cookie headers into one "; "-delimited value.
  1355. if cookies := rp.header["Cookie"]; len(cookies) > 1 {
  1356. rp.header.Set("Cookie", strings.Join(cookies, "; "))
  1357. }
  1358. bodyOpen := rp.stream.state == stateOpen
  1359. body := &requestBody{
  1360. conn: sc,
  1361. stream: rp.stream,
  1362. needsContinue: needsContinue,
  1363. }
  1364. // TODO: handle asterisk '*' requests + test
  1365. url, err := url.ParseRequestURI(rp.path)
  1366. if err != nil {
  1367. // TODO: find the right error code?
  1368. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1369. }
  1370. req := &http.Request{
  1371. Method: rp.method,
  1372. URL: url,
  1373. RemoteAddr: sc.remoteAddrStr,
  1374. Header: rp.header,
  1375. RequestURI: rp.path,
  1376. Proto: "HTTP/2.0",
  1377. ProtoMajor: 2,
  1378. ProtoMinor: 0,
  1379. TLS: tlsState,
  1380. Host: authority,
  1381. Body: body,
  1382. }
  1383. if bodyOpen {
  1384. body.pipe = &pipe{
  1385. b: &fixedBuffer{buf: make([]byte, initialWindowSize)}, // TODO: share/remove XXX
  1386. }
  1387. if vv, ok := rp.header["Content-Length"]; ok {
  1388. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  1389. } else {
  1390. req.ContentLength = -1
  1391. }
  1392. }
  1393. rws := responseWriterStatePool.Get().(*responseWriterState)
  1394. bwSave := rws.bw
  1395. *rws = responseWriterState{} // zero all the fields
  1396. rws.conn = sc
  1397. rws.bw = bwSave
  1398. rws.bw.Reset(chunkWriter{rws})
  1399. rws.stream = rp.stream
  1400. rws.req = req
  1401. rws.body = body
  1402. rw := &responseWriter{rws: rws}
  1403. return rw, req, nil
  1404. }
  1405. // Run on its own goroutine.
  1406. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) {
  1407. defer rw.handlerDone()
  1408. // TODO: catch panics like net/http.Server
  1409. handler(rw, req)
  1410. }
  1411. func handleHeaderListTooLong(w http.ResponseWriter, r *http.Request) {
  1412. // 10.5.1 Limits on Header Block Size:
  1413. // .. "A server that receives a larger header block than it is
  1414. // willing to handle can send an HTTP 431 (Request Header Fields Too
  1415. // Large) status code"
  1416. const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+
  1417. w.WriteHeader(statusRequestHeaderFieldsTooLarge)
  1418. io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
  1419. }
  1420. // called from handler goroutines.
  1421. // h may be nil.
  1422. func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error {
  1423. sc.serveG.checkNotOn() // NOT on
  1424. var errc chan error
  1425. if headerData.h != nil {
  1426. // If there's a header map (which we don't own), so we have to block on
  1427. // waiting for this frame to be written, so an http.Flush mid-handler
  1428. // writes out the correct value of keys, before a handler later potentially
  1429. // mutates it.
  1430. errc = errChanPool.Get().(chan error)
  1431. }
  1432. if err := sc.writeFrameFromHandler(frameWriteMsg{
  1433. write: headerData,
  1434. stream: st,
  1435. done: errc,
  1436. }); err != nil {
  1437. return err
  1438. }
  1439. if errc != nil {
  1440. select {
  1441. case err := <-errc:
  1442. errChanPool.Put(errc)
  1443. return err
  1444. case <-sc.doneServing:
  1445. return errClientDisconnected
  1446. case <-st.cw:
  1447. return errStreamClosed
  1448. }
  1449. }
  1450. return nil
  1451. }
  1452. // called from handler goroutines.
  1453. func (sc *serverConn) write100ContinueHeaders(st *stream) {
  1454. sc.writeFrameFromHandler(frameWriteMsg{
  1455. write: write100ContinueHeadersFrame{st.id},
  1456. stream: st,
  1457. })
  1458. }
  1459. // A bodyReadMsg tells the server loop that the http.Handler read n
  1460. // bytes of the DATA from the client on the given stream.
  1461. type bodyReadMsg struct {
  1462. st *stream
  1463. n int
  1464. }
  1465. // called from handler goroutines.
  1466. // Notes that the handler for the given stream ID read n bytes of its body
  1467. // and schedules flow control tokens to be sent.
  1468. func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int) {
  1469. sc.serveG.checkNotOn() // NOT on
  1470. sc.bodyReadCh <- bodyReadMsg{st, n}
  1471. }
  1472. func (sc *serverConn) noteBodyRead(st *stream, n int) {
  1473. sc.serveG.check()
  1474. sc.sendWindowUpdate(nil, n) // conn-level
  1475. if st.state != stateHalfClosedRemote && st.state != stateClosed {
  1476. // Don't send this WINDOW_UPDATE if the stream is closed
  1477. // remotely.
  1478. sc.sendWindowUpdate(st, n)
  1479. }
  1480. }
  1481. // st may be nil for conn-level
  1482. func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
  1483. sc.serveG.check()
  1484. // "The legal range for the increment to the flow control
  1485. // window is 1 to 2^31-1 (2,147,483,647) octets."
  1486. // A Go Read call on 64-bit machines could in theory read
  1487. // a larger Read than this. Very unlikely, but we handle it here
  1488. // rather than elsewhere for now.
  1489. const maxUint31 = 1<<31 - 1
  1490. for n >= maxUint31 {
  1491. sc.sendWindowUpdate32(st, maxUint31)
  1492. n -= maxUint31
  1493. }
  1494. sc.sendWindowUpdate32(st, int32(n))
  1495. }
  1496. // st may be nil for conn-level
  1497. func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) {
  1498. sc.serveG.check()
  1499. if n == 0 {
  1500. return
  1501. }
  1502. if n < 0 {
  1503. panic("negative update")
  1504. }
  1505. var streamID uint32
  1506. if st != nil {
  1507. streamID = st.id
  1508. }
  1509. sc.writeFrame(frameWriteMsg{
  1510. write: writeWindowUpdate{streamID: streamID, n: uint32(n)},
  1511. stream: st,
  1512. })
  1513. var ok bool
  1514. if st == nil {
  1515. ok = sc.inflow.add(n)
  1516. } else {
  1517. ok = st.inflow.add(n)
  1518. }
  1519. if !ok {
  1520. panic("internal error; sent too many window updates without decrements?")
  1521. }
  1522. }
  1523. type requestBody struct {
  1524. stream *stream
  1525. conn *serverConn
  1526. closed bool
  1527. pipe *pipe // non-nil if we have a HTTP entity message body
  1528. needsContinue bool // need to send a 100-continue
  1529. }
  1530. func (b *requestBody) Close() error {
  1531. if b.pipe != nil {
  1532. b.pipe.CloseWithError(errClosedBody)
  1533. }
  1534. b.closed = true
  1535. return nil
  1536. }
  1537. func (b *requestBody) Read(p []byte) (n int, err error) {
  1538. if b.needsContinue {
  1539. b.needsContinue = false
  1540. b.conn.write100ContinueHeaders(b.stream)
  1541. }
  1542. if b.pipe == nil {
  1543. return 0, io.EOF
  1544. }
  1545. n, err = b.pipe.Read(p)
  1546. if n > 0 {
  1547. b.conn.noteBodyReadFromHandler(b.stream, n)
  1548. }
  1549. return
  1550. }
  1551. // responseWriter is the http.ResponseWriter implementation. It's
  1552. // intentionally small (1 pointer wide) to minimize garbage. The
  1553. // responseWriterState pointer inside is zeroed at the end of a
  1554. // request (in handlerDone) and calls on the responseWriter thereafter
  1555. // simply crash (caller's mistake), but the much larger responseWriterState
  1556. // and buffers are reused between multiple requests.
  1557. type responseWriter struct {
  1558. rws *responseWriterState
  1559. }
  1560. // Optional http.ResponseWriter interfaces implemented.
  1561. var (
  1562. _ http.CloseNotifier = (*responseWriter)(nil)
  1563. _ http.Flusher = (*responseWriter)(nil)
  1564. _ stringWriter = (*responseWriter)(nil)
  1565. )
  1566. type responseWriterState struct {
  1567. // immutable within a request:
  1568. stream *stream
  1569. req *http.Request
  1570. body *requestBody // to close at end of request, if DATA frames didn't
  1571. conn *serverConn
  1572. // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
  1573. bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
  1574. // mutated by http.Handler goroutine:
  1575. handlerHeader http.Header // nil until called
  1576. snapHeader http.Header // snapshot of handlerHeader at WriteHeader time
  1577. status int // status code passed to WriteHeader
  1578. wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
  1579. sentHeader bool // have we sent the header frame?
  1580. handlerDone bool // handler has finished
  1581. curWrite writeData
  1582. closeNotifierMu sync.Mutex // guards closeNotifierCh
  1583. closeNotifierCh chan bool // nil until first used
  1584. }
  1585. type chunkWriter struct{ rws *responseWriterState }
  1586. func (cw chunkWriter) Write(p []byte) (n int, err error) { return cw.rws.writeChunk(p) }
  1587. // writeChunk writes chunks from the bufio.Writer. But because
  1588. // bufio.Writer may bypass its chunking, sometimes p may be
  1589. // arbitrarily large.
  1590. //
  1591. // writeChunk is also responsible (on the first chunk) for sending the
  1592. // HEADER response.
  1593. func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
  1594. if !rws.wroteHeader {
  1595. rws.writeHeader(200)
  1596. }
  1597. if !rws.sentHeader {
  1598. rws.sentHeader = true
  1599. var ctype, clen string // implicit ones, if we can calculate it
  1600. if rws.handlerDone && rws.snapHeader.Get("Content-Length") == "" {
  1601. clen = strconv.Itoa(len(p))
  1602. }
  1603. if rws.snapHeader.Get("Content-Type") == "" {
  1604. ctype = http.DetectContentType(p)
  1605. }
  1606. endStream := rws.handlerDone && len(p) == 0
  1607. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  1608. streamID: rws.stream.id,
  1609. httpResCode: rws.status,
  1610. h: rws.snapHeader,
  1611. endStream: endStream,
  1612. contentType: ctype,
  1613. contentLength: clen,
  1614. })
  1615. if err != nil {
  1616. return 0, err
  1617. }
  1618. if endStream {
  1619. return 0, nil
  1620. }
  1621. }
  1622. if len(p) == 0 && !rws.handlerDone {
  1623. return 0, nil
  1624. }
  1625. // Reuse curWrite (which as a pointer fits into the
  1626. // 'writeFramer' interface value) for each write to avoid an
  1627. // allocation per write.
  1628. curWrite := &rws.curWrite
  1629. curWrite.streamID = rws.stream.id
  1630. curWrite.p = p
  1631. curWrite.endStream = rws.handlerDone
  1632. if err := rws.conn.writeDataFromHandler(rws.stream, curWrite); err != nil {
  1633. return 0, err
  1634. }
  1635. return len(p), nil
  1636. }
  1637. func (w *responseWriter) Flush() {
  1638. rws := w.rws
  1639. if rws == nil {
  1640. panic("Header called after Handler finished")
  1641. }
  1642. if rws.bw.Buffered() > 0 {
  1643. if err := rws.bw.Flush(); err != nil {
  1644. // Ignore the error. The frame writer already knows.
  1645. return
  1646. }
  1647. } else {
  1648. // The bufio.Writer won't call chunkWriter.Write
  1649. // (writeChunk with zero bytes, so we have to do it
  1650. // ourselves to force the HTTP response header and/or
  1651. // final DATA frame (with END_STREAM) to be sent.
  1652. rws.writeChunk(nil)
  1653. }
  1654. }
  1655. func (w *responseWriter) CloseNotify() <-chan bool {
  1656. rws := w.rws
  1657. if rws == nil {
  1658. panic("CloseNotify called after Handler finished")
  1659. }
  1660. rws.closeNotifierMu.Lock()
  1661. ch := rws.closeNotifierCh
  1662. if ch == nil {
  1663. ch = make(chan bool, 1)
  1664. rws.closeNotifierCh = ch
  1665. go func() {
  1666. rws.stream.cw.Wait() // wait for close
  1667. ch <- true
  1668. }()
  1669. }
  1670. rws.closeNotifierMu.Unlock()
  1671. return ch
  1672. }
  1673. func (w *responseWriter) Header() http.Header {
  1674. rws := w.rws
  1675. if rws == nil {
  1676. panic("Header called after Handler finished")
  1677. }
  1678. if rws.handlerHeader == nil {
  1679. rws.handlerHeader = make(http.Header)
  1680. }
  1681. return rws.handlerHeader
  1682. }
  1683. func (w *responseWriter) WriteHeader(code int) {
  1684. rws := w.rws
  1685. if rws == nil {
  1686. panic("WriteHeader called after Handler finished")
  1687. }
  1688. rws.writeHeader(code)
  1689. }
  1690. func (rws *responseWriterState) writeHeader(code int) {
  1691. if !rws.wroteHeader {
  1692. rws.wroteHeader = true
  1693. rws.status = code
  1694. if len(rws.handlerHeader) > 0 {
  1695. rws.snapHeader = cloneHeader(rws.handlerHeader)
  1696. }
  1697. }
  1698. }
  1699. func cloneHeader(h http.Header) http.Header {
  1700. h2 := make(http.Header, len(h))
  1701. for k, vv := range h {
  1702. vv2 := make([]string, len(vv))
  1703. copy(vv2, vv)
  1704. h2[k] = vv2
  1705. }
  1706. return h2
  1707. }
  1708. // The Life Of A Write is like this:
  1709. //
  1710. // * Handler calls w.Write or w.WriteString ->
  1711. // * -> rws.bw (*bufio.Writer) ->
  1712. // * (Handler migth call Flush)
  1713. // * -> chunkWriter{rws}
  1714. // * -> responseWriterState.writeChunk(p []byte)
  1715. // * -> responseWriterState.writeChunk (most of the magic; see comment there)
  1716. func (w *responseWriter) Write(p []byte) (n int, err error) {
  1717. return w.write(len(p), p, "")
  1718. }
  1719. func (w *responseWriter) WriteString(s string) (n int, err error) {
  1720. return w.write(len(s), nil, s)
  1721. }
  1722. // either dataB or dataS is non-zero.
  1723. func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  1724. rws := w.rws
  1725. if rws == nil {
  1726. panic("Write called after Handler finished")
  1727. }
  1728. if !rws.wroteHeader {
  1729. w.WriteHeader(200)
  1730. }
  1731. if dataB != nil {
  1732. return rws.bw.Write(dataB)
  1733. } else {
  1734. return rws.bw.WriteString(dataS)
  1735. }
  1736. }
  1737. func (w *responseWriter) handlerDone() {
  1738. rws := w.rws
  1739. if rws == nil {
  1740. panic("handlerDone called twice")
  1741. }
  1742. rws.handlerDone = true
  1743. w.Flush()
  1744. w.rws = nil
  1745. responseWriterStatePool.Put(rws)
  1746. }