server.go 45 KB

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