server.go 53 KB

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