server.go 51 KB

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