server.go 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  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.writeFrameFromHandler(frameWriteMsg{
  503. write: writeDataFrame,
  504. cost: uint32(len(data.p)),
  505. stream: stream,
  506. endStream: data.end,
  507. v: data,
  508. done: ch,
  509. })
  510. select {
  511. case err := <-ch:
  512. return err
  513. case <-sc.doneServing:
  514. return errClientDisconnected
  515. }
  516. }
  517. // writeFrameFromHandler sends wm to sc.wantWriteFrameCh, but aborts
  518. // if the connection has gone away.
  519. //
  520. // This must not be run from the serve goroutine itself, else it might
  521. // deadlock writing to sc.wantWriteFrameCh (which is only mildly
  522. // buffered and is read by serve itself). If you're on the serve
  523. // goroutine, call writeFrame instead.
  524. func (sc *serverConn) writeFrameFromHandler(wm frameWriteMsg) {
  525. sc.serveG.checkNotOn() // NOT
  526. select {
  527. case sc.wantWriteFrameCh <- wm:
  528. case <-sc.doneServing:
  529. // Client has closed their connection to the server.
  530. }
  531. }
  532. // writeFrame either sends wm to the writeFrames goroutine, or
  533. // enqueues it for the future (with no pushback; the serve goroutine
  534. // never blocks!), for sending when the currently-being-written frame
  535. // is done writing.
  536. //
  537. // If you're not on the serve goroutine, use writeFrame instead.
  538. func (sc *serverConn) writeFrame(wm frameWriteMsg) {
  539. sc.serveG.check()
  540. // Fast path for common case:
  541. if !sc.writingFrame {
  542. sc.startFrameWrite(wm)
  543. return
  544. }
  545. sc.writeSched.add(wm)
  546. }
  547. // startFrameWrite starts a goroutine to write wm (in a separate
  548. // goroutine since that might block on the network), and updates the
  549. // serve goroutine's state about the world, updated from info in wm.
  550. func (sc *serverConn) startFrameWrite(wm frameWriteMsg) {
  551. sc.serveG.check()
  552. if sc.writingFrame {
  553. panic("internal error: can only be writing one frame at a time")
  554. }
  555. st := wm.stream
  556. if st != nil {
  557. switch st.state {
  558. case stateHalfClosedLocal:
  559. panic("internal error: attempt to send frame on half-closed-local stream")
  560. case stateClosed:
  561. if st.sentReset || st.gotReset {
  562. // Skip this frame. But fake the frame write to reschedule:
  563. sc.wroteFrameCh <- struct{}{}
  564. return
  565. }
  566. panic("internal error: attempt to send a frame on a closed stream")
  567. }
  568. }
  569. sc.writingFrame = true
  570. sc.needsFrameFlush = true
  571. if wm.endStream {
  572. if st == nil {
  573. panic("nil stream with endStream set")
  574. }
  575. switch st.state {
  576. case stateOpen:
  577. st.state = stateHalfClosedLocal
  578. case stateHalfClosedRemote:
  579. sc.closeStream(st, nil)
  580. }
  581. }
  582. go sc.writeFrameAsync(wm)
  583. }
  584. // scheduleFrameWrite tickles the frame writing scheduler.
  585. //
  586. // If a frame is already being written, nothing happens. This will be called again
  587. // when the frame is done being written.
  588. //
  589. // If a frame isn't being written we need to send one, the best frame
  590. // to send is selected, preferring first things that aren't
  591. // stream-specific (e.g. ACKing settings), and then finding the
  592. // highest priority stream.
  593. //
  594. // If a frame isn't being written and there's nothing else to send, we
  595. // flush the write buffer.
  596. func (sc *serverConn) scheduleFrameWrite() {
  597. sc.serveG.check()
  598. if sc.writingFrame {
  599. return
  600. }
  601. if sc.needToSendGoAway {
  602. sc.needToSendGoAway = false
  603. sc.startFrameWrite(frameWriteMsg{
  604. write: writeGoAwayFrame,
  605. v: &goAwayParams{
  606. maxStreamID: sc.maxStreamID,
  607. code: sc.goAwayCode,
  608. },
  609. })
  610. return
  611. }
  612. if sc.writeSched.empty() && sc.needsFrameFlush {
  613. sc.startFrameWrite(frameWriteMsg{write: flushFrameWriter})
  614. sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
  615. return
  616. }
  617. if sc.inGoAway {
  618. // No more frames after we've sent GOAWAY.
  619. return
  620. }
  621. if sc.needToSendSettingsAck {
  622. sc.needToSendSettingsAck = false
  623. sc.startFrameWrite(frameWriteMsg{write: writeSettingsAck})
  624. return
  625. }
  626. if sc.writeSched.empty() {
  627. return
  628. }
  629. // TODO: if wm is a data frame, make sure it's not too big
  630. // (because a SETTINGS frame changed our max frame size while
  631. // a stream was open and writing) and cut it up into smaller
  632. // bits.
  633. sc.startFrameWrite(sc.writeSched.take())
  634. }
  635. func (sc *serverConn) goAway(code ErrCode) {
  636. sc.serveG.check()
  637. if sc.inGoAway {
  638. return
  639. }
  640. if code != ErrCodeNo {
  641. sc.shutDownIn(250 * time.Millisecond)
  642. } else {
  643. // TODO: configurable
  644. sc.shutDownIn(1 * time.Second)
  645. }
  646. sc.inGoAway = true
  647. sc.needToSendGoAway = true
  648. sc.goAwayCode = code
  649. sc.scheduleFrameWrite()
  650. }
  651. func (sc *serverConn) shutDownIn(d time.Duration) {
  652. sc.serveG.check()
  653. sc.shutdownTimer = time.NewTimer(d)
  654. sc.shutdownTimerCh = sc.shutdownTimer.C
  655. }
  656. func (sc *serverConn) resetStream(se StreamError) {
  657. sc.serveG.check()
  658. st, ok := sc.streams[se.StreamID]
  659. if !ok {
  660. panic("internal package error; resetStream called on non-existent stream")
  661. }
  662. sc.writeFrame(frameWriteMsg{
  663. write: writeRSTStreamFrame,
  664. v: &se,
  665. })
  666. st.sentReset = true
  667. sc.closeStream(st, se)
  668. }
  669. // curHeaderStreamID returns the stream ID of the header block we're
  670. // currently in the middle of reading. If this returns non-zero, the
  671. // next frame must be a CONTINUATION with this stream id.
  672. func (sc *serverConn) curHeaderStreamID() uint32 {
  673. sc.serveG.check()
  674. st := sc.req.stream
  675. if st == nil {
  676. return 0
  677. }
  678. return st.id
  679. }
  680. // processFrameFromReader processes the serve loop's read from readFrameCh from the
  681. // frame-reading goroutine.
  682. // processFrameFromReader returns whether the connection should be kept open.
  683. func (sc *serverConn) processFrameFromReader(fg frameAndGate, fgValid bool) bool {
  684. sc.serveG.check()
  685. var clientGone bool
  686. var err error
  687. if !fgValid {
  688. err = <-sc.readFrameErrCh
  689. if err == ErrFrameTooLarge {
  690. sc.goAway(ErrCodeFrameSize)
  691. return true // goAway will close the loop
  692. }
  693. clientGone = err == io.EOF || strings.Contains(err.Error(), "use of closed network connection")
  694. if clientGone {
  695. // TODO: could we also get into this state if
  696. // the peer does a half close
  697. // (e.g. CloseWrite) because they're done
  698. // sending frames but they're still wanting
  699. // our open replies? Investigate.
  700. return false
  701. }
  702. }
  703. if fgValid {
  704. f := fg.f
  705. sc.vlogf("got %v: %#v", f.Header(), f)
  706. err = sc.processFrame(f)
  707. fg.g.Done() // unblock the readFrames goroutine
  708. if err == nil {
  709. return true
  710. }
  711. }
  712. switch ev := err.(type) {
  713. case StreamError:
  714. sc.resetStream(ev)
  715. return true
  716. case goAwayFlowError:
  717. sc.goAway(ErrCodeFlowControl)
  718. return true
  719. case ConnectionError:
  720. sc.logf("%v: %v", sc.conn.RemoteAddr(), ev)
  721. sc.goAway(ErrCode(ev))
  722. return true // goAway will handle shutdown
  723. default:
  724. if !fgValid {
  725. sc.logf("disconnecting; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
  726. } else {
  727. sc.logf("disconnection due to other error: %v", err)
  728. }
  729. }
  730. return false
  731. }
  732. func (sc *serverConn) processFrame(f Frame) error {
  733. sc.serveG.check()
  734. // First frame received must be SETTINGS.
  735. if !sc.sawFirstSettings {
  736. if _, ok := f.(*SettingsFrame); !ok {
  737. return ConnectionError(ErrCodeProtocol)
  738. }
  739. sc.sawFirstSettings = true
  740. }
  741. if s := sc.curHeaderStreamID(); s != 0 {
  742. if cf, ok := f.(*ContinuationFrame); !ok {
  743. return ConnectionError(ErrCodeProtocol)
  744. } else if cf.Header().StreamID != s {
  745. return ConnectionError(ErrCodeProtocol)
  746. }
  747. }
  748. switch f := f.(type) {
  749. case *SettingsFrame:
  750. return sc.processSettings(f)
  751. case *HeadersFrame:
  752. return sc.processHeaders(f)
  753. case *ContinuationFrame:
  754. return sc.processContinuation(f)
  755. case *WindowUpdateFrame:
  756. return sc.processWindowUpdate(f)
  757. case *PingFrame:
  758. return sc.processPing(f)
  759. case *DataFrame:
  760. return sc.processData(f)
  761. case *RSTStreamFrame:
  762. return sc.processResetStream(f)
  763. default:
  764. log.Printf("Ignoring frame: %v", f.Header())
  765. return nil
  766. }
  767. }
  768. func (sc *serverConn) processPing(f *PingFrame) error {
  769. sc.serveG.check()
  770. if f.Flags.Has(FlagSettingsAck) {
  771. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  772. // containing this flag."
  773. return nil
  774. }
  775. if f.StreamID != 0 {
  776. // "PING frames are not associated with any individual
  777. // stream. If a PING frame is received with a stream
  778. // identifier field value other than 0x0, the recipient MUST
  779. // respond with a connection error (Section 5.4.1) of type
  780. // PROTOCOL_ERROR."
  781. return ConnectionError(ErrCodeProtocol)
  782. }
  783. sc.writeFrame(frameWriteMsg{
  784. write: writePingAck,
  785. v: f,
  786. })
  787. return nil
  788. }
  789. func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  790. sc.serveG.check()
  791. switch {
  792. case f.StreamID != 0: // stream-level flow control
  793. st := sc.streams[f.StreamID]
  794. if st == nil {
  795. // "WINDOW_UPDATE can be sent by a peer that has sent a
  796. // frame bearing the END_STREAM flag. This means that a
  797. // receiver could receive a WINDOW_UPDATE frame on a "half
  798. // closed (remote)" or "closed" stream. A receiver MUST
  799. // NOT treat this as an error, see Section 5.1."
  800. return nil
  801. }
  802. if !st.flow.add(int32(f.Increment)) {
  803. return StreamError{f.StreamID, ErrCodeFlowControl}
  804. }
  805. default: // connection-level flow control
  806. if !sc.flow.add(int32(f.Increment)) {
  807. return goAwayFlowError{}
  808. }
  809. }
  810. return nil
  811. }
  812. func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
  813. sc.serveG.check()
  814. if sc.state(f.StreamID) == stateIdle {
  815. // 6.4 "RST_STREAM frames MUST NOT be sent for a
  816. // stream in the "idle" state. If a RST_STREAM frame
  817. // identifying an idle stream is received, the
  818. // recipient MUST treat this as a connection error
  819. // (Section 5.4.1) of type PROTOCOL_ERROR.
  820. return ConnectionError(ErrCodeProtocol)
  821. }
  822. st, ok := sc.streams[f.StreamID]
  823. if ok {
  824. st.gotReset = true
  825. sc.closeStream(st, StreamError{f.StreamID, f.ErrCode})
  826. }
  827. return nil
  828. }
  829. func (sc *serverConn) closeStream(st *stream, err error) {
  830. sc.serveG.check()
  831. if st.state == stateIdle || st.state == stateClosed {
  832. panic("invariant")
  833. }
  834. st.state = stateClosed
  835. sc.curOpenStreams--
  836. delete(sc.streams, st.id)
  837. st.flow.close()
  838. if p := st.body; p != nil {
  839. p.Close(err)
  840. }
  841. st.cw.Close() // signals Handler's CloseNotifier goroutine (if any) to send
  842. }
  843. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  844. sc.serveG.check()
  845. if f.IsAck() {
  846. // TODO: do we need to do anything?
  847. // We might want to keep track of which settings we've sent
  848. // vs which settings the client has ACK'd, so we know when to be
  849. // strict. Or at least keep track of the count of
  850. // our SETTINGS send count vs their ACK count. If they're equal,
  851. // then we both have the same view of the world and we can be
  852. // stricter in some cases. But currently we don't send SETTINGS
  853. // at runtime other than the initial SETTINGS.
  854. return nil
  855. }
  856. if err := f.ForeachSetting(sc.processSetting); err != nil {
  857. return err
  858. }
  859. sc.needToSendSettingsAck = true
  860. sc.scheduleFrameWrite()
  861. return nil
  862. }
  863. func (sc *serverConn) processSetting(s Setting) error {
  864. sc.serveG.check()
  865. if err := s.Valid(); err != nil {
  866. return err
  867. }
  868. sc.vlogf("processing setting %v", s)
  869. switch s.ID {
  870. case SettingHeaderTableSize:
  871. sc.headerTableSize = s.Val
  872. sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
  873. case SettingEnablePush:
  874. sc.pushEnabled = s.Val != 0
  875. case SettingMaxConcurrentStreams:
  876. sc.clientMaxStreams = s.Val
  877. case SettingInitialWindowSize:
  878. return sc.processSettingInitialWindowSize(s.Val)
  879. case SettingMaxFrameSize:
  880. sc.maxWriteFrameSize = s.Val
  881. case SettingMaxHeaderListSize:
  882. sc.maxHeaderListSize = s.Val
  883. default:
  884. // Unknown setting: "An endpoint that receives a SETTINGS
  885. // frame with any unknown or unsupported identifier MUST
  886. // ignore that setting."
  887. }
  888. return nil
  889. }
  890. func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  891. sc.serveG.check()
  892. // Note: val already validated to be within range by
  893. // processSetting's Valid call.
  894. // "A SETTINGS frame can alter the initial flow control window
  895. // size for all current streams. When the value of
  896. // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  897. // adjust the size of all stream flow control windows that it
  898. // maintains by the difference between the new value and the
  899. // old value."
  900. old := sc.initialWindowSize
  901. sc.initialWindowSize = int32(val)
  902. growth := sc.initialWindowSize - old // may be negative
  903. for _, st := range sc.streams {
  904. if !st.flow.add(growth) {
  905. // 6.9.2 Initial Flow Control Window Size
  906. // "An endpoint MUST treat a change to
  907. // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  908. // control window to exceed the maximum size as a
  909. // connection error (Section 5.4.1) of type
  910. // FLOW_CONTROL_ERROR."
  911. return ConnectionError(ErrCodeFlowControl)
  912. }
  913. }
  914. return nil
  915. }
  916. func (sc *serverConn) processData(f *DataFrame) error {
  917. sc.serveG.check()
  918. // "If a DATA frame is received whose stream is not in "open"
  919. // or "half closed (local)" state, the recipient MUST respond
  920. // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  921. id := f.Header().StreamID
  922. st, ok := sc.streams[id]
  923. if !ok || (st.state != stateOpen && st.state != stateHalfClosedLocal) {
  924. return StreamError{id, ErrCodeStreamClosed}
  925. }
  926. if st.body == nil {
  927. panic("internal error: should have a body in this state")
  928. }
  929. data := f.Data()
  930. // Sender sending more than they'd declared?
  931. if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  932. st.body.Close(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  933. return StreamError{id, ErrCodeStreamClosed}
  934. }
  935. if len(data) > 0 {
  936. // TODO: verify they're allowed to write with the flow control
  937. // window we'd advertised to them.
  938. wrote, err := st.body.Write(data)
  939. if err != nil {
  940. return StreamError{id, ErrCodeStreamClosed}
  941. }
  942. if wrote != len(data) {
  943. panic("internal error: bad Writer")
  944. }
  945. st.bodyBytes += int64(len(data))
  946. }
  947. if f.StreamEnded() {
  948. if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  949. st.body.Close(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
  950. st.declBodyBytes, st.bodyBytes))
  951. } else {
  952. st.body.Close(io.EOF)
  953. }
  954. switch st.state {
  955. case stateOpen:
  956. st.state = stateHalfClosedRemote
  957. case stateHalfClosedLocal:
  958. st.state = stateClosed
  959. }
  960. }
  961. return nil
  962. }
  963. func (sc *serverConn) processHeaders(f *HeadersFrame) error {
  964. sc.serveG.check()
  965. id := f.Header().StreamID
  966. if sc.inGoAway {
  967. // Ignore.
  968. return nil
  969. }
  970. // http://http2.github.io/http2-spec/#rfc.section.5.1.1
  971. if id%2 != 1 || id <= sc.maxStreamID || sc.req.stream != nil {
  972. // Streams initiated by a client MUST use odd-numbered
  973. // stream identifiers. [...] The identifier of a newly
  974. // established stream MUST be numerically greater than all
  975. // streams that the initiating endpoint has opened or
  976. // reserved. [...] An endpoint that receives an unexpected
  977. // stream identifier MUST respond with a connection error
  978. // (Section 5.4.1) of type PROTOCOL_ERROR.
  979. return ConnectionError(ErrCodeProtocol)
  980. }
  981. if id > sc.maxStreamID {
  982. sc.maxStreamID = id
  983. }
  984. st := &stream{
  985. conn: sc,
  986. id: id,
  987. state: stateOpen,
  988. flow: newFlow(sc.initialWindowSize),
  989. }
  990. st.cw.Init() // make Cond use its Mutex, without heap-promoting them separately
  991. if f.StreamEnded() {
  992. st.state = stateHalfClosedRemote
  993. }
  994. sc.streams[id] = st
  995. sc.curOpenStreams++
  996. sc.req = requestParam{
  997. stream: st,
  998. header: make(http.Header),
  999. }
  1000. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  1001. }
  1002. func (sc *serverConn) processContinuation(f *ContinuationFrame) error {
  1003. sc.serveG.check()
  1004. st := sc.streams[f.Header().StreamID]
  1005. if st == nil || sc.curHeaderStreamID() != st.id {
  1006. return ConnectionError(ErrCodeProtocol)
  1007. }
  1008. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  1009. }
  1010. func (sc *serverConn) processHeaderBlockFragment(st *stream, frag []byte, end bool) error {
  1011. sc.serveG.check()
  1012. if _, err := sc.hpackDecoder.Write(frag); err != nil {
  1013. // TODO: convert to stream error I assume?
  1014. return err
  1015. }
  1016. if !end {
  1017. return nil
  1018. }
  1019. if err := sc.hpackDecoder.Close(); err != nil {
  1020. // TODO: convert to stream error I assume?
  1021. return err
  1022. }
  1023. defer sc.resetPendingRequest()
  1024. if sc.curOpenStreams > sc.advMaxStreams {
  1025. // Too many open streams.
  1026. // TODO: which error code here? Using ErrCodeProtocol for now.
  1027. // https://github.com/http2/http2-spec/issues/649
  1028. return StreamError{st.id, ErrCodeProtocol}
  1029. }
  1030. rw, req, err := sc.newWriterAndRequest()
  1031. if err != nil {
  1032. return err
  1033. }
  1034. st.body = req.Body.(*requestBody).pipe // may be nil
  1035. st.declBodyBytes = req.ContentLength
  1036. go sc.runHandler(rw, req)
  1037. return nil
  1038. }
  1039. // resetPendingRequest zeros out all state related to a HEADERS frame
  1040. // and its zero or more CONTINUATION frames sent to start a new
  1041. // request.
  1042. func (sc *serverConn) resetPendingRequest() {
  1043. sc.serveG.check()
  1044. sc.req = requestParam{}
  1045. }
  1046. func (sc *serverConn) newWriterAndRequest() (*responseWriter, *http.Request, error) {
  1047. sc.serveG.check()
  1048. rp := &sc.req
  1049. if rp.invalidHeader || rp.method == "" || rp.path == "" ||
  1050. (rp.scheme != "https" && rp.scheme != "http") {
  1051. // See 8.1.2.6 Malformed Requests and Responses:
  1052. //
  1053. // Malformed requests or responses that are detected
  1054. // MUST be treated as a stream error (Section 5.4.2)
  1055. // of type PROTOCOL_ERROR."
  1056. //
  1057. // 8.1.2.3 Request Pseudo-Header Fields
  1058. // "All HTTP/2 requests MUST include exactly one valid
  1059. // value for the :method, :scheme, and :path
  1060. // pseudo-header fields"
  1061. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1062. }
  1063. var tlsState *tls.ConnectionState // make this non-nil if https
  1064. if rp.scheme == "https" {
  1065. tlsState = &tls.ConnectionState{}
  1066. if tc, ok := sc.conn.(*tls.Conn); ok {
  1067. *tlsState = tc.ConnectionState()
  1068. if tlsState.Version < tls.VersionTLS12 {
  1069. // 9.2 Use of TLS Features
  1070. // An implementation of HTTP/2 over TLS MUST use TLS
  1071. // 1.2 or higher with the restrictions on feature set
  1072. // and cipher suite described in this section. Due to
  1073. // implementation limitations, it might not be
  1074. // possible to fail TLS negotiation. An endpoint MUST
  1075. // immediately terminate an HTTP/2 connection that
  1076. // does not meet the TLS requirements described in
  1077. // this section with a connection error (Section
  1078. // 5.4.1) of type INADEQUATE_SECURITY.
  1079. return nil, nil, ConnectionError(ErrCodeInadequateSecurity)
  1080. }
  1081. // TODO: verify cipher suites. (9.2.1, 9.2.2)
  1082. }
  1083. }
  1084. authority := rp.authority
  1085. if authority == "" {
  1086. authority = rp.header.Get("Host")
  1087. }
  1088. needsContinue := rp.header.Get("Expect") == "100-continue"
  1089. if needsContinue {
  1090. rp.header.Del("Expect")
  1091. }
  1092. bodyOpen := rp.stream.state == stateOpen
  1093. body := &requestBody{
  1094. stream: rp.stream,
  1095. needsContinue: needsContinue,
  1096. }
  1097. // TODO: handle asterisk '*' requests + test
  1098. url, err := url.ParseRequestURI(rp.path)
  1099. if err != nil {
  1100. // TODO: find the right error code?
  1101. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1102. }
  1103. req := &http.Request{
  1104. Method: rp.method,
  1105. URL: url,
  1106. RemoteAddr: sc.conn.RemoteAddr().String(),
  1107. Header: rp.header,
  1108. RequestURI: rp.path,
  1109. Proto: "HTTP/2.0",
  1110. ProtoMajor: 2,
  1111. ProtoMinor: 0,
  1112. TLS: tlsState,
  1113. Host: authority,
  1114. Body: body,
  1115. }
  1116. if bodyOpen {
  1117. body.pipe = &pipe{
  1118. b: buffer{buf: make([]byte, 65536)}, // TODO: share/remove
  1119. }
  1120. body.pipe.c.L = &body.pipe.m
  1121. if vv, ok := rp.header["Content-Length"]; ok {
  1122. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  1123. } else {
  1124. req.ContentLength = -1
  1125. }
  1126. }
  1127. rws := responseWriterStatePool.Get().(*responseWriterState)
  1128. bwSave := rws.bw
  1129. *rws = responseWriterState{} // zero all the fields
  1130. rws.bw = bwSave
  1131. rws.bw.Reset(chunkWriter{rws})
  1132. rws.stream = rp.stream
  1133. rws.req = req
  1134. rws.body = body
  1135. rws.frameWriteCh = make(chan error, 1)
  1136. rw := &responseWriter{rws: rws}
  1137. return rw, req, nil
  1138. }
  1139. // Run on its own goroutine.
  1140. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request) {
  1141. defer rw.handlerDone()
  1142. // TODO: catch panics like net/http.Server
  1143. sc.handler.ServeHTTP(rw, req)
  1144. }
  1145. // headerWriteReq is a request to write an HTTP response header from a server Handler.
  1146. type headerWriteReq struct {
  1147. stream *stream
  1148. httpResCode int
  1149. h http.Header // may be nil
  1150. endStream bool
  1151. contentType string
  1152. contentLength string
  1153. }
  1154. // called from handler goroutines.
  1155. // h may be nil.
  1156. func (sc *serverConn) writeHeaders(req headerWriteReq, tempCh chan error) {
  1157. sc.serveG.checkNotOn() // NOT on
  1158. var errc chan error
  1159. if req.h != nil {
  1160. // If there's a header map (which we don't own), so we have to block on
  1161. // waiting for this frame to be written, so an http.Flush mid-handler
  1162. // writes out the correct value of keys, before a handler later potentially
  1163. // mutates it.
  1164. errc = tempCh
  1165. }
  1166. sc.writeFrameFromHandler(frameWriteMsg{
  1167. write: writeHeadersFrame,
  1168. v: req,
  1169. stream: req.stream,
  1170. done: errc,
  1171. endStream: req.endStream,
  1172. })
  1173. if errc != nil {
  1174. select {
  1175. case <-errc:
  1176. // Ignore. Just for synchronization.
  1177. // Any error will be handled in the writing goroutine.
  1178. case <-sc.doneServing:
  1179. // Client has closed the connection.
  1180. }
  1181. }
  1182. }
  1183. // called from handler goroutines.
  1184. func (sc *serverConn) write100ContinueHeaders(st *stream) {
  1185. sc.writeFrameFromHandler(frameWriteMsg{
  1186. write: write100ContinueHeadersFrame,
  1187. v: st,
  1188. stream: st,
  1189. })
  1190. }
  1191. // called from handler goroutines
  1192. func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
  1193. if st == nil {
  1194. panic("no stream")
  1195. }
  1196. const maxUint32 = 2147483647
  1197. for n >= maxUint32 {
  1198. sc.writeFrameFromHandler(frameWriteMsg{
  1199. write: writeWindowUpdate,
  1200. v: windowUpdateReq{streamID: st.id, n: maxUint32},
  1201. stream: st,
  1202. })
  1203. n -= maxUint32
  1204. }
  1205. if n > 0 {
  1206. sc.writeFrameFromHandler(frameWriteMsg{
  1207. write: writeWindowUpdate,
  1208. v: windowUpdateReq{streamID: st.id, n: uint32(n)},
  1209. stream: st,
  1210. })
  1211. }
  1212. }
  1213. type requestBody struct {
  1214. stream *stream
  1215. closed bool
  1216. pipe *pipe // non-nil if we have a HTTP entity message body
  1217. needsContinue bool // need to send a 100-continue
  1218. }
  1219. func (b *requestBody) Close() error {
  1220. if b.pipe != nil {
  1221. b.pipe.Close(errClosedBody)
  1222. }
  1223. b.closed = true
  1224. return nil
  1225. }
  1226. func (b *requestBody) Read(p []byte) (n int, err error) {
  1227. if b.needsContinue {
  1228. b.needsContinue = false
  1229. b.stream.conn.write100ContinueHeaders(b.stream)
  1230. }
  1231. if b.pipe == nil {
  1232. return 0, io.EOF
  1233. }
  1234. n, err = b.pipe.Read(p)
  1235. if n > 0 {
  1236. b.stream.conn.sendWindowUpdate(b.stream, n)
  1237. }
  1238. return
  1239. }
  1240. // responseWriter is the http.ResponseWriter implementation. It's
  1241. // intentionally small (1 pointer wide) to minimize garbage. The
  1242. // responseWriterState pointer inside is zeroed at the end of a
  1243. // request (in handlerDone) and calls on the responseWriter thereafter
  1244. // simply crash (caller's mistake), but the much larger responseWriterState
  1245. // and buffers are reused between multiple requests.
  1246. type responseWriter struct {
  1247. rws *responseWriterState
  1248. }
  1249. // Optional http.ResponseWriter interfaces implemented.
  1250. var (
  1251. _ http.CloseNotifier = (*responseWriter)(nil)
  1252. _ http.Flusher = (*responseWriter)(nil)
  1253. _ stringWriter = (*responseWriter)(nil)
  1254. )
  1255. type responseWriterState struct {
  1256. // immutable within a request:
  1257. stream *stream
  1258. req *http.Request
  1259. body *requestBody // to close at end of request, if DATA frames didn't
  1260. // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
  1261. bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
  1262. // mutated by http.Handler goroutine:
  1263. handlerHeader http.Header // nil until called
  1264. snapHeader http.Header // snapshot of handlerHeader at WriteHeader time
  1265. status int // status code passed to WriteHeader
  1266. wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
  1267. sentHeader bool // have we sent the header frame?
  1268. handlerDone bool // handler has finished
  1269. curWrite dataWriteParams
  1270. frameWriteCh chan error // re-used whenever we need to block on a frame being written
  1271. closeNotifierMu sync.Mutex // guards closeNotifierCh
  1272. closeNotifierCh chan bool // nil until first used
  1273. }
  1274. func (rws *responseWriterState) writeData(p []byte, end bool) error {
  1275. rws.curWrite.streamID = rws.stream.id
  1276. rws.curWrite.p = p
  1277. rws.curWrite.end = end
  1278. return rws.stream.conn.writeData(rws.stream, &rws.curWrite, rws.frameWriteCh)
  1279. }
  1280. type chunkWriter struct{ rws *responseWriterState }
  1281. func (cw chunkWriter) Write(p []byte) (n int, err error) { return cw.rws.writeChunk(p) }
  1282. // writeChunk writes chunks from the bufio.Writer. But because
  1283. // bufio.Writer may bypass its chunking, sometimes p may be
  1284. // arbitrarily large.
  1285. //
  1286. // writeChunk is also responsible (on the first chunk) for sending the
  1287. // HEADER response.
  1288. func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
  1289. if !rws.wroteHeader {
  1290. rws.writeHeader(200)
  1291. }
  1292. if !rws.sentHeader {
  1293. rws.sentHeader = true
  1294. var ctype, clen string // implicit ones, if we can calculate it
  1295. if rws.handlerDone && rws.snapHeader.Get("Content-Length") == "" {
  1296. clen = strconv.Itoa(len(p))
  1297. }
  1298. if rws.snapHeader.Get("Content-Type") == "" {
  1299. ctype = http.DetectContentType(p)
  1300. }
  1301. endStream := rws.handlerDone && len(p) == 0
  1302. rws.stream.conn.writeHeaders(headerWriteReq{
  1303. stream: rws.stream,
  1304. httpResCode: rws.status,
  1305. h: rws.snapHeader,
  1306. endStream: endStream,
  1307. contentType: ctype,
  1308. contentLength: clen,
  1309. }, rws.frameWriteCh)
  1310. if endStream {
  1311. return
  1312. }
  1313. }
  1314. if len(p) == 0 {
  1315. if rws.handlerDone {
  1316. err = rws.writeData(nil, true)
  1317. }
  1318. return
  1319. }
  1320. for len(p) > 0 {
  1321. chunk := p
  1322. if len(chunk) > handlerChunkWriteSize {
  1323. chunk = chunk[:handlerChunkWriteSize]
  1324. }
  1325. allowedSize := rws.stream.flow.wait(int32(len(chunk)))
  1326. if allowedSize == 0 {
  1327. return n, errStreamBroken
  1328. }
  1329. chunk = chunk[:allowedSize]
  1330. p = p[len(chunk):]
  1331. isFinal := rws.handlerDone && len(p) == 0
  1332. err = rws.writeData(chunk, isFinal)
  1333. if err != nil {
  1334. break
  1335. }
  1336. n += len(chunk)
  1337. }
  1338. return
  1339. }
  1340. func (w *responseWriter) Flush() {
  1341. rws := w.rws
  1342. if rws == nil {
  1343. panic("Header called after Handler finished")
  1344. }
  1345. if rws.bw.Buffered() > 0 {
  1346. if err := rws.bw.Flush(); err != nil {
  1347. // Ignore the error. The frame writer already knows.
  1348. return
  1349. }
  1350. } else {
  1351. // The bufio.Writer won't call chunkWriter.Write
  1352. // (writeChunk with zero bytes, so we have to do it
  1353. // ourselves to force the HTTP response header and/or
  1354. // final DATA frame (with END_STREAM) to be sent.
  1355. rws.writeChunk(nil)
  1356. }
  1357. }
  1358. func (w *responseWriter) CloseNotify() <-chan bool {
  1359. rws := w.rws
  1360. if rws == nil {
  1361. panic("CloseNotify called after Handler finished")
  1362. }
  1363. rws.closeNotifierMu.Lock()
  1364. ch := rws.closeNotifierCh
  1365. if ch == nil {
  1366. ch = make(chan bool, 1)
  1367. rws.closeNotifierCh = ch
  1368. go func() {
  1369. rws.stream.cw.Wait() // wait for close
  1370. ch <- true
  1371. }()
  1372. }
  1373. rws.closeNotifierMu.Unlock()
  1374. return ch
  1375. }
  1376. func (w *responseWriter) Header() http.Header {
  1377. rws := w.rws
  1378. if rws == nil {
  1379. panic("Header called after Handler finished")
  1380. }
  1381. if rws.handlerHeader == nil {
  1382. rws.handlerHeader = make(http.Header)
  1383. }
  1384. return rws.handlerHeader
  1385. }
  1386. func (w *responseWriter) WriteHeader(code int) {
  1387. rws := w.rws
  1388. if rws == nil {
  1389. panic("WriteHeader called after Handler finished")
  1390. }
  1391. rws.writeHeader(code)
  1392. }
  1393. func (rws *responseWriterState) writeHeader(code int) {
  1394. if !rws.wroteHeader {
  1395. rws.wroteHeader = true
  1396. rws.status = code
  1397. if len(rws.handlerHeader) > 0 {
  1398. rws.snapHeader = cloneHeader(rws.handlerHeader)
  1399. }
  1400. }
  1401. }
  1402. func cloneHeader(h http.Header) http.Header {
  1403. h2 := make(http.Header, len(h))
  1404. for k, vv := range h {
  1405. vv2 := make([]string, len(vv))
  1406. copy(vv2, vv)
  1407. h2[k] = vv2
  1408. }
  1409. return h2
  1410. }
  1411. // The Life Of A Write is like this:
  1412. //
  1413. // * Handler calls w.Write or w.WriteString ->
  1414. // * -> rws.bw (*bufio.Writer) ->
  1415. // * (Handler migth call Flush)
  1416. // * -> chunkWriter{rws}
  1417. // * -> responseWriterState.writeChunk(p []byte)
  1418. // * -> responseWriterState.writeChunk (most of the magic; see comment there)
  1419. func (w *responseWriter) Write(p []byte) (n int, err error) {
  1420. return w.write(len(p), p, "")
  1421. }
  1422. func (w *responseWriter) WriteString(s string) (n int, err error) {
  1423. return w.write(len(s), nil, s)
  1424. }
  1425. // either dataB or dataS is non-zero.
  1426. func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  1427. rws := w.rws
  1428. if rws == nil {
  1429. panic("Write called after Handler finished")
  1430. }
  1431. if !rws.wroteHeader {
  1432. w.WriteHeader(200)
  1433. }
  1434. if dataB != nil {
  1435. return rws.bw.Write(dataB)
  1436. } else {
  1437. return rws.bw.WriteString(dataS)
  1438. }
  1439. }
  1440. func (w *responseWriter) handlerDone() {
  1441. rws := w.rws
  1442. if rws == nil {
  1443. panic("handlerDone called twice")
  1444. }
  1445. rws.handlerDone = true
  1446. w.Flush()
  1447. w.rws = nil
  1448. responseWriterStatePool.Put(rws)
  1449. }