server.go 63 KB

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