server.go 45 KB

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