server.go 47 KB

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