server.go 45 KB

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