server.go 36 KB

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