server.go 42 KB

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