server.go 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534
  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. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS
  5. // Licensed under the same terms as Go itself:
  6. // https://code.google.com/p/go/source/browse/LICENSE
  7. package http2
  8. import (
  9. "bufio"
  10. "bytes"
  11. "crypto/tls"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "log"
  16. "net"
  17. "net/http"
  18. "net/url"
  19. "strconv"
  20. "strings"
  21. "sync"
  22. "time"
  23. "github.com/bradfitz/http2/hpack"
  24. )
  25. const (
  26. prefaceTimeout = 10 * time.Second
  27. firstSettingsTimeout = 2 * time.Second // should be in-flight with preface anyway
  28. handlerChunkWriteSize = 4 << 10
  29. defaultMaxStreams = 250
  30. )
  31. var (
  32. errClientDisconnected = errors.New("client disconnected")
  33. errClosedBody = errors.New("body closed by handler")
  34. errStreamBroken = errors.New("http2: stream broken")
  35. )
  36. var responseWriterStatePool = sync.Pool{
  37. New: func() interface{} {
  38. rws := &responseWriterState{}
  39. rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize)
  40. return rws
  41. },
  42. }
  43. // Test hooks.
  44. var (
  45. testHookOnConn func()
  46. testHookGetServerConn func(*serverConn)
  47. )
  48. // TODO: finish GOAWAY support. Consider each incoming frame type and
  49. // whether it should be ignored during a shutdown race.
  50. // TODO: (edge case?) if peer sends a SETTINGS frame with e.g. a
  51. // SETTINGS_MAX_FRAME_SIZE that's lower than what we had before,
  52. // before we ACK it we have to make sure all currently-active streams
  53. // know about that and don't have existing too-large frames in flight?
  54. // Perhaps the settings processing should just wait for new frame to
  55. // be in-flight and then the frame scheduler in the serve goroutine
  56. // will be responsible for splitting things.
  57. // TODO: send PING frames to idle clients and disconnect them if no
  58. // reply
  59. // TODO: for bonus points: turn off the serve goroutine when idle, so
  60. // an idle conn only has the readFrames goroutine active. (which could
  61. // also be optimized probably to pin less memory in crypto/tls). This
  62. // would involve tracking when the serve goroutine is active (atomic
  63. // int32 read/CAS probably?) and starting it up when frames arrive,
  64. // and shutting it down when all handlers exit. the occasional PING
  65. // packets could use time.AfterFunc to call sc.wakeStartServeLoop()
  66. // (which is a no-op if already running) and then queue the PING write
  67. // as normal. The serve loop would then exit in most cases (if no
  68. // Handlers running) and not be woken up again until the PING packet
  69. // returns.
  70. // Server is an HTTP/2 server.
  71. type Server struct {
  72. // MaxHandlers limits the number of http.Handler ServeHTTP goroutines
  73. // which may run at a time over all connections.
  74. // Negative or zero no limit.
  75. // TODO: implement
  76. MaxHandlers int
  77. // MaxConcurrentStreams optionally specifies the number of
  78. // concurrent streams that each client may have open at a
  79. // time. This is unrelated to the number of http.Handler goroutines
  80. // which may be active globally, which is MaxHandlers.
  81. // If zero, MaxConcurrentStreams defaults to at least 100, per
  82. // the HTTP/2 spec's recommendations.
  83. MaxConcurrentStreams uint32
  84. // MaxReadFrameSize optionally specifies the largest frame
  85. // this server is willing to read. A valid value is between
  86. // 16k and 16M, inclusive. If zero or otherwise invalid, a
  87. // default value is used.
  88. MaxReadFrameSize uint32
  89. }
  90. func (s *Server) maxReadFrameSize() uint32 {
  91. if v := s.MaxReadFrameSize; v >= minMaxFrameSize && v <= maxFrameSize {
  92. return v
  93. }
  94. return defaultMaxReadFrameSize
  95. }
  96. func (s *Server) maxConcurrentStreams() uint32 {
  97. if v := s.MaxConcurrentStreams; v > 0 {
  98. return v
  99. }
  100. return defaultMaxStreams
  101. }
  102. // ConfigureServer adds HTTP/2 support to a net/http Server.
  103. //
  104. // The configuration conf may be nil.
  105. //
  106. // ConfigureServer must be called before s begins serving.
  107. func ConfigureServer(s *http.Server, conf *Server) {
  108. if conf == nil {
  109. conf = new(Server)
  110. }
  111. if s.TLSConfig == nil {
  112. s.TLSConfig = new(tls.Config)
  113. }
  114. haveNPN := false
  115. for _, p := range s.TLSConfig.NextProtos {
  116. if p == NextProtoTLS {
  117. haveNPN = true
  118. break
  119. }
  120. }
  121. if !haveNPN {
  122. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, NextProtoTLS)
  123. }
  124. if s.TLSNextProto == nil {
  125. s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
  126. }
  127. s.TLSNextProto[NextProtoTLS] = func(hs *http.Server, c *tls.Conn, h http.Handler) {
  128. if testHookOnConn != nil {
  129. testHookOnConn()
  130. }
  131. conf.handleConn(hs, c, h)
  132. }
  133. }
  134. func (srv *Server) handleConn(hs *http.Server, c net.Conn, h http.Handler) {
  135. sc := &serverConn{
  136. srv: srv,
  137. hs: hs,
  138. conn: c,
  139. bw: newBufferedWriter(c),
  140. handler: h,
  141. streams: make(map[uint32]*stream),
  142. readFrameCh: make(chan frameAndGate),
  143. readFrameErrCh: make(chan error, 1), // must be buffered for 1
  144. wantWriteFrameCh: make(chan frameWriteMsg, 8),
  145. wroteFrameCh: make(chan struct{}, 1), // buffered; one send in reading goroutine
  146. flow: newFlow(initialWindowSize),
  147. doneServing: make(chan struct{}),
  148. advMaxStreams: srv.maxConcurrentStreams(),
  149. maxWriteFrameSize: initialMaxFrameSize,
  150. initialWindowSize: initialWindowSize,
  151. headerTableSize: initialHeaderTableSize,
  152. serveG: newGoroutineLock(),
  153. pushEnabled: true,
  154. }
  155. sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
  156. sc.hpackDecoder = hpack.NewDecoder(initialHeaderTableSize, sc.onNewHeaderField)
  157. fr := NewFramer(sc.bw, c)
  158. fr.SetMaxReadFrameSize(srv.maxReadFrameSize())
  159. sc.framer = fr
  160. if hook := testHookGetServerConn; hook != nil {
  161. hook(sc)
  162. }
  163. sc.serve()
  164. }
  165. // frameAndGates coordinates the readFrames and serve
  166. // goroutines. Because the Framer interface only permits the most
  167. // recently-read Frame from being accessed, the readFrames goroutine
  168. // blocks until it has a frame, passes it to serve, and then waits for
  169. // serve to be done with it before reading the next one.
  170. type frameAndGate struct {
  171. f Frame
  172. g gate
  173. }
  174. type serverConn struct {
  175. // Immutable:
  176. srv *Server
  177. hs *http.Server
  178. conn net.Conn
  179. bw *bufferedWriter // writing to conn
  180. handler http.Handler
  181. framer *Framer
  182. hpackDecoder *hpack.Decoder
  183. doneServing chan struct{} // closed when serverConn.serve ends
  184. readFrameCh chan frameAndGate // written by serverConn.readFrames
  185. readFrameErrCh chan error
  186. wantWriteFrameCh chan frameWriteMsg // from handlers -> serve
  187. wroteFrameCh chan struct{} // from writeFrameAsync -> serve, tickles more frame writes
  188. testHookCh chan func() // code to run on the serve loop
  189. flow *flow // connection-wide (not stream-specific) flow control
  190. // Everything following is owned by the serve loop; use serveG.check():
  191. serveG goroutineLock // used to verify funcs are on serve()
  192. pushEnabled bool
  193. sawFirstSettings bool // got the initial SETTINGS frame after the preface
  194. needToSendSettingsAck bool
  195. clientMaxStreams uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)
  196. advMaxStreams uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client
  197. curOpenStreams uint32 // client's number of open streams
  198. maxStreamID uint32 // max ever seen
  199. streams map[uint32]*stream
  200. maxWriteFrameSize uint32
  201. initialWindowSize int32
  202. headerTableSize uint32
  203. maxHeaderListSize uint32 // zero means unknown (default)
  204. canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case
  205. req requestParam // non-zero while reading request headers
  206. writingFrame bool // started write goroutine but haven't heard back on wroteFrameCh
  207. needsFrameFlush bool // last frame write wasn't a flush
  208. writeSched writeScheduler
  209. inGoAway bool // we've started to or sent GOAWAY
  210. needToSendGoAway bool // we need to schedule a GOAWAY frame write
  211. goAwayCode ErrCode
  212. shutdownTimerCh <-chan time.Time // nil until used
  213. shutdownTimer *time.Timer // nil until used
  214. // Owned by the writeFrameAsync goroutine:
  215. headerWriteBuf bytes.Buffer
  216. hpackEncoder *hpack.Encoder
  217. }
  218. // requestParam is the state of the next request, initialized over
  219. // potentially several frames HEADERS + zero or more CONTINUATION
  220. // frames.
  221. type requestParam struct {
  222. // stream is non-nil if we're reading (HEADER or CONTINUATION)
  223. // frames for a request (but not DATA).
  224. stream *stream
  225. header http.Header
  226. method, path string
  227. scheme, authority string
  228. sawRegularHeader bool // saw a non-pseudo header already
  229. invalidHeader bool // an invalid header was seen
  230. }
  231. // stream represents a stream. This is the minimal metadata needed by
  232. // the serve goroutine. Most of the actual stream state is owned by
  233. // the http.Handler's goroutine in the responseWriter. Because the
  234. // responseWriter's responseWriterState is recycled at the end of a
  235. // handler, this struct intentionally has no pointer to the
  236. // *responseWriter{,State} itself, as the Handler ending nils out the
  237. // responseWriter's state field.
  238. type stream struct {
  239. // immutable:
  240. id uint32
  241. conn *serverConn
  242. flow *flow // limits writing from Handler to client
  243. body *pipe // non-nil if expecting DATA frames
  244. cw closeWaiter // closed wait stream transitions to closed state
  245. // owned by serverConn's serve loop:
  246. state streamState
  247. bodyBytes int64 // body bytes seen so far
  248. declBodyBytes int64 // or -1 if undeclared
  249. sentReset bool // only true once detached from streams map
  250. gotReset bool // only true once detacted from streams map
  251. }
  252. func (sc *serverConn) Framer() *Framer { return sc.framer }
  253. func (sc *serverConn) CloseConn() error { return sc.conn.Close() }
  254. func (sc *serverConn) Flush() error { return sc.bw.Flush() }
  255. func (sc *serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) {
  256. return sc.hpackEncoder, &sc.headerWriteBuf
  257. }
  258. func (sc *serverConn) state(streamID uint32) streamState {
  259. sc.serveG.check()
  260. // http://http2.github.io/http2-spec/#rfc.section.5.1
  261. if st, ok := sc.streams[streamID]; ok {
  262. return st.state
  263. }
  264. // "The first use of a new stream identifier implicitly closes all
  265. // streams in the "idle" state that might have been initiated by
  266. // that peer with a lower-valued stream identifier. For example, if
  267. // a client sends a HEADERS frame on stream 7 without ever sending a
  268. // frame on stream 5, then stream 5 transitions to the "closed"
  269. // state when the first frame for stream 7 is sent or received."
  270. if streamID <= sc.maxStreamID {
  271. return stateClosed
  272. }
  273. return stateIdle
  274. }
  275. func (sc *serverConn) vlogf(format string, args ...interface{}) {
  276. if VerboseLogs {
  277. sc.logf(format, args...)
  278. }
  279. }
  280. func (sc *serverConn) logf(format string, args ...interface{}) {
  281. if lg := sc.hs.ErrorLog; lg != nil {
  282. lg.Printf(format, args...)
  283. } else {
  284. log.Printf(format, args...)
  285. }
  286. }
  287. func (sc *serverConn) condlogf(err error, format string, args ...interface{}) {
  288. if err == nil {
  289. return
  290. }
  291. str := err.Error()
  292. if err == io.EOF || strings.Contains(str, "use of closed network connection") {
  293. // Boring, expected errors.
  294. sc.vlogf(format, args...)
  295. } else {
  296. sc.logf(format, args...)
  297. }
  298. }
  299. func (sc *serverConn) onNewHeaderField(f hpack.HeaderField) {
  300. sc.serveG.check()
  301. switch {
  302. case !validHeader(f.Name):
  303. sc.req.invalidHeader = true
  304. case strings.HasPrefix(f.Name, ":"):
  305. if sc.req.sawRegularHeader {
  306. sc.logf("pseudo-header after regular header")
  307. sc.req.invalidHeader = true
  308. return
  309. }
  310. var dst *string
  311. switch f.Name {
  312. case ":method":
  313. dst = &sc.req.method
  314. case ":path":
  315. dst = &sc.req.path
  316. case ":scheme":
  317. dst = &sc.req.scheme
  318. case ":authority":
  319. dst = &sc.req.authority
  320. default:
  321. // 8.1.2.1 Pseudo-Header Fields
  322. // "Endpoints MUST treat a request or response
  323. // that contains undefined or invalid
  324. // pseudo-header fields as malformed (Section
  325. // 8.1.2.6)."
  326. sc.logf("invalid pseudo-header %q", f.Name)
  327. sc.req.invalidHeader = true
  328. return
  329. }
  330. if *dst != "" {
  331. sc.logf("duplicate pseudo-header %q sent", f.Name)
  332. sc.req.invalidHeader = true
  333. return
  334. }
  335. *dst = f.Value
  336. case f.Name == "cookie":
  337. sc.req.sawRegularHeader = true
  338. if s, ok := sc.req.header["Cookie"]; ok && len(s) == 1 {
  339. s[0] = s[0] + "; " + f.Value
  340. } else {
  341. sc.req.header.Add("Cookie", f.Value)
  342. }
  343. default:
  344. sc.req.sawRegularHeader = true
  345. sc.req.header.Add(sc.canonicalHeader(f.Name), f.Value)
  346. }
  347. }
  348. func (sc *serverConn) canonicalHeader(v string) string {
  349. sc.serveG.check()
  350. cv, ok := commonCanonHeader[v]
  351. if ok {
  352. return cv
  353. }
  354. cv, ok = sc.canonHeader[v]
  355. if ok {
  356. return cv
  357. }
  358. if sc.canonHeader == nil {
  359. sc.canonHeader = make(map[string]string)
  360. }
  361. cv = http.CanonicalHeaderKey(v)
  362. sc.canonHeader[v] = cv
  363. return cv
  364. }
  365. // readFrames is the loop that reads incoming frames.
  366. // It's run on its own goroutine.
  367. func (sc *serverConn) readFrames() {
  368. g := make(gate, 1)
  369. for {
  370. f, err := sc.framer.ReadFrame()
  371. if err != nil {
  372. sc.readFrameErrCh <- err
  373. close(sc.readFrameCh)
  374. return
  375. }
  376. sc.readFrameCh <- frameAndGate{f, g}
  377. // We can't read another frame until this one is
  378. // processed, as the ReadFrame interface doesn't copy
  379. // memory. The Frame accessor methods access the last
  380. // frame's (shared) buffer. So we wait for the
  381. // serve goroutine to tell us it's done:
  382. g.Wait()
  383. }
  384. }
  385. // writeFrameAsync runs in its own goroutine and writes a single frame
  386. // and then reports when it's done.
  387. // At most one goroutine can be running writeFrameAsync at a time per
  388. // serverConn.
  389. func (sc *serverConn) writeFrameAsync(wm frameWriteMsg) {
  390. err := wm.write.writeFrame(sc)
  391. if ch := wm.done; ch != nil {
  392. select {
  393. case ch <- err:
  394. default:
  395. panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wm.write))
  396. }
  397. }
  398. sc.wroteFrameCh <- struct{}{} // tickle frame selection scheduler
  399. }
  400. func (sc *serverConn) closeAllStreamsOnConnClose() {
  401. sc.serveG.check()
  402. for _, st := range sc.streams {
  403. sc.closeStream(st, errClientDisconnected)
  404. }
  405. }
  406. func (sc *serverConn) stopShutdownTimer() {
  407. sc.serveG.check()
  408. if t := sc.shutdownTimer; t != nil {
  409. t.Stop()
  410. }
  411. }
  412. func (sc *serverConn) serve() {
  413. sc.serveG.check()
  414. defer sc.conn.Close()
  415. defer sc.closeAllStreamsOnConnClose()
  416. defer sc.stopShutdownTimer()
  417. defer close(sc.doneServing) // unblocks handlers trying to send
  418. sc.vlogf("HTTP/2 connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
  419. sc.writeFrame(frameWriteMsg{
  420. write: writeSettings{
  421. {SettingMaxFrameSize, sc.srv.maxReadFrameSize()},
  422. {SettingMaxConcurrentStreams, sc.advMaxStreams},
  423. /* TODO: more actual settings */
  424. },
  425. })
  426. if err := sc.readPreface(); err != nil {
  427. sc.condlogf(err, "error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
  428. return
  429. }
  430. go sc.readFrames() // closed by defer sc.conn.Close above
  431. settingsTimer := time.NewTimer(firstSettingsTimeout)
  432. for {
  433. select {
  434. case wm := <-sc.wantWriteFrameCh:
  435. sc.writeFrame(wm)
  436. case <-sc.wroteFrameCh:
  437. sc.writingFrame = false
  438. sc.scheduleFrameWrite()
  439. case fg, ok := <-sc.readFrameCh:
  440. if !ok {
  441. sc.readFrameCh = nil
  442. }
  443. if !sc.processFrameFromReader(fg, ok) {
  444. return
  445. }
  446. if settingsTimer.C != nil {
  447. settingsTimer.Stop()
  448. settingsTimer.C = nil
  449. }
  450. case <-settingsTimer.C:
  451. sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
  452. return
  453. case <-sc.shutdownTimerCh:
  454. sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
  455. return
  456. case fn := <-sc.testHookCh:
  457. fn()
  458. }
  459. }
  460. }
  461. // readPreface reads the ClientPreface greeting from the peer
  462. // or returns an error on timeout or an invalid greeting.
  463. func (sc *serverConn) readPreface() error {
  464. errc := make(chan error, 1)
  465. go func() {
  466. // Read the client preface
  467. buf := make([]byte, len(ClientPreface))
  468. if _, err := io.ReadFull(sc.conn, buf); err != nil {
  469. errc <- err
  470. } else if !bytes.Equal(buf, clientPreface) {
  471. errc <- fmt.Errorf("bogus greeting %q", buf)
  472. } else {
  473. errc <- nil
  474. }
  475. }()
  476. timer := time.NewTimer(5 * time.Second) // TODO: configurable on *Server?
  477. defer timer.Stop()
  478. select {
  479. case <-timer.C:
  480. return errors.New("timeout waiting for client preface")
  481. case err := <-errc:
  482. if err == nil {
  483. sc.vlogf("client %v said hello", sc.conn.RemoteAddr())
  484. }
  485. return err
  486. }
  487. }
  488. // writeDataFromHandler writes the data described in req to stream.id.
  489. //
  490. // The provided ch is used to avoid allocating new channels for each
  491. // write operation. It's expected that the caller reuses writeData and ch
  492. // over time.
  493. //
  494. // The flow control currently happens in the Handler where it waits
  495. // for 1 or more bytes to be available to then write here. So at this
  496. // point we know that we have flow control. But this might have to
  497. // change when priority is implemented, so the serve goroutine knows
  498. // the total amount of bytes waiting to be sent and can can have more
  499. // scheduling decisions available.
  500. func (sc *serverConn) writeDataFromHandler(stream *stream, writeData *writeData, ch chan error) error {
  501. sc.writeFrameFromHandler(frameWriteMsg{
  502. write: writeData,
  503. stream: stream,
  504. done: ch,
  505. })
  506. select {
  507. case err := <-ch:
  508. return err
  509. case <-sc.doneServing:
  510. return errClientDisconnected
  511. }
  512. }
  513. // writeFrameFromHandler sends wm to sc.wantWriteFrameCh, but aborts
  514. // if the connection has gone away.
  515. //
  516. // This must not be run from the serve goroutine itself, else it might
  517. // deadlock writing to sc.wantWriteFrameCh (which is only mildly
  518. // buffered and is read by serve itself). If you're on the serve
  519. // goroutine, call writeFrame instead.
  520. func (sc *serverConn) writeFrameFromHandler(wm frameWriteMsg) {
  521. sc.serveG.checkNotOn() // NOT
  522. select {
  523. case sc.wantWriteFrameCh <- wm:
  524. case <-sc.doneServing:
  525. // Client has closed their connection to the server.
  526. }
  527. }
  528. // writeFrame either sends wm to the writeFrames goroutine, or
  529. // enqueues it for the future (with no pushback; the serve goroutine
  530. // never blocks!), for sending when the currently-being-written frame
  531. // is done writing.
  532. //
  533. // If you're not on the serve goroutine, use writeFrame instead.
  534. func (sc *serverConn) writeFrame(wm frameWriteMsg) {
  535. sc.serveG.check()
  536. // Fast path for common case:
  537. if !sc.writingFrame {
  538. sc.startFrameWrite(wm)
  539. return
  540. }
  541. sc.writeSched.add(wm)
  542. }
  543. // startFrameWrite starts a goroutine to write wm (in a separate
  544. // goroutine since that might block on the network), and updates the
  545. // serve goroutine's state about the world, updated from info in wm.
  546. func (sc *serverConn) startFrameWrite(wm frameWriteMsg) {
  547. sc.serveG.check()
  548. if sc.writingFrame {
  549. panic("internal error: can only be writing one frame at a time")
  550. }
  551. st := wm.stream
  552. if st != nil {
  553. switch st.state {
  554. case stateHalfClosedLocal:
  555. panic("internal error: attempt to send frame on half-closed-local stream")
  556. case stateClosed:
  557. if st.sentReset || st.gotReset {
  558. // Skip this frame. But fake the frame write to reschedule:
  559. sc.wroteFrameCh <- struct{}{}
  560. return
  561. }
  562. panic("internal error: attempt to send a frame on a closed stream")
  563. }
  564. }
  565. sc.writingFrame = true
  566. sc.needsFrameFlush = true
  567. if endsStream(wm.write) {
  568. if st == nil {
  569. panic("internal error: expecting non-nil stream")
  570. }
  571. switch st.state {
  572. case stateOpen:
  573. st.state = stateHalfClosedLocal
  574. case stateHalfClosedRemote:
  575. sc.closeStream(st, nil)
  576. }
  577. }
  578. go sc.writeFrameAsync(wm)
  579. }
  580. // scheduleFrameWrite tickles the frame writing scheduler.
  581. //
  582. // If a frame is already being written, nothing happens. This will be called again
  583. // when the frame is done being written.
  584. //
  585. // If a frame isn't being written we need to send one, the best frame
  586. // to send is selected, preferring first things that aren't
  587. // stream-specific (e.g. ACKing settings), and then finding the
  588. // highest priority stream.
  589. //
  590. // If a frame isn't being written and there's nothing else to send, we
  591. // flush the write buffer.
  592. func (sc *serverConn) scheduleFrameWrite() {
  593. sc.serveG.check()
  594. if sc.writingFrame {
  595. return
  596. }
  597. if sc.needToSendGoAway {
  598. sc.needToSendGoAway = false
  599. sc.startFrameWrite(frameWriteMsg{
  600. write: &writeGoAway{
  601. maxStreamID: sc.maxStreamID,
  602. code: sc.goAwayCode,
  603. },
  604. })
  605. return
  606. }
  607. if sc.writeSched.empty() && sc.needsFrameFlush {
  608. sc.startFrameWrite(frameWriteMsg{write: flushFrameWriter{}})
  609. sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
  610. return
  611. }
  612. if sc.inGoAway {
  613. // No more frames after we've sent GOAWAY.
  614. return
  615. }
  616. if sc.needToSendSettingsAck {
  617. sc.needToSendSettingsAck = false
  618. sc.startFrameWrite(frameWriteMsg{write: writeSettingsAck{}})
  619. return
  620. }
  621. if sc.writeSched.empty() {
  622. return
  623. }
  624. // TODO: if wm is a data frame, make sure it's not too big
  625. // (because a SETTINGS frame changed our max frame size while
  626. // a stream was open and writing) and cut it up into smaller
  627. // bits.
  628. sc.startFrameWrite(sc.writeSched.take())
  629. }
  630. func (sc *serverConn) goAway(code ErrCode) {
  631. sc.serveG.check()
  632. if sc.inGoAway {
  633. return
  634. }
  635. if code != ErrCodeNo {
  636. sc.shutDownIn(250 * time.Millisecond)
  637. } else {
  638. // TODO: configurable
  639. sc.shutDownIn(1 * time.Second)
  640. }
  641. sc.inGoAway = true
  642. sc.needToSendGoAway = true
  643. sc.goAwayCode = code
  644. sc.scheduleFrameWrite()
  645. }
  646. func (sc *serverConn) shutDownIn(d time.Duration) {
  647. sc.serveG.check()
  648. sc.shutdownTimer = time.NewTimer(d)
  649. sc.shutdownTimerCh = sc.shutdownTimer.C
  650. }
  651. func (sc *serverConn) resetStream(se StreamError) {
  652. sc.serveG.check()
  653. st, ok := sc.streams[se.StreamID]
  654. if !ok {
  655. panic("internal package error; resetStream called on non-existent stream")
  656. }
  657. sc.writeFrame(frameWriteMsg{write: se})
  658. st.sentReset = true
  659. sc.closeStream(st, se)
  660. }
  661. // curHeaderStreamID returns the stream ID of the header block we're
  662. // currently in the middle of reading. If this returns non-zero, the
  663. // next frame must be a CONTINUATION with this stream id.
  664. func (sc *serverConn) curHeaderStreamID() uint32 {
  665. sc.serveG.check()
  666. st := sc.req.stream
  667. if st == nil {
  668. return 0
  669. }
  670. return st.id
  671. }
  672. // processFrameFromReader processes the serve loop's read from readFrameCh from the
  673. // frame-reading goroutine.
  674. // processFrameFromReader returns whether the connection should be kept open.
  675. func (sc *serverConn) processFrameFromReader(fg frameAndGate, fgValid bool) bool {
  676. sc.serveG.check()
  677. var clientGone bool
  678. var err error
  679. if !fgValid {
  680. err = <-sc.readFrameErrCh
  681. if err == ErrFrameTooLarge {
  682. sc.goAway(ErrCodeFrameSize)
  683. return true // goAway will close the loop
  684. }
  685. clientGone = err == io.EOF || strings.Contains(err.Error(), "use of closed network connection")
  686. if clientGone {
  687. // TODO: could we also get into this state if
  688. // the peer does a half close
  689. // (e.g. CloseWrite) because they're done
  690. // sending frames but they're still wanting
  691. // our open replies? Investigate.
  692. return false
  693. }
  694. }
  695. if fgValid {
  696. f := fg.f
  697. sc.vlogf("got %v: %#v", f.Header(), f)
  698. err = sc.processFrame(f)
  699. fg.g.Done() // unblock the readFrames goroutine
  700. if err == nil {
  701. return true
  702. }
  703. }
  704. switch ev := err.(type) {
  705. case StreamError:
  706. sc.resetStream(ev)
  707. return true
  708. case goAwayFlowError:
  709. sc.goAway(ErrCodeFlowControl)
  710. return true
  711. case ConnectionError:
  712. sc.logf("%v: %v", sc.conn.RemoteAddr(), ev)
  713. sc.goAway(ErrCode(ev))
  714. return true // goAway will handle shutdown
  715. default:
  716. if !fgValid {
  717. sc.logf("disconnecting; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
  718. } else {
  719. sc.logf("disconnection due to other error: %v", err)
  720. }
  721. }
  722. return false
  723. }
  724. func (sc *serverConn) processFrame(f Frame) error {
  725. sc.serveG.check()
  726. // First frame received must be SETTINGS.
  727. if !sc.sawFirstSettings {
  728. if _, ok := f.(*SettingsFrame); !ok {
  729. return ConnectionError(ErrCodeProtocol)
  730. }
  731. sc.sawFirstSettings = true
  732. }
  733. if s := sc.curHeaderStreamID(); s != 0 {
  734. if cf, ok := f.(*ContinuationFrame); !ok {
  735. return ConnectionError(ErrCodeProtocol)
  736. } else if cf.Header().StreamID != s {
  737. return ConnectionError(ErrCodeProtocol)
  738. }
  739. }
  740. switch f := f.(type) {
  741. case *SettingsFrame:
  742. return sc.processSettings(f)
  743. case *HeadersFrame:
  744. return sc.processHeaders(f)
  745. case *ContinuationFrame:
  746. return sc.processContinuation(f)
  747. case *WindowUpdateFrame:
  748. return sc.processWindowUpdate(f)
  749. case *PingFrame:
  750. return sc.processPing(f)
  751. case *DataFrame:
  752. return sc.processData(f)
  753. case *RSTStreamFrame:
  754. return sc.processResetStream(f)
  755. default:
  756. log.Printf("Ignoring frame: %v", f.Header())
  757. return nil
  758. }
  759. }
  760. func (sc *serverConn) processPing(f *PingFrame) error {
  761. sc.serveG.check()
  762. if f.Flags.Has(FlagSettingsAck) {
  763. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  764. // containing this flag."
  765. return nil
  766. }
  767. if f.StreamID != 0 {
  768. // "PING frames are not associated with any individual
  769. // stream. If a PING frame is received with a stream
  770. // identifier field value other than 0x0, the recipient MUST
  771. // respond with a connection error (Section 5.4.1) of type
  772. // PROTOCOL_ERROR."
  773. return ConnectionError(ErrCodeProtocol)
  774. }
  775. sc.writeFrame(frameWriteMsg{write: writePingAck{f}})
  776. return nil
  777. }
  778. func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  779. sc.serveG.check()
  780. switch {
  781. case f.StreamID != 0: // stream-level flow control
  782. st := sc.streams[f.StreamID]
  783. if st == nil {
  784. // "WINDOW_UPDATE can be sent by a peer that has sent a
  785. // frame bearing the END_STREAM flag. This means that a
  786. // receiver could receive a WINDOW_UPDATE frame on a "half
  787. // closed (remote)" or "closed" stream. A receiver MUST
  788. // NOT treat this as an error, see Section 5.1."
  789. return nil
  790. }
  791. if !st.flow.add(int32(f.Increment)) {
  792. return StreamError{f.StreamID, ErrCodeFlowControl}
  793. }
  794. default: // connection-level flow control
  795. if !sc.flow.add(int32(f.Increment)) {
  796. return goAwayFlowError{}
  797. }
  798. }
  799. return nil
  800. }
  801. func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
  802. sc.serveG.check()
  803. if sc.state(f.StreamID) == stateIdle {
  804. // 6.4 "RST_STREAM frames MUST NOT be sent for a
  805. // stream in the "idle" state. If a RST_STREAM frame
  806. // identifying an idle stream is received, the
  807. // recipient MUST treat this as a connection error
  808. // (Section 5.4.1) of type PROTOCOL_ERROR.
  809. return ConnectionError(ErrCodeProtocol)
  810. }
  811. st, ok := sc.streams[f.StreamID]
  812. if ok {
  813. st.gotReset = true
  814. sc.closeStream(st, StreamError{f.StreamID, f.ErrCode})
  815. }
  816. return nil
  817. }
  818. func (sc *serverConn) closeStream(st *stream, err error) {
  819. sc.serveG.check()
  820. if st.state == stateIdle || st.state == stateClosed {
  821. panic("invariant")
  822. }
  823. st.state = stateClosed
  824. sc.curOpenStreams--
  825. delete(sc.streams, st.id)
  826. st.flow.close()
  827. if p := st.body; p != nil {
  828. p.Close(err)
  829. }
  830. st.cw.Close() // signals Handler's CloseNotifier goroutine (if any) to send
  831. }
  832. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  833. sc.serveG.check()
  834. if f.IsAck() {
  835. // TODO: do we need to do anything?
  836. // We might want to keep track of which settings we've sent
  837. // vs which settings the client has ACK'd, so we know when to be
  838. // strict. Or at least keep track of the count of
  839. // our SETTINGS send count vs their ACK count. If they're equal,
  840. // then we both have the same view of the world and we can be
  841. // stricter in some cases. But currently we don't send SETTINGS
  842. // at runtime other than the initial SETTINGS.
  843. return nil
  844. }
  845. if err := f.ForeachSetting(sc.processSetting); err != nil {
  846. return err
  847. }
  848. sc.needToSendSettingsAck = true
  849. sc.scheduleFrameWrite()
  850. return nil
  851. }
  852. func (sc *serverConn) processSetting(s Setting) error {
  853. sc.serveG.check()
  854. if err := s.Valid(); err != nil {
  855. return err
  856. }
  857. sc.vlogf("processing setting %v", s)
  858. switch s.ID {
  859. case SettingHeaderTableSize:
  860. sc.headerTableSize = s.Val
  861. sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
  862. case SettingEnablePush:
  863. sc.pushEnabled = s.Val != 0
  864. case SettingMaxConcurrentStreams:
  865. sc.clientMaxStreams = s.Val
  866. case SettingInitialWindowSize:
  867. return sc.processSettingInitialWindowSize(s.Val)
  868. case SettingMaxFrameSize:
  869. sc.maxWriteFrameSize = s.Val
  870. case SettingMaxHeaderListSize:
  871. sc.maxHeaderListSize = s.Val
  872. default:
  873. // Unknown setting: "An endpoint that receives a SETTINGS
  874. // frame with any unknown or unsupported identifier MUST
  875. // ignore that setting."
  876. }
  877. return nil
  878. }
  879. func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  880. sc.serveG.check()
  881. // Note: val already validated to be within range by
  882. // processSetting's Valid call.
  883. // "A SETTINGS frame can alter the initial flow control window
  884. // size for all current streams. When the value of
  885. // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  886. // adjust the size of all stream flow control windows that it
  887. // maintains by the difference between the new value and the
  888. // old value."
  889. old := sc.initialWindowSize
  890. sc.initialWindowSize = int32(val)
  891. growth := sc.initialWindowSize - old // may be negative
  892. for _, st := range sc.streams {
  893. if !st.flow.add(growth) {
  894. // 6.9.2 Initial Flow Control Window Size
  895. // "An endpoint MUST treat a change to
  896. // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  897. // control window to exceed the maximum size as a
  898. // connection error (Section 5.4.1) of type
  899. // FLOW_CONTROL_ERROR."
  900. return ConnectionError(ErrCodeFlowControl)
  901. }
  902. }
  903. return nil
  904. }
  905. func (sc *serverConn) processData(f *DataFrame) error {
  906. sc.serveG.check()
  907. // "If a DATA frame is received whose stream is not in "open"
  908. // or "half closed (local)" state, the recipient MUST respond
  909. // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  910. id := f.Header().StreamID
  911. st, ok := sc.streams[id]
  912. if !ok || (st.state != stateOpen && st.state != stateHalfClosedLocal) {
  913. return StreamError{id, ErrCodeStreamClosed}
  914. }
  915. if st.body == nil {
  916. panic("internal error: should have a body in this state")
  917. }
  918. data := f.Data()
  919. // Sender sending more than they'd declared?
  920. if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  921. st.body.Close(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  922. return StreamError{id, ErrCodeStreamClosed}
  923. }
  924. if len(data) > 0 {
  925. // TODO: verify they're allowed to write with the flow control
  926. // window we'd advertised to them.
  927. wrote, err := st.body.Write(data)
  928. if err != nil {
  929. return StreamError{id, ErrCodeStreamClosed}
  930. }
  931. if wrote != len(data) {
  932. panic("internal error: bad Writer")
  933. }
  934. st.bodyBytes += int64(len(data))
  935. }
  936. if f.StreamEnded() {
  937. if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  938. st.body.Close(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
  939. st.declBodyBytes, st.bodyBytes))
  940. } else {
  941. st.body.Close(io.EOF)
  942. }
  943. switch st.state {
  944. case stateOpen:
  945. st.state = stateHalfClosedRemote
  946. case stateHalfClosedLocal:
  947. st.state = stateClosed
  948. }
  949. }
  950. return nil
  951. }
  952. func (sc *serverConn) processHeaders(f *HeadersFrame) error {
  953. sc.serveG.check()
  954. id := f.Header().StreamID
  955. if sc.inGoAway {
  956. // Ignore.
  957. return nil
  958. }
  959. // http://http2.github.io/http2-spec/#rfc.section.5.1.1
  960. if id%2 != 1 || id <= sc.maxStreamID || sc.req.stream != nil {
  961. // Streams initiated by a client MUST use odd-numbered
  962. // stream identifiers. [...] The identifier of a newly
  963. // established stream MUST be numerically greater than all
  964. // streams that the initiating endpoint has opened or
  965. // reserved. [...] An endpoint that receives an unexpected
  966. // stream identifier MUST respond with a connection error
  967. // (Section 5.4.1) of type PROTOCOL_ERROR.
  968. return ConnectionError(ErrCodeProtocol)
  969. }
  970. if id > sc.maxStreamID {
  971. sc.maxStreamID = id
  972. }
  973. st := &stream{
  974. conn: sc,
  975. id: id,
  976. state: stateOpen,
  977. flow: newFlow(sc.initialWindowSize),
  978. }
  979. st.cw.Init() // make Cond use its Mutex, without heap-promoting them separately
  980. if f.StreamEnded() {
  981. st.state = stateHalfClosedRemote
  982. }
  983. sc.streams[id] = st
  984. sc.curOpenStreams++
  985. sc.req = requestParam{
  986. stream: st,
  987. header: make(http.Header),
  988. }
  989. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  990. }
  991. func (sc *serverConn) processContinuation(f *ContinuationFrame) error {
  992. sc.serveG.check()
  993. st := sc.streams[f.Header().StreamID]
  994. if st == nil || sc.curHeaderStreamID() != st.id {
  995. return ConnectionError(ErrCodeProtocol)
  996. }
  997. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  998. }
  999. func (sc *serverConn) processHeaderBlockFragment(st *stream, frag []byte, end bool) error {
  1000. sc.serveG.check()
  1001. if _, err := sc.hpackDecoder.Write(frag); err != nil {
  1002. // TODO: convert to stream error I assume?
  1003. return err
  1004. }
  1005. if !end {
  1006. return nil
  1007. }
  1008. if err := sc.hpackDecoder.Close(); err != nil {
  1009. // TODO: convert to stream error I assume?
  1010. return err
  1011. }
  1012. defer sc.resetPendingRequest()
  1013. if sc.curOpenStreams > sc.advMaxStreams {
  1014. // Too many open streams.
  1015. // TODO: which error code here? Using ErrCodeProtocol for now.
  1016. // https://github.com/http2/http2-spec/issues/649
  1017. return StreamError{st.id, ErrCodeProtocol}
  1018. }
  1019. rw, req, err := sc.newWriterAndRequest()
  1020. if err != nil {
  1021. return err
  1022. }
  1023. st.body = req.Body.(*requestBody).pipe // may be nil
  1024. st.declBodyBytes = req.ContentLength
  1025. go sc.runHandler(rw, req)
  1026. return nil
  1027. }
  1028. // resetPendingRequest zeros out all state related to a HEADERS frame
  1029. // and its zero or more CONTINUATION frames sent to start a new
  1030. // request.
  1031. func (sc *serverConn) resetPendingRequest() {
  1032. sc.serveG.check()
  1033. sc.req = requestParam{}
  1034. }
  1035. func (sc *serverConn) newWriterAndRequest() (*responseWriter, *http.Request, error) {
  1036. sc.serveG.check()
  1037. rp := &sc.req
  1038. if rp.invalidHeader || rp.method == "" || rp.path == "" ||
  1039. (rp.scheme != "https" && rp.scheme != "http") {
  1040. // See 8.1.2.6 Malformed Requests and Responses:
  1041. //
  1042. // Malformed requests or responses that are detected
  1043. // MUST be treated as a stream error (Section 5.4.2)
  1044. // of type PROTOCOL_ERROR."
  1045. //
  1046. // 8.1.2.3 Request Pseudo-Header Fields
  1047. // "All HTTP/2 requests MUST include exactly one valid
  1048. // value for the :method, :scheme, and :path
  1049. // pseudo-header fields"
  1050. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1051. }
  1052. var tlsState *tls.ConnectionState // make this non-nil if https
  1053. if rp.scheme == "https" {
  1054. tlsState = &tls.ConnectionState{}
  1055. if tc, ok := sc.conn.(*tls.Conn); ok {
  1056. *tlsState = tc.ConnectionState()
  1057. if tlsState.Version < tls.VersionTLS12 {
  1058. // 9.2 Use of TLS Features
  1059. // An implementation of HTTP/2 over TLS MUST use TLS
  1060. // 1.2 or higher with the restrictions on feature set
  1061. // and cipher suite described in this section. Due to
  1062. // implementation limitations, it might not be
  1063. // possible to fail TLS negotiation. An endpoint MUST
  1064. // immediately terminate an HTTP/2 connection that
  1065. // does not meet the TLS requirements described in
  1066. // this section with a connection error (Section
  1067. // 5.4.1) of type INADEQUATE_SECURITY.
  1068. return nil, nil, ConnectionError(ErrCodeInadequateSecurity)
  1069. }
  1070. // TODO: verify cipher suites. (9.2.1, 9.2.2)
  1071. }
  1072. }
  1073. authority := rp.authority
  1074. if authority == "" {
  1075. authority = rp.header.Get("Host")
  1076. }
  1077. needsContinue := rp.header.Get("Expect") == "100-continue"
  1078. if needsContinue {
  1079. rp.header.Del("Expect")
  1080. }
  1081. bodyOpen := rp.stream.state == stateOpen
  1082. body := &requestBody{
  1083. stream: rp.stream,
  1084. needsContinue: needsContinue,
  1085. }
  1086. // TODO: handle asterisk '*' requests + test
  1087. url, err := url.ParseRequestURI(rp.path)
  1088. if err != nil {
  1089. // TODO: find the right error code?
  1090. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1091. }
  1092. req := &http.Request{
  1093. Method: rp.method,
  1094. URL: url,
  1095. RemoteAddr: sc.conn.RemoteAddr().String(),
  1096. Header: rp.header,
  1097. RequestURI: rp.path,
  1098. Proto: "HTTP/2.0",
  1099. ProtoMajor: 2,
  1100. ProtoMinor: 0,
  1101. TLS: tlsState,
  1102. Host: authority,
  1103. Body: body,
  1104. }
  1105. if bodyOpen {
  1106. body.pipe = &pipe{
  1107. b: buffer{buf: make([]byte, 65536)}, // TODO: share/remove
  1108. }
  1109. body.pipe.c.L = &body.pipe.m
  1110. if vv, ok := rp.header["Content-Length"]; ok {
  1111. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  1112. } else {
  1113. req.ContentLength = -1
  1114. }
  1115. }
  1116. rws := responseWriterStatePool.Get().(*responseWriterState)
  1117. bwSave := rws.bw
  1118. *rws = responseWriterState{} // zero all the fields
  1119. rws.bw = bwSave
  1120. rws.bw.Reset(chunkWriter{rws})
  1121. rws.stream = rp.stream
  1122. rws.req = req
  1123. rws.body = body
  1124. rws.frameWriteCh = make(chan error, 1)
  1125. rw := &responseWriter{rws: rws}
  1126. return rw, req, nil
  1127. }
  1128. // Run on its own goroutine.
  1129. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request) {
  1130. defer rw.handlerDone()
  1131. // TODO: catch panics like net/http.Server
  1132. sc.handler.ServeHTTP(rw, req)
  1133. }
  1134. // called from handler goroutines.
  1135. // h may be nil.
  1136. func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders, tempCh chan error) {
  1137. sc.serveG.checkNotOn() // NOT on
  1138. var errc chan error
  1139. if headerData.h != nil {
  1140. // If there's a header map (which we don't own), so we have to block on
  1141. // waiting for this frame to be written, so an http.Flush mid-handler
  1142. // writes out the correct value of keys, before a handler later potentially
  1143. // mutates it.
  1144. errc = tempCh
  1145. }
  1146. sc.writeFrameFromHandler(frameWriteMsg{
  1147. write: headerData,
  1148. stream: st,
  1149. done: errc,
  1150. })
  1151. if errc != nil {
  1152. select {
  1153. case <-errc:
  1154. // Ignore. Just for synchronization.
  1155. // Any error will be handled in the writing goroutine.
  1156. case <-sc.doneServing:
  1157. // Client has closed the connection.
  1158. }
  1159. }
  1160. }
  1161. // called from handler goroutines.
  1162. func (sc *serverConn) write100ContinueHeaders(st *stream) {
  1163. sc.writeFrameFromHandler(frameWriteMsg{
  1164. write: write100ContinueHeadersFrame{st.id},
  1165. stream: st,
  1166. })
  1167. }
  1168. // called from handler goroutines
  1169. func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
  1170. if st == nil {
  1171. panic("no stream")
  1172. }
  1173. const maxUint32 = 2147483647
  1174. for n >= maxUint32 {
  1175. sc.writeFrameFromHandler(frameWriteMsg{
  1176. write: writeWindowUpdate{streamID: st.id, n: maxUint32},
  1177. stream: st,
  1178. })
  1179. n -= maxUint32
  1180. }
  1181. if n > 0 {
  1182. sc.writeFrameFromHandler(frameWriteMsg{
  1183. write: writeWindowUpdate{streamID: st.id, n: uint32(n)},
  1184. stream: st,
  1185. })
  1186. }
  1187. }
  1188. type requestBody struct {
  1189. stream *stream
  1190. closed bool
  1191. pipe *pipe // non-nil if we have a HTTP entity message body
  1192. needsContinue bool // need to send a 100-continue
  1193. }
  1194. func (b *requestBody) Close() error {
  1195. if b.pipe != nil {
  1196. b.pipe.Close(errClosedBody)
  1197. }
  1198. b.closed = true
  1199. return nil
  1200. }
  1201. func (b *requestBody) Read(p []byte) (n int, err error) {
  1202. if b.needsContinue {
  1203. b.needsContinue = false
  1204. b.stream.conn.write100ContinueHeaders(b.stream)
  1205. }
  1206. if b.pipe == nil {
  1207. return 0, io.EOF
  1208. }
  1209. n, err = b.pipe.Read(p)
  1210. if n > 0 {
  1211. b.stream.conn.sendWindowUpdate(b.stream, n)
  1212. }
  1213. return
  1214. }
  1215. // responseWriter is the http.ResponseWriter implementation. It's
  1216. // intentionally small (1 pointer wide) to minimize garbage. The
  1217. // responseWriterState pointer inside is zeroed at the end of a
  1218. // request (in handlerDone) and calls on the responseWriter thereafter
  1219. // simply crash (caller's mistake), but the much larger responseWriterState
  1220. // and buffers are reused between multiple requests.
  1221. type responseWriter struct {
  1222. rws *responseWriterState
  1223. }
  1224. // Optional http.ResponseWriter interfaces implemented.
  1225. var (
  1226. _ http.CloseNotifier = (*responseWriter)(nil)
  1227. _ http.Flusher = (*responseWriter)(nil)
  1228. _ stringWriter = (*responseWriter)(nil)
  1229. )
  1230. type responseWriterState struct {
  1231. // immutable within a request:
  1232. stream *stream
  1233. req *http.Request
  1234. body *requestBody // to close at end of request, if DATA frames didn't
  1235. // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
  1236. bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
  1237. // mutated by http.Handler goroutine:
  1238. handlerHeader http.Header // nil until called
  1239. snapHeader http.Header // snapshot of handlerHeader at WriteHeader time
  1240. status int // status code passed to WriteHeader
  1241. wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
  1242. sentHeader bool // have we sent the header frame?
  1243. handlerDone bool // handler has finished
  1244. curWrite writeData
  1245. frameWriteCh chan error // re-used whenever we need to block on a frame being written
  1246. closeNotifierMu sync.Mutex // guards closeNotifierCh
  1247. closeNotifierCh chan bool // nil until first used
  1248. }
  1249. func (rws *responseWriterState) writeData(p []byte, end bool) error {
  1250. rws.curWrite.streamID = rws.stream.id
  1251. rws.curWrite.p = p
  1252. rws.curWrite.endStream = end
  1253. return rws.stream.conn.writeDataFromHandler(rws.stream, &rws.curWrite, rws.frameWriteCh)
  1254. }
  1255. type chunkWriter struct{ rws *responseWriterState }
  1256. func (cw chunkWriter) Write(p []byte) (n int, err error) { return cw.rws.writeChunk(p) }
  1257. // writeChunk writes chunks from the bufio.Writer. But because
  1258. // bufio.Writer may bypass its chunking, sometimes p may be
  1259. // arbitrarily large.
  1260. //
  1261. // writeChunk is also responsible (on the first chunk) for sending the
  1262. // HEADER response.
  1263. func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
  1264. if !rws.wroteHeader {
  1265. rws.writeHeader(200)
  1266. }
  1267. if !rws.sentHeader {
  1268. rws.sentHeader = true
  1269. var ctype, clen string // implicit ones, if we can calculate it
  1270. if rws.handlerDone && rws.snapHeader.Get("Content-Length") == "" {
  1271. clen = strconv.Itoa(len(p))
  1272. }
  1273. if rws.snapHeader.Get("Content-Type") == "" {
  1274. ctype = http.DetectContentType(p)
  1275. }
  1276. endStream := rws.handlerDone && len(p) == 0
  1277. rws.stream.conn.writeHeaders(rws.stream, &writeResHeaders{
  1278. streamID: rws.stream.id,
  1279. httpResCode: rws.status,
  1280. h: rws.snapHeader,
  1281. endStream: endStream,
  1282. contentType: ctype,
  1283. contentLength: clen,
  1284. }, rws.frameWriteCh)
  1285. if endStream {
  1286. return
  1287. }
  1288. }
  1289. if len(p) == 0 {
  1290. if rws.handlerDone {
  1291. err = rws.writeData(nil, true)
  1292. }
  1293. return
  1294. }
  1295. for len(p) > 0 {
  1296. chunk := p
  1297. if len(chunk) > handlerChunkWriteSize {
  1298. chunk = chunk[:handlerChunkWriteSize]
  1299. }
  1300. allowedSize := rws.stream.flow.wait(int32(len(chunk)))
  1301. if allowedSize == 0 {
  1302. return n, errStreamBroken
  1303. }
  1304. chunk = chunk[:allowedSize]
  1305. p = p[len(chunk):]
  1306. isFinal := rws.handlerDone && len(p) == 0
  1307. err = rws.writeData(chunk, isFinal)
  1308. if err != nil {
  1309. break
  1310. }
  1311. n += len(chunk)
  1312. }
  1313. return
  1314. }
  1315. func (w *responseWriter) Flush() {
  1316. rws := w.rws
  1317. if rws == nil {
  1318. panic("Header called after Handler finished")
  1319. }
  1320. if rws.bw.Buffered() > 0 {
  1321. if err := rws.bw.Flush(); err != nil {
  1322. // Ignore the error. The frame writer already knows.
  1323. return
  1324. }
  1325. } else {
  1326. // The bufio.Writer won't call chunkWriter.Write
  1327. // (writeChunk with zero bytes, so we have to do it
  1328. // ourselves to force the HTTP response header and/or
  1329. // final DATA frame (with END_STREAM) to be sent.
  1330. rws.writeChunk(nil)
  1331. }
  1332. }
  1333. func (w *responseWriter) CloseNotify() <-chan bool {
  1334. rws := w.rws
  1335. if rws == nil {
  1336. panic("CloseNotify called after Handler finished")
  1337. }
  1338. rws.closeNotifierMu.Lock()
  1339. ch := rws.closeNotifierCh
  1340. if ch == nil {
  1341. ch = make(chan bool, 1)
  1342. rws.closeNotifierCh = ch
  1343. go func() {
  1344. rws.stream.cw.Wait() // wait for close
  1345. ch <- true
  1346. }()
  1347. }
  1348. rws.closeNotifierMu.Unlock()
  1349. return ch
  1350. }
  1351. func (w *responseWriter) Header() http.Header {
  1352. rws := w.rws
  1353. if rws == nil {
  1354. panic("Header called after Handler finished")
  1355. }
  1356. if rws.handlerHeader == nil {
  1357. rws.handlerHeader = make(http.Header)
  1358. }
  1359. return rws.handlerHeader
  1360. }
  1361. func (w *responseWriter) WriteHeader(code int) {
  1362. rws := w.rws
  1363. if rws == nil {
  1364. panic("WriteHeader called after Handler finished")
  1365. }
  1366. rws.writeHeader(code)
  1367. }
  1368. func (rws *responseWriterState) writeHeader(code int) {
  1369. if !rws.wroteHeader {
  1370. rws.wroteHeader = true
  1371. rws.status = code
  1372. if len(rws.handlerHeader) > 0 {
  1373. rws.snapHeader = cloneHeader(rws.handlerHeader)
  1374. }
  1375. }
  1376. }
  1377. func cloneHeader(h http.Header) http.Header {
  1378. h2 := make(http.Header, len(h))
  1379. for k, vv := range h {
  1380. vv2 := make([]string, len(vv))
  1381. copy(vv2, vv)
  1382. h2[k] = vv2
  1383. }
  1384. return h2
  1385. }
  1386. // The Life Of A Write is like this:
  1387. //
  1388. // * Handler calls w.Write or w.WriteString ->
  1389. // * -> rws.bw (*bufio.Writer) ->
  1390. // * (Handler migth call Flush)
  1391. // * -> chunkWriter{rws}
  1392. // * -> responseWriterState.writeChunk(p []byte)
  1393. // * -> responseWriterState.writeChunk (most of the magic; see comment there)
  1394. func (w *responseWriter) Write(p []byte) (n int, err error) {
  1395. return w.write(len(p), p, "")
  1396. }
  1397. func (w *responseWriter) WriteString(s string) (n int, err error) {
  1398. return w.write(len(s), nil, s)
  1399. }
  1400. // either dataB or dataS is non-zero.
  1401. func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  1402. rws := w.rws
  1403. if rws == nil {
  1404. panic("Write called after Handler finished")
  1405. }
  1406. if !rws.wroteHeader {
  1407. w.WriteHeader(200)
  1408. }
  1409. if dataB != nil {
  1410. return rws.bw.Write(dataB)
  1411. } else {
  1412. return rws.bw.WriteString(dataS)
  1413. }
  1414. }
  1415. func (w *responseWriter) handlerDone() {
  1416. rws := w.rws
  1417. if rws == nil {
  1418. panic("handlerDone called twice")
  1419. }
  1420. rws.handlerDone = true
  1421. w.Flush()
  1422. w.rws = nil
  1423. responseWriterStatePool.Put(rws)
  1424. }