server.go 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206
  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. // TODO: replace all <-sc.doneServing with reads from the stream's cw
  5. // instead, and make sure that on close we close all open
  6. // streams. then remove doneServing?
  7. // TODO: re-audit GOAWAY support. Consider each incoming frame type and
  8. // whether it should be ignored during graceful shutdown.
  9. // TODO: disconnect idle clients. GFE seems to do 4 minutes. make
  10. // configurable? or maximum number of idle clients and remove the
  11. // oldest?
  12. // TODO: turn off the serve goroutine when idle, so
  13. // an idle conn only has the readFrames goroutine active. (which could
  14. // also be optimized probably to pin less memory in crypto/tls). This
  15. // would involve tracking when the serve goroutine is active (atomic
  16. // int32 read/CAS probably?) and starting it up when frames arrive,
  17. // and shutting it down when all handlers exit. the occasional PING
  18. // packets could use time.AfterFunc to call sc.wakeStartServeLoop()
  19. // (which is a no-op if already running) and then queue the PING write
  20. // as normal. The serve loop would then exit in most cases (if no
  21. // Handlers running) and not be woken up again until the PING packet
  22. // returns.
  23. // TODO (maybe): add a mechanism for Handlers to going into
  24. // half-closed-local mode (rw.(io.Closer) test?) but not exit their
  25. // handler, and continue to be able to read from the
  26. // Request.Body. This would be a somewhat semantic change from HTTP/1
  27. // (or at least what we expose in net/http), so I'd probably want to
  28. // add it there too. For now, this package says that returning from
  29. // the Handler ServeHTTP function means you're both done reading and
  30. // done writing, without a way to stop just one or the other.
  31. package http2
  32. import (
  33. "bufio"
  34. "bytes"
  35. "crypto/tls"
  36. "errors"
  37. "fmt"
  38. "io"
  39. "log"
  40. "net"
  41. "net/http"
  42. "net/textproto"
  43. "net/url"
  44. "os"
  45. "reflect"
  46. "runtime"
  47. "strconv"
  48. "strings"
  49. "sync"
  50. "time"
  51. "golang.org/x/net/http2/hpack"
  52. )
  53. const (
  54. prefaceTimeout = 10 * time.Second
  55. firstSettingsTimeout = 2 * time.Second // should be in-flight with preface anyway
  56. handlerChunkWriteSize = 4 << 10
  57. defaultMaxStreams = 250 // TODO: make this 100 as the GFE seems to?
  58. )
  59. var (
  60. errClientDisconnected = errors.New("client disconnected")
  61. errClosedBody = errors.New("body closed by handler")
  62. errHandlerComplete = errors.New("http2: request body closed due to handler exiting")
  63. errStreamClosed = errors.New("http2: stream closed")
  64. )
  65. var responseWriterStatePool = sync.Pool{
  66. New: func() interface{} {
  67. rws := &responseWriterState{}
  68. rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize)
  69. return rws
  70. },
  71. }
  72. // Test hooks.
  73. var (
  74. testHookOnConn func()
  75. testHookGetServerConn func(*serverConn)
  76. testHookOnPanicMu *sync.Mutex // nil except in tests
  77. testHookOnPanic func(sc *serverConn, panicVal interface{}) (rePanic bool)
  78. )
  79. // Server is an HTTP/2 server.
  80. type Server struct {
  81. // MaxHandlers limits the number of http.Handler ServeHTTP goroutines
  82. // which may run at a time over all connections.
  83. // Negative or zero no limit.
  84. // TODO: implement
  85. MaxHandlers int
  86. // MaxConcurrentStreams optionally specifies the number of
  87. // concurrent streams that each client may have open at a
  88. // time. This is unrelated to the number of http.Handler goroutines
  89. // which may be active globally, which is MaxHandlers.
  90. // If zero, MaxConcurrentStreams defaults to at least 100, per
  91. // the HTTP/2 spec's recommendations.
  92. MaxConcurrentStreams uint32
  93. // MaxReadFrameSize optionally specifies the largest frame
  94. // this server is willing to read. A valid value is between
  95. // 16k and 16M, inclusive. If zero or otherwise invalid, a
  96. // default value is used.
  97. MaxReadFrameSize uint32
  98. // PermitProhibitedCipherSuites, if true, permits the use of
  99. // cipher suites prohibited by the HTTP/2 spec.
  100. PermitProhibitedCipherSuites bool
  101. }
  102. func (s *Server) maxReadFrameSize() uint32 {
  103. if v := s.MaxReadFrameSize; v >= minMaxFrameSize && v <= maxFrameSize {
  104. return v
  105. }
  106. return defaultMaxReadFrameSize
  107. }
  108. func (s *Server) maxConcurrentStreams() uint32 {
  109. if v := s.MaxConcurrentStreams; v > 0 {
  110. return v
  111. }
  112. return defaultMaxStreams
  113. }
  114. // ConfigureServer adds HTTP/2 support to a net/http Server.
  115. //
  116. // The configuration conf may be nil.
  117. //
  118. // ConfigureServer must be called before s begins serving.
  119. func ConfigureServer(s *http.Server, conf *Server) error {
  120. if conf == nil {
  121. conf = new(Server)
  122. }
  123. if s.TLSConfig == nil {
  124. s.TLSConfig = new(tls.Config)
  125. } else if s.TLSConfig.CipherSuites != nil {
  126. // If they already provided a CipherSuite list, return
  127. // an error if it has a bad order or is missing
  128. // ECDHE_RSA_WITH_AES_128_GCM_SHA256.
  129. const requiredCipher = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  130. haveRequired := false
  131. sawBad := false
  132. for i, cs := range s.TLSConfig.CipherSuites {
  133. if cs == requiredCipher {
  134. haveRequired = true
  135. }
  136. if isBadCipher(cs) {
  137. sawBad = true
  138. } else if sawBad {
  139. return fmt.Errorf("http2: TLSConfig.CipherSuites index %d contains an HTTP/2-approved cipher suite (%#04x), but it comes after unapproved cipher suites. With this configuration, clients that don't support previous, approved cipher suites may be given an unapproved one and reject the connection.", i, cs)
  140. }
  141. }
  142. if !haveRequired {
  143. return fmt.Errorf("http2: TLSConfig.CipherSuites is missing HTTP/2-required TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256")
  144. }
  145. }
  146. // Note: not setting MinVersion to tls.VersionTLS12,
  147. // as we don't want to interfere with HTTP/1.1 traffic
  148. // on the user's server. We enforce TLS 1.2 later once
  149. // we accept a connection. Ideally this should be done
  150. // during next-proto selection, but using TLS <1.2 with
  151. // HTTP/2 is still the client's bug.
  152. s.TLSConfig.PreferServerCipherSuites = true
  153. haveNPN := false
  154. for _, p := range s.TLSConfig.NextProtos {
  155. if p == NextProtoTLS {
  156. haveNPN = true
  157. break
  158. }
  159. }
  160. if !haveNPN {
  161. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, NextProtoTLS)
  162. }
  163. // h2-14 is temporary (as of 2015-03-05) while we wait for all browsers
  164. // to switch to "h2".
  165. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, "h2-14")
  166. if s.TLSNextProto == nil {
  167. s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
  168. }
  169. protoHandler := func(hs *http.Server, c *tls.Conn, h http.Handler) {
  170. if testHookOnConn != nil {
  171. testHookOnConn()
  172. }
  173. conf.handleConn(hs, c, h)
  174. }
  175. s.TLSNextProto[NextProtoTLS] = protoHandler
  176. s.TLSNextProto["h2-14"] = protoHandler // temporary; see above.
  177. return nil
  178. }
  179. func (srv *Server) handleConn(hs *http.Server, c net.Conn, h http.Handler) {
  180. sc := &serverConn{
  181. srv: srv,
  182. hs: hs,
  183. conn: c,
  184. remoteAddrStr: c.RemoteAddr().String(),
  185. bw: newBufferedWriter(c),
  186. handler: h,
  187. streams: make(map[uint32]*stream),
  188. readFrameCh: make(chan readFrameResult),
  189. wantWriteFrameCh: make(chan frameWriteMsg, 8),
  190. wroteFrameCh: make(chan frameWriteResult, 1), // buffered; one send in writeFrameAsync
  191. bodyReadCh: make(chan bodyReadMsg), // buffering doesn't matter either way
  192. doneServing: make(chan struct{}),
  193. advMaxStreams: srv.maxConcurrentStreams(),
  194. writeSched: writeScheduler{
  195. maxFrameSize: initialMaxFrameSize,
  196. },
  197. initialWindowSize: initialWindowSize,
  198. headerTableSize: initialHeaderTableSize,
  199. serveG: newGoroutineLock(),
  200. pushEnabled: true,
  201. }
  202. sc.flow.add(initialWindowSize)
  203. sc.inflow.add(initialWindowSize)
  204. sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
  205. sc.hpackDecoder = hpack.NewDecoder(initialHeaderTableSize, nil)
  206. sc.hpackDecoder.SetMaxStringLength(sc.maxHeaderStringLen())
  207. fr := NewFramer(sc.bw, c)
  208. fr.SetMaxReadFrameSize(srv.maxReadFrameSize())
  209. sc.framer = fr
  210. if tc, ok := c.(*tls.Conn); ok {
  211. sc.tlsState = new(tls.ConnectionState)
  212. *sc.tlsState = tc.ConnectionState()
  213. // 9.2 Use of TLS Features
  214. // An implementation of HTTP/2 over TLS MUST use TLS
  215. // 1.2 or higher with the restrictions on feature set
  216. // and cipher suite described in this section. Due to
  217. // implementation limitations, it might not be
  218. // possible to fail TLS negotiation. An endpoint MUST
  219. // immediately terminate an HTTP/2 connection that
  220. // does not meet the TLS requirements described in
  221. // this section with a connection error (Section
  222. // 5.4.1) of type INADEQUATE_SECURITY.
  223. if sc.tlsState.Version < tls.VersionTLS12 {
  224. sc.rejectConn(ErrCodeInadequateSecurity, "TLS version too low")
  225. return
  226. }
  227. if sc.tlsState.ServerName == "" {
  228. // Client must use SNI, but we don't enforce that anymore,
  229. // since it was causing problems when connecting to bare IP
  230. // addresses during development.
  231. //
  232. // TODO: optionally enforce? Or enforce at the time we receive
  233. // a new request, and verify the the ServerName matches the :authority?
  234. // But that precludes proxy situations, perhaps.
  235. //
  236. // So for now, do nothing here again.
  237. }
  238. if !srv.PermitProhibitedCipherSuites && isBadCipher(sc.tlsState.CipherSuite) {
  239. // "Endpoints MAY choose to generate a connection error
  240. // (Section 5.4.1) of type INADEQUATE_SECURITY if one of
  241. // the prohibited cipher suites are negotiated."
  242. //
  243. // We choose that. In my opinion, the spec is weak
  244. // here. It also says both parties must support at least
  245. // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 so there's no
  246. // excuses here. If we really must, we could allow an
  247. // "AllowInsecureWeakCiphers" option on the server later.
  248. // Let's see how it plays out first.
  249. sc.rejectConn(ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite))
  250. return
  251. }
  252. }
  253. if hook := testHookGetServerConn; hook != nil {
  254. hook(sc)
  255. }
  256. sc.serve()
  257. }
  258. // isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec.
  259. func isBadCipher(cipher uint16) bool {
  260. switch cipher {
  261. case tls.TLS_RSA_WITH_RC4_128_SHA,
  262. tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  263. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  264. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  265. tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
  266. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  267. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  268. tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
  269. tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  270. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  271. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
  272. // Reject cipher suites from Appendix A.
  273. // "This list includes those cipher suites that do not
  274. // offer an ephemeral key exchange and those that are
  275. // based on the TLS null, stream or block cipher type"
  276. return true
  277. default:
  278. return false
  279. }
  280. }
  281. func (sc *serverConn) rejectConn(err ErrCode, debug string) {
  282. sc.vlogf("http2: server rejecting conn: %v, %s", err, debug)
  283. // ignoring errors. hanging up anyway.
  284. sc.framer.WriteGoAway(0, err, []byte(debug))
  285. sc.bw.Flush()
  286. sc.conn.Close()
  287. }
  288. type serverConn struct {
  289. // Immutable:
  290. srv *Server
  291. hs *http.Server
  292. conn net.Conn
  293. bw *bufferedWriter // writing to conn
  294. handler http.Handler
  295. framer *Framer
  296. hpackDecoder *hpack.Decoder
  297. doneServing chan struct{} // closed when serverConn.serve ends
  298. readFrameCh chan readFrameResult // written by serverConn.readFrames
  299. wantWriteFrameCh chan frameWriteMsg // from handlers -> serve
  300. wroteFrameCh chan frameWriteResult // from writeFrameAsync -> serve, tickles more frame writes
  301. bodyReadCh chan bodyReadMsg // from handlers -> serve
  302. testHookCh chan func(int) // code to run on the serve loop
  303. flow flow // conn-wide (not stream-specific) outbound flow control
  304. inflow flow // conn-wide inbound flow control
  305. tlsState *tls.ConnectionState // shared by all handlers, like net/http
  306. remoteAddrStr string
  307. // Everything following is owned by the serve loop; use serveG.check():
  308. serveG goroutineLock // used to verify funcs are on serve()
  309. pushEnabled bool
  310. sawFirstSettings bool // got the initial SETTINGS frame after the preface
  311. needToSendSettingsAck bool
  312. unackedSettings int // how many SETTINGS have we sent without ACKs?
  313. clientMaxStreams uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)
  314. advMaxStreams uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client
  315. curOpenStreams uint32 // client's number of open streams
  316. maxStreamID uint32 // max ever seen
  317. streams map[uint32]*stream
  318. initialWindowSize int32
  319. headerTableSize uint32
  320. peerMaxHeaderListSize uint32 // zero means unknown (default)
  321. canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case
  322. req requestParam // non-zero while reading request headers
  323. writingFrame bool // started write goroutine but haven't heard back on wroteFrameCh
  324. needsFrameFlush bool // last frame write wasn't a flush
  325. writeSched writeScheduler
  326. inGoAway bool // we've started to or sent GOAWAY
  327. needToSendGoAway bool // we need to schedule a GOAWAY frame write
  328. goAwayCode ErrCode
  329. shutdownTimerCh <-chan time.Time // nil until used
  330. shutdownTimer *time.Timer // nil until used
  331. // Owned by the writeFrameAsync goroutine:
  332. headerWriteBuf bytes.Buffer
  333. hpackEncoder *hpack.Encoder
  334. }
  335. func (sc *serverConn) maxHeaderStringLen() int {
  336. v := sc.maxHeaderListSize()
  337. if uint32(int(v)) == v {
  338. return int(v)
  339. }
  340. // They had a crazy big number for MaxHeaderBytes anyway,
  341. // so give them unlimited header lengths:
  342. return 0
  343. }
  344. func (sc *serverConn) maxHeaderListSize() uint32 {
  345. n := sc.hs.MaxHeaderBytes
  346. if n <= 0 {
  347. n = http.DefaultMaxHeaderBytes
  348. }
  349. // http2's count is in a slightly different unit and includes 32 bytes per pair.
  350. // So, take the net/http.Server value and pad it up a bit, assuming 10 headers.
  351. const perFieldOverhead = 32 // per http2 spec
  352. const typicalHeaders = 10 // conservative
  353. return uint32(n + typicalHeaders*perFieldOverhead)
  354. }
  355. // requestParam is the state of the next request, initialized over
  356. // potentially several frames HEADERS + zero or more CONTINUATION
  357. // frames.
  358. type requestParam struct {
  359. // stream is non-nil if we're reading (HEADER or CONTINUATION)
  360. // frames for a request (but not DATA).
  361. stream *stream
  362. header http.Header
  363. method, path string
  364. scheme, authority string
  365. sawRegularHeader bool // saw a non-pseudo header already
  366. invalidHeader bool // an invalid header was seen
  367. headerListSize int64 // actually uint32, but easier math this way
  368. }
  369. // stream represents a stream. This is the minimal metadata needed by
  370. // the serve goroutine. Most of the actual stream state is owned by
  371. // the http.Handler's goroutine in the responseWriter. Because the
  372. // responseWriter's responseWriterState is recycled at the end of a
  373. // handler, this struct intentionally has no pointer to the
  374. // *responseWriter{,State} itself, as the Handler ending nils out the
  375. // responseWriter's state field.
  376. type stream struct {
  377. // immutable:
  378. sc *serverConn
  379. id uint32
  380. body *pipe // non-nil if expecting DATA frames
  381. cw closeWaiter // closed wait stream transitions to closed state
  382. // owned by serverConn's serve loop:
  383. bodyBytes int64 // body bytes seen so far
  384. declBodyBytes int64 // or -1 if undeclared
  385. flow flow // limits writing from Handler to client
  386. inflow flow // what the client is allowed to POST/etc to us
  387. parent *stream // or nil
  388. numTrailerValues int64
  389. weight uint8
  390. state streamState
  391. sentReset bool // only true once detached from streams map
  392. gotReset bool // only true once detacted from streams map
  393. gotTrailerHeader bool // HEADER frame for trailers was seen
  394. trailer http.Header // accumulated trailers
  395. reqTrailer http.Header // handler's Request.Trailer
  396. }
  397. func (sc *serverConn) Framer() *Framer { return sc.framer }
  398. func (sc *serverConn) CloseConn() error { return sc.conn.Close() }
  399. func (sc *serverConn) Flush() error { return sc.bw.Flush() }
  400. func (sc *serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) {
  401. return sc.hpackEncoder, &sc.headerWriteBuf
  402. }
  403. func (sc *serverConn) state(streamID uint32) (streamState, *stream) {
  404. sc.serveG.check()
  405. // http://http2.github.io/http2-spec/#rfc.section.5.1
  406. if st, ok := sc.streams[streamID]; ok {
  407. return st.state, st
  408. }
  409. // "The first use of a new stream identifier implicitly closes all
  410. // streams in the "idle" state that might have been initiated by
  411. // that peer with a lower-valued stream identifier. For example, if
  412. // a client sends a HEADERS frame on stream 7 without ever sending a
  413. // frame on stream 5, then stream 5 transitions to the "closed"
  414. // state when the first frame for stream 7 is sent or received."
  415. if streamID <= sc.maxStreamID {
  416. return stateClosed, nil
  417. }
  418. return stateIdle, nil
  419. }
  420. // setConnState calls the net/http ConnState hook for this connection, if configured.
  421. // Note that the net/http package does StateNew and StateClosed for us.
  422. // There is currently no plan for StateHijacked or hijacking HTTP/2 connections.
  423. func (sc *serverConn) setConnState(state http.ConnState) {
  424. if sc.hs.ConnState != nil {
  425. sc.hs.ConnState(sc.conn, state)
  426. }
  427. }
  428. func (sc *serverConn) vlogf(format string, args ...interface{}) {
  429. if VerboseLogs {
  430. sc.logf(format, args...)
  431. }
  432. }
  433. func (sc *serverConn) logf(format string, args ...interface{}) {
  434. if lg := sc.hs.ErrorLog; lg != nil {
  435. lg.Printf(format, args...)
  436. } else {
  437. log.Printf(format, args...)
  438. }
  439. }
  440. // errno returns v's underlying uintptr, else 0.
  441. //
  442. // TODO: remove this helper function once http2 can use build
  443. // tags. See comment in isClosedConnError.
  444. func errno(v error) uintptr {
  445. if rv := reflect.ValueOf(v); rv.Kind() == reflect.Uintptr {
  446. return uintptr(rv.Uint())
  447. }
  448. return 0
  449. }
  450. // isClosedConnError reports whether err is an error from use of a closed
  451. // network connection.
  452. func isClosedConnError(err error) bool {
  453. if err == nil {
  454. return false
  455. }
  456. // TODO: remove this string search and be more like the Windows
  457. // case below. That might involve modifying the standard library
  458. // to return better error types.
  459. str := err.Error()
  460. if strings.Contains(str, "use of closed network connection") {
  461. return true
  462. }
  463. // TODO(bradfitz): x/tools/cmd/bundle doesn't really support
  464. // build tags, so I can't make an http2_windows.go file with
  465. // Windows-specific stuff. Fix that and move this, once we
  466. // have a way to bundle this into std's net/http somehow.
  467. if runtime.GOOS == "windows" {
  468. if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
  469. if se, ok := oe.Err.(*os.SyscallError); ok && se.Syscall == "wsarecv" {
  470. const WSAECONNABORTED = 10053
  471. const WSAECONNRESET = 10054
  472. if n := errno(se.Err); n == WSAECONNRESET || n == WSAECONNABORTED {
  473. return true
  474. }
  475. }
  476. }
  477. }
  478. return false
  479. }
  480. func (sc *serverConn) condlogf(err error, format string, args ...interface{}) {
  481. if err == nil {
  482. return
  483. }
  484. if err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) {
  485. // Boring, expected errors.
  486. sc.vlogf(format, args...)
  487. } else {
  488. sc.logf(format, args...)
  489. }
  490. }
  491. func (sc *serverConn) onNewHeaderField(f hpack.HeaderField) {
  492. sc.serveG.check()
  493. if VerboseLogs {
  494. sc.vlogf("http2: server decoded %v", f)
  495. }
  496. switch {
  497. case !validHeaderFieldValue(f.Value): // f.Name checked _after_ pseudo check, since ':' is invalid
  498. sc.req.invalidHeader = true
  499. case strings.HasPrefix(f.Name, ":"):
  500. if sc.req.sawRegularHeader {
  501. sc.logf("pseudo-header after regular header")
  502. sc.req.invalidHeader = true
  503. return
  504. }
  505. var dst *string
  506. switch f.Name {
  507. case ":method":
  508. dst = &sc.req.method
  509. case ":path":
  510. dst = &sc.req.path
  511. case ":scheme":
  512. dst = &sc.req.scheme
  513. case ":authority":
  514. dst = &sc.req.authority
  515. default:
  516. // 8.1.2.1 Pseudo-Header Fields
  517. // "Endpoints MUST treat a request or response
  518. // that contains undefined or invalid
  519. // pseudo-header fields as malformed (Section
  520. // 8.1.2.6)."
  521. sc.logf("invalid pseudo-header %q", f.Name)
  522. sc.req.invalidHeader = true
  523. return
  524. }
  525. if *dst != "" {
  526. sc.logf("duplicate pseudo-header %q sent", f.Name)
  527. sc.req.invalidHeader = true
  528. return
  529. }
  530. *dst = f.Value
  531. case !validHeaderFieldName(f.Name):
  532. sc.req.invalidHeader = true
  533. default:
  534. sc.req.sawRegularHeader = true
  535. sc.req.header.Add(sc.canonicalHeader(f.Name), f.Value)
  536. const headerFieldOverhead = 32 // per spec
  537. sc.req.headerListSize += int64(len(f.Name)) + int64(len(f.Value)) + headerFieldOverhead
  538. if sc.req.headerListSize > int64(sc.maxHeaderListSize()) {
  539. sc.hpackDecoder.SetEmitEnabled(false)
  540. }
  541. }
  542. }
  543. func (st *stream) onNewTrailerField(f hpack.HeaderField) {
  544. sc := st.sc
  545. sc.serveG.check()
  546. if VerboseLogs {
  547. sc.vlogf("http2: server decoded trailer %v", f)
  548. }
  549. switch {
  550. case strings.HasPrefix(f.Name, ":"):
  551. sc.req.invalidHeader = true
  552. return
  553. case !validHeaderFieldName(f.Name) || !validHeaderFieldValue(f.Value):
  554. sc.req.invalidHeader = true
  555. return
  556. default:
  557. key := sc.canonicalHeader(f.Name)
  558. if st.trailer != nil {
  559. vv := append(st.trailer[key], f.Value)
  560. st.trailer[key] = vv
  561. // arbitrary; TODO: read spec about header list size limits wrt trailers
  562. const tooBig = 1000
  563. if len(vv) >= tooBig {
  564. sc.hpackDecoder.SetEmitEnabled(false)
  565. }
  566. }
  567. }
  568. }
  569. func (sc *serverConn) canonicalHeader(v string) string {
  570. sc.serveG.check()
  571. cv, ok := commonCanonHeader[v]
  572. if ok {
  573. return cv
  574. }
  575. cv, ok = sc.canonHeader[v]
  576. if ok {
  577. return cv
  578. }
  579. if sc.canonHeader == nil {
  580. sc.canonHeader = make(map[string]string)
  581. }
  582. cv = http.CanonicalHeaderKey(v)
  583. sc.canonHeader[v] = cv
  584. return cv
  585. }
  586. type readFrameResult struct {
  587. f Frame // valid until readMore is called
  588. err error
  589. // readMore should be called once the consumer no longer needs or
  590. // retains f. After readMore, f is invalid and more frames can be
  591. // read.
  592. readMore func()
  593. }
  594. // readFrames is the loop that reads incoming frames.
  595. // It takes care to only read one frame at a time, blocking until the
  596. // consumer is done with the frame.
  597. // It's run on its own goroutine.
  598. func (sc *serverConn) readFrames() {
  599. gate := make(gate)
  600. for {
  601. f, err := sc.framer.ReadFrame()
  602. select {
  603. case sc.readFrameCh <- readFrameResult{f, err, gate.Done}:
  604. case <-sc.doneServing:
  605. return
  606. }
  607. select {
  608. case <-gate:
  609. case <-sc.doneServing:
  610. return
  611. }
  612. if terminalReadFrameError(err) {
  613. return
  614. }
  615. }
  616. }
  617. // frameWriteResult is the message passed from writeFrameAsync to the serve goroutine.
  618. type frameWriteResult struct {
  619. wm frameWriteMsg // what was written (or attempted)
  620. err error // result of the writeFrame call
  621. }
  622. // writeFrameAsync runs in its own goroutine and writes a single frame
  623. // and then reports when it's done.
  624. // At most one goroutine can be running writeFrameAsync at a time per
  625. // serverConn.
  626. func (sc *serverConn) writeFrameAsync(wm frameWriteMsg) {
  627. err := wm.write.writeFrame(sc)
  628. sc.wroteFrameCh <- frameWriteResult{wm, err}
  629. }
  630. func (sc *serverConn) closeAllStreamsOnConnClose() {
  631. sc.serveG.check()
  632. for _, st := range sc.streams {
  633. sc.closeStream(st, errClientDisconnected)
  634. }
  635. }
  636. func (sc *serverConn) stopShutdownTimer() {
  637. sc.serveG.check()
  638. if t := sc.shutdownTimer; t != nil {
  639. t.Stop()
  640. }
  641. }
  642. func (sc *serverConn) notePanic() {
  643. // Note: this is for serverConn.serve panicking, not http.Handler code.
  644. if testHookOnPanicMu != nil {
  645. testHookOnPanicMu.Lock()
  646. defer testHookOnPanicMu.Unlock()
  647. }
  648. if testHookOnPanic != nil {
  649. if e := recover(); e != nil {
  650. if testHookOnPanic(sc, e) {
  651. panic(e)
  652. }
  653. }
  654. }
  655. }
  656. func (sc *serverConn) serve() {
  657. sc.serveG.check()
  658. defer sc.notePanic()
  659. defer sc.conn.Close()
  660. defer sc.closeAllStreamsOnConnClose()
  661. defer sc.stopShutdownTimer()
  662. defer close(sc.doneServing) // unblocks handlers trying to send
  663. if VerboseLogs {
  664. sc.vlogf("http2: server connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
  665. }
  666. sc.writeFrame(frameWriteMsg{
  667. write: writeSettings{
  668. {SettingMaxFrameSize, sc.srv.maxReadFrameSize()},
  669. {SettingMaxConcurrentStreams, sc.advMaxStreams},
  670. {SettingMaxHeaderListSize, sc.maxHeaderListSize()},
  671. // TODO: more actual settings, notably
  672. // SettingInitialWindowSize, but then we also
  673. // want to bump up the conn window size the
  674. // same amount here right after the settings
  675. },
  676. })
  677. sc.unackedSettings++
  678. if err := sc.readPreface(); err != nil {
  679. sc.condlogf(err, "http2: server: error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
  680. return
  681. }
  682. // Now that we've got the preface, get us out of the
  683. // "StateNew" state. We can't go directly to idle, though.
  684. // Active means we read some data and anticipate a request. We'll
  685. // do another Active when we get a HEADERS frame.
  686. sc.setConnState(http.StateActive)
  687. sc.setConnState(http.StateIdle)
  688. go sc.readFrames() // closed by defer sc.conn.Close above
  689. settingsTimer := time.NewTimer(firstSettingsTimeout)
  690. loopNum := 0
  691. for {
  692. loopNum++
  693. select {
  694. case wm := <-sc.wantWriteFrameCh:
  695. sc.writeFrame(wm)
  696. case res := <-sc.wroteFrameCh:
  697. sc.wroteFrame(res)
  698. case res := <-sc.readFrameCh:
  699. if !sc.processFrameFromReader(res) {
  700. return
  701. }
  702. res.readMore()
  703. if settingsTimer.C != nil {
  704. settingsTimer.Stop()
  705. settingsTimer.C = nil
  706. }
  707. case m := <-sc.bodyReadCh:
  708. sc.noteBodyRead(m.st, m.n)
  709. case <-settingsTimer.C:
  710. sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
  711. return
  712. case <-sc.shutdownTimerCh:
  713. sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
  714. return
  715. case fn := <-sc.testHookCh:
  716. fn(loopNum)
  717. }
  718. }
  719. }
  720. // readPreface reads the ClientPreface greeting from the peer
  721. // or returns an error on timeout or an invalid greeting.
  722. func (sc *serverConn) readPreface() error {
  723. errc := make(chan error, 1)
  724. go func() {
  725. // Read the client preface
  726. buf := make([]byte, len(ClientPreface))
  727. if _, err := io.ReadFull(sc.conn, buf); err != nil {
  728. errc <- err
  729. } else if !bytes.Equal(buf, clientPreface) {
  730. errc <- fmt.Errorf("bogus greeting %q", buf)
  731. } else {
  732. errc <- nil
  733. }
  734. }()
  735. timer := time.NewTimer(prefaceTimeout) // TODO: configurable on *Server?
  736. defer timer.Stop()
  737. select {
  738. case <-timer.C:
  739. return errors.New("timeout waiting for client preface")
  740. case err := <-errc:
  741. if err == nil {
  742. if VerboseLogs {
  743. sc.vlogf("http2: server: client %v said hello", sc.conn.RemoteAddr())
  744. }
  745. }
  746. return err
  747. }
  748. }
  749. var errChanPool = sync.Pool{
  750. New: func() interface{} { return make(chan error, 1) },
  751. }
  752. var writeDataPool = sync.Pool{
  753. New: func() interface{} { return new(writeData) },
  754. }
  755. // writeDataFromHandler writes DATA response frames from a handler on
  756. // the given stream.
  757. func (sc *serverConn) writeDataFromHandler(stream *stream, data []byte, endStream bool) error {
  758. ch := errChanPool.Get().(chan error)
  759. writeArg := writeDataPool.Get().(*writeData)
  760. *writeArg = writeData{stream.id, data, endStream}
  761. err := sc.writeFrameFromHandler(frameWriteMsg{
  762. write: writeArg,
  763. stream: stream,
  764. done: ch,
  765. })
  766. if err != nil {
  767. return err
  768. }
  769. var frameWriteDone bool // the frame write is done (successfully or not)
  770. select {
  771. case err = <-ch:
  772. frameWriteDone = true
  773. case <-sc.doneServing:
  774. return errClientDisconnected
  775. case <-stream.cw:
  776. // If both ch and stream.cw were ready (as might
  777. // happen on the final Write after an http.Handler
  778. // ends), prefer the write result. Otherwise this
  779. // might just be us successfully closing the stream.
  780. // The writeFrameAsync and serve goroutines guarantee
  781. // that the ch send will happen before the stream.cw
  782. // close.
  783. select {
  784. case err = <-ch:
  785. frameWriteDone = true
  786. default:
  787. return errStreamClosed
  788. }
  789. }
  790. errChanPool.Put(ch)
  791. if frameWriteDone {
  792. writeDataPool.Put(writeArg)
  793. }
  794. return err
  795. }
  796. // writeFrameFromHandler sends wm to sc.wantWriteFrameCh, but aborts
  797. // if the connection has gone away.
  798. //
  799. // This must not be run from the serve goroutine itself, else it might
  800. // deadlock writing to sc.wantWriteFrameCh (which is only mildly
  801. // buffered and is read by serve itself). If you're on the serve
  802. // goroutine, call writeFrame instead.
  803. func (sc *serverConn) writeFrameFromHandler(wm frameWriteMsg) error {
  804. sc.serveG.checkNotOn() // NOT
  805. select {
  806. case sc.wantWriteFrameCh <- wm:
  807. return nil
  808. case <-sc.doneServing:
  809. // Serve loop is gone.
  810. // Client has closed their connection to the server.
  811. return errClientDisconnected
  812. }
  813. }
  814. // writeFrame schedules a frame to write and sends it if there's nothing
  815. // already being written.
  816. //
  817. // There is no pushback here (the serve goroutine never blocks). It's
  818. // the http.Handlers that block, waiting for their previous frames to
  819. // make it onto the wire
  820. //
  821. // If you're not on the serve goroutine, use writeFrameFromHandler instead.
  822. func (sc *serverConn) writeFrame(wm frameWriteMsg) {
  823. sc.serveG.check()
  824. sc.writeSched.add(wm)
  825. sc.scheduleFrameWrite()
  826. }
  827. // startFrameWrite starts a goroutine to write wm (in a separate
  828. // goroutine since that might block on the network), and updates the
  829. // serve goroutine's state about the world, updated from info in wm.
  830. func (sc *serverConn) startFrameWrite(wm frameWriteMsg) {
  831. sc.serveG.check()
  832. if sc.writingFrame {
  833. panic("internal error: can only be writing one frame at a time")
  834. }
  835. st := wm.stream
  836. if st != nil {
  837. switch st.state {
  838. case stateHalfClosedLocal:
  839. panic("internal error: attempt to send frame on half-closed-local stream")
  840. case stateClosed:
  841. if st.sentReset || st.gotReset {
  842. // Skip this frame.
  843. sc.scheduleFrameWrite()
  844. return
  845. }
  846. panic(fmt.Sprintf("internal error: attempt to send a write %v on a closed stream", wm))
  847. }
  848. }
  849. sc.writingFrame = true
  850. sc.needsFrameFlush = true
  851. go sc.writeFrameAsync(wm)
  852. }
  853. // errHandlerPanicked is the error given to any callers blocked in a read from
  854. // Request.Body when the main goroutine panics. Since most handlers read in the
  855. // the main ServeHTTP goroutine, this will show up rarely.
  856. var errHandlerPanicked = errors.New("http2: handler panicked")
  857. // wroteFrame is called on the serve goroutine with the result of
  858. // whatever happened on writeFrameAsync.
  859. func (sc *serverConn) wroteFrame(res frameWriteResult) {
  860. sc.serveG.check()
  861. if !sc.writingFrame {
  862. panic("internal error: expected to be already writing a frame")
  863. }
  864. sc.writingFrame = false
  865. wm := res.wm
  866. st := wm.stream
  867. closeStream := endsStream(wm.write)
  868. if _, ok := wm.write.(handlerPanicRST); ok {
  869. sc.closeStream(st, errHandlerPanicked)
  870. }
  871. // Reply (if requested) to the blocked ServeHTTP goroutine.
  872. if ch := wm.done; ch != nil {
  873. select {
  874. case ch <- res.err:
  875. default:
  876. panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wm.write))
  877. }
  878. }
  879. wm.write = nil // prevent use (assume it's tainted after wm.done send)
  880. if closeStream {
  881. if st == nil {
  882. panic("internal error: expecting non-nil stream")
  883. }
  884. switch st.state {
  885. case stateOpen:
  886. // Here we would go to stateHalfClosedLocal in
  887. // theory, but since our handler is done and
  888. // the net/http package provides no mechanism
  889. // for finishing writing to a ResponseWriter
  890. // while still reading data (see possible TODO
  891. // at top of this file), we go into closed
  892. // state here anyway, after telling the peer
  893. // we're hanging up on them.
  894. st.state = stateHalfClosedLocal // won't last long, but necessary for closeStream via resetStream
  895. errCancel := StreamError{st.id, ErrCodeCancel}
  896. sc.resetStream(errCancel)
  897. case stateHalfClosedRemote:
  898. sc.closeStream(st, errHandlerComplete)
  899. }
  900. }
  901. sc.scheduleFrameWrite()
  902. }
  903. // scheduleFrameWrite tickles the frame writing scheduler.
  904. //
  905. // If a frame is already being written, nothing happens. This will be called again
  906. // when the frame is done being written.
  907. //
  908. // If a frame isn't being written we need to send one, the best frame
  909. // to send is selected, preferring first things that aren't
  910. // stream-specific (e.g. ACKing settings), and then finding the
  911. // highest priority stream.
  912. //
  913. // If a frame isn't being written and there's nothing else to send, we
  914. // flush the write buffer.
  915. func (sc *serverConn) scheduleFrameWrite() {
  916. sc.serveG.check()
  917. if sc.writingFrame {
  918. return
  919. }
  920. if sc.needToSendGoAway {
  921. sc.needToSendGoAway = false
  922. sc.startFrameWrite(frameWriteMsg{
  923. write: &writeGoAway{
  924. maxStreamID: sc.maxStreamID,
  925. code: sc.goAwayCode,
  926. },
  927. })
  928. return
  929. }
  930. if sc.needToSendSettingsAck {
  931. sc.needToSendSettingsAck = false
  932. sc.startFrameWrite(frameWriteMsg{write: writeSettingsAck{}})
  933. return
  934. }
  935. if !sc.inGoAway {
  936. if wm, ok := sc.writeSched.take(); ok {
  937. sc.startFrameWrite(wm)
  938. return
  939. }
  940. }
  941. if sc.needsFrameFlush {
  942. sc.startFrameWrite(frameWriteMsg{write: flushFrameWriter{}})
  943. sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
  944. return
  945. }
  946. }
  947. func (sc *serverConn) goAway(code ErrCode) {
  948. sc.serveG.check()
  949. if sc.inGoAway {
  950. return
  951. }
  952. if code != ErrCodeNo {
  953. sc.shutDownIn(250 * time.Millisecond)
  954. } else {
  955. // TODO: configurable
  956. sc.shutDownIn(1 * time.Second)
  957. }
  958. sc.inGoAway = true
  959. sc.needToSendGoAway = true
  960. sc.goAwayCode = code
  961. sc.scheduleFrameWrite()
  962. }
  963. func (sc *serverConn) shutDownIn(d time.Duration) {
  964. sc.serveG.check()
  965. sc.shutdownTimer = time.NewTimer(d)
  966. sc.shutdownTimerCh = sc.shutdownTimer.C
  967. }
  968. func (sc *serverConn) resetStream(se StreamError) {
  969. sc.serveG.check()
  970. sc.writeFrame(frameWriteMsg{write: se})
  971. if st, ok := sc.streams[se.StreamID]; ok {
  972. st.sentReset = true
  973. sc.closeStream(st, se)
  974. }
  975. }
  976. // processFrameFromReader processes the serve loop's read from readFrameCh from the
  977. // frame-reading goroutine.
  978. // processFrameFromReader returns whether the connection should be kept open.
  979. func (sc *serverConn) processFrameFromReader(res readFrameResult) bool {
  980. sc.serveG.check()
  981. err := res.err
  982. if err != nil {
  983. if err == ErrFrameTooLarge {
  984. sc.goAway(ErrCodeFrameSize)
  985. return true // goAway will close the loop
  986. }
  987. clientGone := err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err)
  988. if clientGone {
  989. // TODO: could we also get into this state if
  990. // the peer does a half close
  991. // (e.g. CloseWrite) because they're done
  992. // sending frames but they're still wanting
  993. // our open replies? Investigate.
  994. // TODO: add CloseWrite to crypto/tls.Conn first
  995. // so we have a way to test this? I suppose
  996. // just for testing we could have a non-TLS mode.
  997. return false
  998. }
  999. } else {
  1000. f := res.f
  1001. if VerboseLogs {
  1002. sc.vlogf("http2: server read frame %v", summarizeFrame(f))
  1003. }
  1004. err = sc.processFrame(f)
  1005. if err == nil {
  1006. return true
  1007. }
  1008. }
  1009. switch ev := err.(type) {
  1010. case StreamError:
  1011. sc.resetStream(ev)
  1012. return true
  1013. case goAwayFlowError:
  1014. sc.goAway(ErrCodeFlowControl)
  1015. return true
  1016. case ConnectionError:
  1017. sc.logf("http2: server connection error from %v: %v", sc.conn.RemoteAddr(), ev)
  1018. sc.goAway(ErrCode(ev))
  1019. return true // goAway will handle shutdown
  1020. default:
  1021. if res.err != nil {
  1022. sc.vlogf("http2: server closing client connection; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
  1023. } else {
  1024. sc.logf("http2: server closing client connection: %v", err)
  1025. }
  1026. return false
  1027. }
  1028. }
  1029. func (sc *serverConn) processFrame(f Frame) error {
  1030. sc.serveG.check()
  1031. // First frame received must be SETTINGS.
  1032. if !sc.sawFirstSettings {
  1033. if _, ok := f.(*SettingsFrame); !ok {
  1034. return ConnectionError(ErrCodeProtocol)
  1035. }
  1036. sc.sawFirstSettings = true
  1037. }
  1038. switch f := f.(type) {
  1039. case *SettingsFrame:
  1040. return sc.processSettings(f)
  1041. case *HeadersFrame:
  1042. return sc.processHeaders(f)
  1043. case *ContinuationFrame:
  1044. return sc.processContinuation(f)
  1045. case *WindowUpdateFrame:
  1046. return sc.processWindowUpdate(f)
  1047. case *PingFrame:
  1048. return sc.processPing(f)
  1049. case *DataFrame:
  1050. return sc.processData(f)
  1051. case *RSTStreamFrame:
  1052. return sc.processResetStream(f)
  1053. case *PriorityFrame:
  1054. return sc.processPriority(f)
  1055. case *PushPromiseFrame:
  1056. // A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE
  1057. // frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1058. return ConnectionError(ErrCodeProtocol)
  1059. default:
  1060. sc.vlogf("http2: server ignoring frame: %v", f.Header())
  1061. return nil
  1062. }
  1063. }
  1064. func (sc *serverConn) processPing(f *PingFrame) error {
  1065. sc.serveG.check()
  1066. if f.IsAck() {
  1067. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  1068. // containing this flag."
  1069. return nil
  1070. }
  1071. if f.StreamID != 0 {
  1072. // "PING frames are not associated with any individual
  1073. // stream. If a PING frame is received with a stream
  1074. // identifier field value other than 0x0, the recipient MUST
  1075. // respond with a connection error (Section 5.4.1) of type
  1076. // PROTOCOL_ERROR."
  1077. return ConnectionError(ErrCodeProtocol)
  1078. }
  1079. sc.writeFrame(frameWriteMsg{write: writePingAck{f}})
  1080. return nil
  1081. }
  1082. func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  1083. sc.serveG.check()
  1084. switch {
  1085. case f.StreamID != 0: // stream-level flow control
  1086. st := sc.streams[f.StreamID]
  1087. if st == nil {
  1088. // "WINDOW_UPDATE can be sent by a peer that has sent a
  1089. // frame bearing the END_STREAM flag. This means that a
  1090. // receiver could receive a WINDOW_UPDATE frame on a "half
  1091. // closed (remote)" or "closed" stream. A receiver MUST
  1092. // NOT treat this as an error, see Section 5.1."
  1093. return nil
  1094. }
  1095. if !st.flow.add(int32(f.Increment)) {
  1096. return StreamError{f.StreamID, ErrCodeFlowControl}
  1097. }
  1098. default: // connection-level flow control
  1099. if !sc.flow.add(int32(f.Increment)) {
  1100. return goAwayFlowError{}
  1101. }
  1102. }
  1103. sc.scheduleFrameWrite()
  1104. return nil
  1105. }
  1106. func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
  1107. sc.serveG.check()
  1108. state, st := sc.state(f.StreamID)
  1109. if state == stateIdle {
  1110. // 6.4 "RST_STREAM frames MUST NOT be sent for a
  1111. // stream in the "idle" state. If a RST_STREAM frame
  1112. // identifying an idle stream is received, the
  1113. // recipient MUST treat this as a connection error
  1114. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1115. return ConnectionError(ErrCodeProtocol)
  1116. }
  1117. if st != nil {
  1118. st.gotReset = true
  1119. sc.closeStream(st, StreamError{f.StreamID, f.ErrCode})
  1120. }
  1121. return nil
  1122. }
  1123. func (sc *serverConn) closeStream(st *stream, err error) {
  1124. sc.serveG.check()
  1125. if st.state == stateIdle || st.state == stateClosed {
  1126. panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
  1127. }
  1128. st.state = stateClosed
  1129. sc.curOpenStreams--
  1130. if sc.curOpenStreams == 0 {
  1131. sc.setConnState(http.StateIdle)
  1132. }
  1133. delete(sc.streams, st.id)
  1134. if p := st.body; p != nil {
  1135. p.CloseWithError(err)
  1136. }
  1137. st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc
  1138. sc.writeSched.forgetStream(st.id)
  1139. }
  1140. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  1141. sc.serveG.check()
  1142. if f.IsAck() {
  1143. sc.unackedSettings--
  1144. if sc.unackedSettings < 0 {
  1145. // Why is the peer ACKing settings we never sent?
  1146. // The spec doesn't mention this case, but
  1147. // hang up on them anyway.
  1148. return ConnectionError(ErrCodeProtocol)
  1149. }
  1150. return nil
  1151. }
  1152. if err := f.ForeachSetting(sc.processSetting); err != nil {
  1153. return err
  1154. }
  1155. sc.needToSendSettingsAck = true
  1156. sc.scheduleFrameWrite()
  1157. return nil
  1158. }
  1159. func (sc *serverConn) processSetting(s Setting) error {
  1160. sc.serveG.check()
  1161. if err := s.Valid(); err != nil {
  1162. return err
  1163. }
  1164. if VerboseLogs {
  1165. sc.vlogf("http2: server processing setting %v", s)
  1166. }
  1167. switch s.ID {
  1168. case SettingHeaderTableSize:
  1169. sc.headerTableSize = s.Val
  1170. sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
  1171. case SettingEnablePush:
  1172. sc.pushEnabled = s.Val != 0
  1173. case SettingMaxConcurrentStreams:
  1174. sc.clientMaxStreams = s.Val
  1175. case SettingInitialWindowSize:
  1176. return sc.processSettingInitialWindowSize(s.Val)
  1177. case SettingMaxFrameSize:
  1178. sc.writeSched.maxFrameSize = s.Val
  1179. case SettingMaxHeaderListSize:
  1180. sc.peerMaxHeaderListSize = s.Val
  1181. default:
  1182. // Unknown setting: "An endpoint that receives a SETTINGS
  1183. // frame with any unknown or unsupported identifier MUST
  1184. // ignore that setting."
  1185. if VerboseLogs {
  1186. sc.vlogf("http2: server ignoring unknown setting %v", s)
  1187. }
  1188. }
  1189. return nil
  1190. }
  1191. func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  1192. sc.serveG.check()
  1193. // Note: val already validated to be within range by
  1194. // processSetting's Valid call.
  1195. // "A SETTINGS frame can alter the initial flow control window
  1196. // size for all current streams. When the value of
  1197. // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  1198. // adjust the size of all stream flow control windows that it
  1199. // maintains by the difference between the new value and the
  1200. // old value."
  1201. old := sc.initialWindowSize
  1202. sc.initialWindowSize = int32(val)
  1203. growth := sc.initialWindowSize - old // may be negative
  1204. for _, st := range sc.streams {
  1205. if !st.flow.add(growth) {
  1206. // 6.9.2 Initial Flow Control Window Size
  1207. // "An endpoint MUST treat a change to
  1208. // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  1209. // control window to exceed the maximum size as a
  1210. // connection error (Section 5.4.1) of type
  1211. // FLOW_CONTROL_ERROR."
  1212. return ConnectionError(ErrCodeFlowControl)
  1213. }
  1214. }
  1215. return nil
  1216. }
  1217. func (sc *serverConn) processData(f *DataFrame) error {
  1218. sc.serveG.check()
  1219. // "If a DATA frame is received whose stream is not in "open"
  1220. // or "half closed (local)" state, the recipient MUST respond
  1221. // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  1222. id := f.Header().StreamID
  1223. st, ok := sc.streams[id]
  1224. if !ok || st.state != stateOpen || st.gotTrailerHeader {
  1225. // This includes sending a RST_STREAM if the stream is
  1226. // in stateHalfClosedLocal (which currently means that
  1227. // the http.Handler returned, so it's done reading &
  1228. // done writing). Try to stop the client from sending
  1229. // more DATA.
  1230. return StreamError{id, ErrCodeStreamClosed}
  1231. }
  1232. if st.body == nil {
  1233. panic("internal error: should have a body in this state")
  1234. }
  1235. data := f.Data()
  1236. // Sender sending more than they'd declared?
  1237. if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  1238. st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  1239. return StreamError{id, ErrCodeStreamClosed}
  1240. }
  1241. if len(data) > 0 {
  1242. // Check whether the client has flow control quota.
  1243. if int(st.inflow.available()) < len(data) {
  1244. return StreamError{id, ErrCodeFlowControl}
  1245. }
  1246. st.inflow.take(int32(len(data)))
  1247. wrote, err := st.body.Write(data)
  1248. if err != nil {
  1249. return StreamError{id, ErrCodeStreamClosed}
  1250. }
  1251. if wrote != len(data) {
  1252. panic("internal error: bad Writer")
  1253. }
  1254. st.bodyBytes += int64(len(data))
  1255. }
  1256. if f.StreamEnded() {
  1257. st.endStream()
  1258. }
  1259. return nil
  1260. }
  1261. // endStream closes a Request.Body's pipe. It is called when a DATA
  1262. // frame says a request body is over (or after trailers).
  1263. func (st *stream) endStream() {
  1264. sc := st.sc
  1265. sc.serveG.check()
  1266. if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  1267. st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
  1268. st.declBodyBytes, st.bodyBytes))
  1269. } else {
  1270. st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest)
  1271. st.body.CloseWithError(io.EOF)
  1272. }
  1273. st.state = stateHalfClosedRemote
  1274. }
  1275. // copyTrailersToHandlerRequest is run in the Handler's goroutine in
  1276. // its Request.Body.Read just before it gets io.EOF.
  1277. func (st *stream) copyTrailersToHandlerRequest() {
  1278. for k, vv := range st.trailer {
  1279. if _, ok := st.reqTrailer[k]; ok {
  1280. // Only copy it over it was pre-declared.
  1281. st.reqTrailer[k] = vv
  1282. }
  1283. }
  1284. }
  1285. func (sc *serverConn) processHeaders(f *HeadersFrame) error {
  1286. sc.serveG.check()
  1287. id := f.Header().StreamID
  1288. if sc.inGoAway {
  1289. // Ignore.
  1290. return nil
  1291. }
  1292. // http://http2.github.io/http2-spec/#rfc.section.5.1.1
  1293. // Streams initiated by a client MUST use odd-numbered stream
  1294. // identifiers. [...] An endpoint that receives an unexpected
  1295. // stream identifier MUST respond with a connection error
  1296. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1297. if id%2 != 1 {
  1298. return ConnectionError(ErrCodeProtocol)
  1299. }
  1300. // A HEADERS frame can be used to create a new stream or
  1301. // send a trailer for an open one. If we already have a stream
  1302. // open, let it process its own HEADERS frame (trailers at this
  1303. // point, if it's valid).
  1304. st := sc.streams[f.Header().StreamID]
  1305. if st != nil {
  1306. return st.processTrailerHeaders(f)
  1307. }
  1308. // [...] The identifier of a newly established stream MUST be
  1309. // numerically greater than all streams that the initiating
  1310. // endpoint has opened or reserved. [...] An endpoint that
  1311. // receives an unexpected stream identifier MUST respond with
  1312. // a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1313. if id <= sc.maxStreamID || sc.req.stream != nil {
  1314. return ConnectionError(ErrCodeProtocol)
  1315. }
  1316. if id > sc.maxStreamID {
  1317. sc.maxStreamID = id
  1318. }
  1319. st = &stream{
  1320. sc: sc,
  1321. id: id,
  1322. state: stateOpen,
  1323. }
  1324. if f.StreamEnded() {
  1325. st.state = stateHalfClosedRemote
  1326. }
  1327. st.cw.Init()
  1328. st.flow.conn = &sc.flow // link to conn-level counter
  1329. st.flow.add(sc.initialWindowSize)
  1330. st.inflow.conn = &sc.inflow // link to conn-level counter
  1331. st.inflow.add(initialWindowSize) // TODO: update this when we send a higher initial window size in the initial settings
  1332. sc.streams[id] = st
  1333. if f.HasPriority() {
  1334. adjustStreamPriority(sc.streams, st.id, f.Priority)
  1335. }
  1336. sc.curOpenStreams++
  1337. if sc.curOpenStreams == 1 {
  1338. sc.setConnState(http.StateActive)
  1339. }
  1340. sc.req = requestParam{
  1341. stream: st,
  1342. header: make(http.Header),
  1343. }
  1344. sc.hpackDecoder.SetEmitFunc(sc.onNewHeaderField)
  1345. sc.hpackDecoder.SetEmitEnabled(true)
  1346. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  1347. }
  1348. func (st *stream) processTrailerHeaders(f *HeadersFrame) error {
  1349. sc := st.sc
  1350. sc.serveG.check()
  1351. if st.gotTrailerHeader {
  1352. return ConnectionError(ErrCodeProtocol)
  1353. }
  1354. st.gotTrailerHeader = true
  1355. if !f.StreamEnded() {
  1356. return StreamError{st.id, ErrCodeProtocol}
  1357. }
  1358. sc.resetPendingRequest() // we use invalidHeader from it for trailers
  1359. return st.processTrailerHeaderBlockFragment(f.HeaderBlockFragment(), f.HeadersEnded())
  1360. }
  1361. func (sc *serverConn) processContinuation(f *ContinuationFrame) error {
  1362. sc.serveG.check()
  1363. st := sc.streams[f.Header().StreamID]
  1364. if st.gotTrailerHeader {
  1365. return st.processTrailerHeaderBlockFragment(f.HeaderBlockFragment(), f.HeadersEnded())
  1366. }
  1367. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  1368. }
  1369. func (sc *serverConn) processHeaderBlockFragment(st *stream, frag []byte, end bool) error {
  1370. sc.serveG.check()
  1371. if _, err := sc.hpackDecoder.Write(frag); err != nil {
  1372. return ConnectionError(ErrCodeCompression)
  1373. }
  1374. if !end {
  1375. return nil
  1376. }
  1377. if err := sc.hpackDecoder.Close(); err != nil {
  1378. return ConnectionError(ErrCodeCompression)
  1379. }
  1380. defer sc.resetPendingRequest()
  1381. if sc.curOpenStreams > sc.advMaxStreams {
  1382. // "Endpoints MUST NOT exceed the limit set by their
  1383. // peer. An endpoint that receives a HEADERS frame
  1384. // that causes their advertised concurrent stream
  1385. // limit to be exceeded MUST treat this as a stream
  1386. // error (Section 5.4.2) of type PROTOCOL_ERROR or
  1387. // REFUSED_STREAM."
  1388. if sc.unackedSettings == 0 {
  1389. // They should know better.
  1390. return StreamError{st.id, ErrCodeProtocol}
  1391. }
  1392. // Assume it's a network race, where they just haven't
  1393. // received our last SETTINGS update. But actually
  1394. // this can't happen yet, because we don't yet provide
  1395. // a way for users to adjust server parameters at
  1396. // runtime.
  1397. return StreamError{st.id, ErrCodeRefusedStream}
  1398. }
  1399. rw, req, err := sc.newWriterAndRequest()
  1400. if err != nil {
  1401. return err
  1402. }
  1403. st.reqTrailer = req.Trailer
  1404. if st.reqTrailer != nil {
  1405. st.trailer = make(http.Header)
  1406. }
  1407. st.body = req.Body.(*requestBody).pipe // may be nil
  1408. st.declBodyBytes = req.ContentLength
  1409. handler := sc.handler.ServeHTTP
  1410. if !sc.hpackDecoder.EmitEnabled() {
  1411. // Their header list was too long. Send a 431 error.
  1412. handler = handleHeaderListTooLong
  1413. }
  1414. go sc.runHandler(rw, req, handler)
  1415. return nil
  1416. }
  1417. func (st *stream) processTrailerHeaderBlockFragment(frag []byte, end bool) error {
  1418. sc := st.sc
  1419. sc.serveG.check()
  1420. sc.hpackDecoder.SetEmitFunc(st.onNewTrailerField)
  1421. if _, err := sc.hpackDecoder.Write(frag); err != nil {
  1422. return ConnectionError(ErrCodeCompression)
  1423. }
  1424. if !end {
  1425. return nil
  1426. }
  1427. rp := &sc.req
  1428. if rp.invalidHeader {
  1429. return StreamError{rp.stream.id, ErrCodeProtocol}
  1430. }
  1431. err := sc.hpackDecoder.Close()
  1432. st.endStream()
  1433. if err != nil {
  1434. return ConnectionError(ErrCodeCompression)
  1435. }
  1436. return nil
  1437. }
  1438. func (sc *serverConn) processPriority(f *PriorityFrame) error {
  1439. adjustStreamPriority(sc.streams, f.StreamID, f.PriorityParam)
  1440. return nil
  1441. }
  1442. func adjustStreamPriority(streams map[uint32]*stream, streamID uint32, priority PriorityParam) {
  1443. st, ok := streams[streamID]
  1444. if !ok {
  1445. // TODO: not quite correct (this streamID might
  1446. // already exist in the dep tree, but be closed), but
  1447. // close enough for now.
  1448. return
  1449. }
  1450. st.weight = priority.Weight
  1451. parent := streams[priority.StreamDep] // might be nil
  1452. if parent == st {
  1453. // if client tries to set this stream to be the parent of itself
  1454. // ignore and keep going
  1455. return
  1456. }
  1457. // section 5.3.3: If a stream is made dependent on one of its
  1458. // own dependencies, the formerly dependent stream is first
  1459. // moved to be dependent on the reprioritized stream's previous
  1460. // parent. The moved dependency retains its weight.
  1461. for piter := parent; piter != nil; piter = piter.parent {
  1462. if piter == st {
  1463. parent.parent = st.parent
  1464. break
  1465. }
  1466. }
  1467. st.parent = parent
  1468. if priority.Exclusive && (st.parent != nil || priority.StreamDep == 0) {
  1469. for _, openStream := range streams {
  1470. if openStream != st && openStream.parent == st.parent {
  1471. openStream.parent = st
  1472. }
  1473. }
  1474. }
  1475. }
  1476. // resetPendingRequest zeros out all state related to a HEADERS frame
  1477. // and its zero or more CONTINUATION frames sent to start a new
  1478. // request.
  1479. func (sc *serverConn) resetPendingRequest() {
  1480. sc.serveG.check()
  1481. sc.req = requestParam{}
  1482. }
  1483. func (sc *serverConn) newWriterAndRequest() (*responseWriter, *http.Request, error) {
  1484. sc.serveG.check()
  1485. rp := &sc.req
  1486. if rp.invalidHeader {
  1487. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1488. }
  1489. isConnect := rp.method == "CONNECT"
  1490. if isConnect {
  1491. if rp.path != "" || rp.scheme != "" || rp.authority == "" {
  1492. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1493. }
  1494. } else if rp.method == "" || rp.path == "" ||
  1495. (rp.scheme != "https" && rp.scheme != "http") {
  1496. // See 8.1.2.6 Malformed Requests and Responses:
  1497. //
  1498. // Malformed requests or responses that are detected
  1499. // MUST be treated as a stream error (Section 5.4.2)
  1500. // of type PROTOCOL_ERROR."
  1501. //
  1502. // 8.1.2.3 Request Pseudo-Header Fields
  1503. // "All HTTP/2 requests MUST include exactly one valid
  1504. // value for the :method, :scheme, and :path
  1505. // pseudo-header fields"
  1506. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1507. }
  1508. bodyOpen := rp.stream.state == stateOpen
  1509. if rp.method == "HEAD" && bodyOpen {
  1510. // HEAD requests can't have bodies
  1511. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1512. }
  1513. var tlsState *tls.ConnectionState // nil if not scheme https
  1514. if rp.scheme == "https" {
  1515. tlsState = sc.tlsState
  1516. }
  1517. authority := rp.authority
  1518. if authority == "" {
  1519. authority = rp.header.Get("Host")
  1520. }
  1521. needsContinue := rp.header.Get("Expect") == "100-continue"
  1522. if needsContinue {
  1523. rp.header.Del("Expect")
  1524. }
  1525. // Merge Cookie headers into one "; "-delimited value.
  1526. if cookies := rp.header["Cookie"]; len(cookies) > 1 {
  1527. rp.header.Set("Cookie", strings.Join(cookies, "; "))
  1528. }
  1529. // Setup Trailers
  1530. var trailer http.Header
  1531. for _, v := range rp.header["Trailer"] {
  1532. for _, key := range strings.Split(v, ",") {
  1533. key = http.CanonicalHeaderKey(strings.TrimSpace(key))
  1534. switch key {
  1535. case "Transfer-Encoding", "Trailer", "Content-Length":
  1536. // Bogus. (copy of http1 rules)
  1537. // Ignore.
  1538. default:
  1539. if trailer == nil {
  1540. trailer = make(http.Header)
  1541. }
  1542. trailer[key] = nil
  1543. }
  1544. }
  1545. }
  1546. delete(rp.header, "Trailer")
  1547. body := &requestBody{
  1548. conn: sc,
  1549. stream: rp.stream,
  1550. needsContinue: needsContinue,
  1551. }
  1552. var url_ *url.URL
  1553. var requestURI string
  1554. if isConnect {
  1555. url_ = &url.URL{Host: rp.authority}
  1556. requestURI = rp.authority // mimic HTTP/1 server behavior
  1557. } else {
  1558. var err error
  1559. url_, err = url.ParseRequestURI(rp.path)
  1560. if err != nil {
  1561. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1562. }
  1563. requestURI = rp.path
  1564. }
  1565. req := &http.Request{
  1566. Method: rp.method,
  1567. URL: url_,
  1568. RemoteAddr: sc.remoteAddrStr,
  1569. Header: rp.header,
  1570. RequestURI: requestURI,
  1571. Proto: "HTTP/2.0",
  1572. ProtoMajor: 2,
  1573. ProtoMinor: 0,
  1574. TLS: tlsState,
  1575. Host: authority,
  1576. Body: body,
  1577. Trailer: trailer,
  1578. }
  1579. if bodyOpen {
  1580. body.pipe = &pipe{
  1581. b: &fixedBuffer{buf: make([]byte, initialWindowSize)}, // TODO: garbage
  1582. }
  1583. if vv, ok := rp.header["Content-Length"]; ok {
  1584. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  1585. } else {
  1586. req.ContentLength = -1
  1587. }
  1588. }
  1589. rws := responseWriterStatePool.Get().(*responseWriterState)
  1590. bwSave := rws.bw
  1591. *rws = responseWriterState{} // zero all the fields
  1592. rws.conn = sc
  1593. rws.bw = bwSave
  1594. rws.bw.Reset(chunkWriter{rws})
  1595. rws.stream = rp.stream
  1596. rws.req = req
  1597. rws.body = body
  1598. rw := &responseWriter{rws: rws}
  1599. return rw, req, nil
  1600. }
  1601. // Run on its own goroutine.
  1602. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) {
  1603. didPanic := true
  1604. defer func() {
  1605. if didPanic {
  1606. e := recover()
  1607. // Same as net/http:
  1608. const size = 64 << 10
  1609. buf := make([]byte, size)
  1610. buf = buf[:runtime.Stack(buf, false)]
  1611. sc.writeFrameFromHandler(frameWriteMsg{
  1612. write: handlerPanicRST{rw.rws.stream.id},
  1613. stream: rw.rws.stream,
  1614. })
  1615. sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf)
  1616. return
  1617. }
  1618. rw.handlerDone()
  1619. }()
  1620. handler(rw, req)
  1621. didPanic = false
  1622. }
  1623. func handleHeaderListTooLong(w http.ResponseWriter, r *http.Request) {
  1624. // 10.5.1 Limits on Header Block Size:
  1625. // .. "A server that receives a larger header block than it is
  1626. // willing to handle can send an HTTP 431 (Request Header Fields Too
  1627. // Large) status code"
  1628. const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+
  1629. w.WriteHeader(statusRequestHeaderFieldsTooLarge)
  1630. io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
  1631. }
  1632. // called from handler goroutines.
  1633. // h may be nil.
  1634. func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error {
  1635. sc.serveG.checkNotOn() // NOT on
  1636. var errc chan error
  1637. if headerData.h != nil {
  1638. // If there's a header map (which we don't own), so we have to block on
  1639. // waiting for this frame to be written, so an http.Flush mid-handler
  1640. // writes out the correct value of keys, before a handler later potentially
  1641. // mutates it.
  1642. errc = errChanPool.Get().(chan error)
  1643. }
  1644. if err := sc.writeFrameFromHandler(frameWriteMsg{
  1645. write: headerData,
  1646. stream: st,
  1647. done: errc,
  1648. }); err != nil {
  1649. return err
  1650. }
  1651. if errc != nil {
  1652. select {
  1653. case err := <-errc:
  1654. errChanPool.Put(errc)
  1655. return err
  1656. case <-sc.doneServing:
  1657. return errClientDisconnected
  1658. case <-st.cw:
  1659. return errStreamClosed
  1660. }
  1661. }
  1662. return nil
  1663. }
  1664. // called from handler goroutines.
  1665. func (sc *serverConn) write100ContinueHeaders(st *stream) {
  1666. sc.writeFrameFromHandler(frameWriteMsg{
  1667. write: write100ContinueHeadersFrame{st.id},
  1668. stream: st,
  1669. })
  1670. }
  1671. // A bodyReadMsg tells the server loop that the http.Handler read n
  1672. // bytes of the DATA from the client on the given stream.
  1673. type bodyReadMsg struct {
  1674. st *stream
  1675. n int
  1676. }
  1677. // called from handler goroutines.
  1678. // Notes that the handler for the given stream ID read n bytes of its body
  1679. // and schedules flow control tokens to be sent.
  1680. func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int) {
  1681. sc.serveG.checkNotOn() // NOT on
  1682. select {
  1683. case sc.bodyReadCh <- bodyReadMsg{st, n}:
  1684. case <-sc.doneServing:
  1685. }
  1686. }
  1687. func (sc *serverConn) noteBodyRead(st *stream, n int) {
  1688. sc.serveG.check()
  1689. sc.sendWindowUpdate(nil, n) // conn-level
  1690. if st.state != stateHalfClosedRemote && st.state != stateClosed {
  1691. // Don't send this WINDOW_UPDATE if the stream is closed
  1692. // remotely.
  1693. sc.sendWindowUpdate(st, n)
  1694. }
  1695. }
  1696. // st may be nil for conn-level
  1697. func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
  1698. sc.serveG.check()
  1699. // "The legal range for the increment to the flow control
  1700. // window is 1 to 2^31-1 (2,147,483,647) octets."
  1701. // A Go Read call on 64-bit machines could in theory read
  1702. // a larger Read than this. Very unlikely, but we handle it here
  1703. // rather than elsewhere for now.
  1704. const maxUint31 = 1<<31 - 1
  1705. for n >= maxUint31 {
  1706. sc.sendWindowUpdate32(st, maxUint31)
  1707. n -= maxUint31
  1708. }
  1709. sc.sendWindowUpdate32(st, int32(n))
  1710. }
  1711. // st may be nil for conn-level
  1712. func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) {
  1713. sc.serveG.check()
  1714. if n == 0 {
  1715. return
  1716. }
  1717. if n < 0 {
  1718. panic("negative update")
  1719. }
  1720. var streamID uint32
  1721. if st != nil {
  1722. streamID = st.id
  1723. }
  1724. sc.writeFrame(frameWriteMsg{
  1725. write: writeWindowUpdate{streamID: streamID, n: uint32(n)},
  1726. stream: st,
  1727. })
  1728. var ok bool
  1729. if st == nil {
  1730. ok = sc.inflow.add(n)
  1731. } else {
  1732. ok = st.inflow.add(n)
  1733. }
  1734. if !ok {
  1735. panic("internal error; sent too many window updates without decrements?")
  1736. }
  1737. }
  1738. type requestBody struct {
  1739. stream *stream
  1740. conn *serverConn
  1741. closed bool
  1742. pipe *pipe // non-nil if we have a HTTP entity message body
  1743. needsContinue bool // need to send a 100-continue
  1744. }
  1745. func (b *requestBody) Close() error {
  1746. if b.pipe != nil {
  1747. b.pipe.CloseWithError(errClosedBody)
  1748. }
  1749. b.closed = true
  1750. return nil
  1751. }
  1752. func (b *requestBody) Read(p []byte) (n int, err error) {
  1753. if b.needsContinue {
  1754. b.needsContinue = false
  1755. b.conn.write100ContinueHeaders(b.stream)
  1756. }
  1757. if b.pipe == nil {
  1758. return 0, io.EOF
  1759. }
  1760. n, err = b.pipe.Read(p)
  1761. if n > 0 {
  1762. b.conn.noteBodyReadFromHandler(b.stream, n)
  1763. }
  1764. return
  1765. }
  1766. // responseWriter is the http.ResponseWriter implementation. It's
  1767. // intentionally small (1 pointer wide) to minimize garbage. The
  1768. // responseWriterState pointer inside is zeroed at the end of a
  1769. // request (in handlerDone) and calls on the responseWriter thereafter
  1770. // simply crash (caller's mistake), but the much larger responseWriterState
  1771. // and buffers are reused between multiple requests.
  1772. type responseWriter struct {
  1773. rws *responseWriterState
  1774. }
  1775. // Optional http.ResponseWriter interfaces implemented.
  1776. var (
  1777. _ http.CloseNotifier = (*responseWriter)(nil)
  1778. _ http.Flusher = (*responseWriter)(nil)
  1779. _ stringWriter = (*responseWriter)(nil)
  1780. )
  1781. type responseWriterState struct {
  1782. // immutable within a request:
  1783. stream *stream
  1784. req *http.Request
  1785. body *requestBody // to close at end of request, if DATA frames didn't
  1786. conn *serverConn
  1787. // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
  1788. bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
  1789. // mutated by http.Handler goroutine:
  1790. handlerHeader http.Header // nil until called
  1791. snapHeader http.Header // snapshot of handlerHeader at WriteHeader time
  1792. trailers []string // set in writeChunk
  1793. status int // status code passed to WriteHeader
  1794. wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
  1795. sentHeader bool // have we sent the header frame?
  1796. handlerDone bool // handler has finished
  1797. sentContentLen int64 // non-zero if handler set a Content-Length header
  1798. wroteBytes int64
  1799. closeNotifierMu sync.Mutex // guards closeNotifierCh
  1800. closeNotifierCh chan bool // nil until first used
  1801. }
  1802. type chunkWriter struct{ rws *responseWriterState }
  1803. func (cw chunkWriter) Write(p []byte) (n int, err error) { return cw.rws.writeChunk(p) }
  1804. func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) != 0 }
  1805. // declareTrailer is called for each Trailer header when the
  1806. // response header is written. It notes that a header will need to be
  1807. // written in the trailers at the end of the response.
  1808. func (rws *responseWriterState) declareTrailer(k string) {
  1809. k = http.CanonicalHeaderKey(k)
  1810. switch k {
  1811. case "Transfer-Encoding", "Content-Length", "Trailer":
  1812. // Forbidden by RFC 2616 14.40.
  1813. return
  1814. }
  1815. rws.trailers = append(rws.trailers, k)
  1816. }
  1817. // writeChunk writes chunks from the bufio.Writer. But because
  1818. // bufio.Writer may bypass its chunking, sometimes p may be
  1819. // arbitrarily large.
  1820. //
  1821. // writeChunk is also responsible (on the first chunk) for sending the
  1822. // HEADER response.
  1823. func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
  1824. if !rws.wroteHeader {
  1825. rws.writeHeader(200)
  1826. }
  1827. isHeadResp := rws.req.Method == "HEAD"
  1828. if !rws.sentHeader {
  1829. rws.sentHeader = true
  1830. var ctype, clen string
  1831. if clen = rws.snapHeader.Get("Content-Length"); clen != "" {
  1832. rws.snapHeader.Del("Content-Length")
  1833. clen64, err := strconv.ParseInt(clen, 10, 64)
  1834. if err == nil && clen64 >= 0 {
  1835. rws.sentContentLen = clen64
  1836. } else {
  1837. clen = ""
  1838. }
  1839. }
  1840. if clen == "" && rws.handlerDone && bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) {
  1841. clen = strconv.Itoa(len(p))
  1842. }
  1843. _, hasContentType := rws.snapHeader["Content-Type"]
  1844. if !hasContentType && bodyAllowedForStatus(rws.status) {
  1845. ctype = http.DetectContentType(p)
  1846. }
  1847. var date string
  1848. if _, ok := rws.snapHeader["Date"]; !ok {
  1849. // TODO(bradfitz): be faster here, like net/http? measure.
  1850. date = time.Now().UTC().Format(http.TimeFormat)
  1851. }
  1852. for _, v := range rws.snapHeader["Trailer"] {
  1853. foreachHeaderElement(v, rws.declareTrailer)
  1854. }
  1855. endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp
  1856. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  1857. streamID: rws.stream.id,
  1858. httpResCode: rws.status,
  1859. h: rws.snapHeader,
  1860. endStream: endStream,
  1861. contentType: ctype,
  1862. contentLength: clen,
  1863. date: date,
  1864. })
  1865. if err != nil {
  1866. return 0, err
  1867. }
  1868. if endStream {
  1869. return 0, nil
  1870. }
  1871. }
  1872. if isHeadResp {
  1873. return len(p), nil
  1874. }
  1875. if len(p) == 0 && !rws.handlerDone {
  1876. return 0, nil
  1877. }
  1878. endStream := rws.handlerDone && !rws.hasTrailers()
  1879. if len(p) > 0 || endStream {
  1880. // only send a 0 byte DATA frame if we're ending the stream.
  1881. if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil {
  1882. return 0, err
  1883. }
  1884. }
  1885. if rws.handlerDone && rws.hasTrailers() {
  1886. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  1887. streamID: rws.stream.id,
  1888. h: rws.handlerHeader,
  1889. trailers: rws.trailers,
  1890. endStream: true,
  1891. })
  1892. return len(p), err
  1893. }
  1894. return len(p), nil
  1895. }
  1896. func (w *responseWriter) Flush() {
  1897. rws := w.rws
  1898. if rws == nil {
  1899. panic("Header called after Handler finished")
  1900. }
  1901. if rws.bw.Buffered() > 0 {
  1902. if err := rws.bw.Flush(); err != nil {
  1903. // Ignore the error. The frame writer already knows.
  1904. return
  1905. }
  1906. } else {
  1907. // The bufio.Writer won't call chunkWriter.Write
  1908. // (writeChunk with zero bytes, so we have to do it
  1909. // ourselves to force the HTTP response header and/or
  1910. // final DATA frame (with END_STREAM) to be sent.
  1911. rws.writeChunk(nil)
  1912. }
  1913. }
  1914. func (w *responseWriter) CloseNotify() <-chan bool {
  1915. rws := w.rws
  1916. if rws == nil {
  1917. panic("CloseNotify called after Handler finished")
  1918. }
  1919. rws.closeNotifierMu.Lock()
  1920. ch := rws.closeNotifierCh
  1921. if ch == nil {
  1922. ch = make(chan bool, 1)
  1923. rws.closeNotifierCh = ch
  1924. go func() {
  1925. rws.stream.cw.Wait() // wait for close
  1926. ch <- true
  1927. }()
  1928. }
  1929. rws.closeNotifierMu.Unlock()
  1930. return ch
  1931. }
  1932. func (w *responseWriter) Header() http.Header {
  1933. rws := w.rws
  1934. if rws == nil {
  1935. panic("Header called after Handler finished")
  1936. }
  1937. if rws.handlerHeader == nil {
  1938. rws.handlerHeader = make(http.Header)
  1939. }
  1940. return rws.handlerHeader
  1941. }
  1942. func (w *responseWriter) WriteHeader(code int) {
  1943. rws := w.rws
  1944. if rws == nil {
  1945. panic("WriteHeader called after Handler finished")
  1946. }
  1947. rws.writeHeader(code)
  1948. }
  1949. func (rws *responseWriterState) writeHeader(code int) {
  1950. if !rws.wroteHeader {
  1951. rws.wroteHeader = true
  1952. rws.status = code
  1953. if len(rws.handlerHeader) > 0 {
  1954. rws.snapHeader = cloneHeader(rws.handlerHeader)
  1955. }
  1956. }
  1957. }
  1958. func cloneHeader(h http.Header) http.Header {
  1959. h2 := make(http.Header, len(h))
  1960. for k, vv := range h {
  1961. vv2 := make([]string, len(vv))
  1962. copy(vv2, vv)
  1963. h2[k] = vv2
  1964. }
  1965. return h2
  1966. }
  1967. // The Life Of A Write is like this:
  1968. //
  1969. // * Handler calls w.Write or w.WriteString ->
  1970. // * -> rws.bw (*bufio.Writer) ->
  1971. // * (Handler migth call Flush)
  1972. // * -> chunkWriter{rws}
  1973. // * -> responseWriterState.writeChunk(p []byte)
  1974. // * -> responseWriterState.writeChunk (most of the magic; see comment there)
  1975. func (w *responseWriter) Write(p []byte) (n int, err error) {
  1976. return w.write(len(p), p, "")
  1977. }
  1978. func (w *responseWriter) WriteString(s string) (n int, err error) {
  1979. return w.write(len(s), nil, s)
  1980. }
  1981. // either dataB or dataS is non-zero.
  1982. func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  1983. rws := w.rws
  1984. if rws == nil {
  1985. panic("Write called after Handler finished")
  1986. }
  1987. if !rws.wroteHeader {
  1988. w.WriteHeader(200)
  1989. }
  1990. if !bodyAllowedForStatus(rws.status) {
  1991. return 0, http.ErrBodyNotAllowed
  1992. }
  1993. rws.wroteBytes += int64(len(dataB)) + int64(len(dataS)) // only one can be set
  1994. if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen {
  1995. // TODO: send a RST_STREAM
  1996. return 0, errors.New("http2: handler wrote more than declared Content-Length")
  1997. }
  1998. if dataB != nil {
  1999. return rws.bw.Write(dataB)
  2000. } else {
  2001. return rws.bw.WriteString(dataS)
  2002. }
  2003. }
  2004. func (w *responseWriter) handlerDone() {
  2005. rws := w.rws
  2006. rws.handlerDone = true
  2007. w.Flush()
  2008. w.rws = nil
  2009. responseWriterStatePool.Put(rws)
  2010. }
  2011. // foreachHeaderElement splits v according to the "#rule" construction
  2012. // in RFC 2616 section 2.1 and calls fn for each non-empty element.
  2013. func foreachHeaderElement(v string, fn func(string)) {
  2014. v = textproto.TrimString(v)
  2015. if v == "" {
  2016. return
  2017. }
  2018. if !strings.Contains(v, ",") {
  2019. fn(v)
  2020. return
  2021. }
  2022. for _, f := range strings.Split(v, ",") {
  2023. if f = textproto.TrimString(f); f != "" {
  2024. fn(f)
  2025. }
  2026. }
  2027. }