server.go 58 KB

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