server.go 50 KB

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