server.go 45 KB

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