server.go 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140
  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. }
  570. }
  571. // frameWriteResult is the message passed from writeFrameAsync to the serve goroutine.
  572. type frameWriteResult struct {
  573. wm frameWriteMsg // what was written (or attempted)
  574. err error // result of the writeFrame call
  575. }
  576. // writeFrameAsync runs in its own goroutine and writes a single frame
  577. // and then reports when it's done.
  578. // At most one goroutine can be running writeFrameAsync at a time per
  579. // serverConn.
  580. func (sc *serverConn) writeFrameAsync(wm frameWriteMsg) {
  581. err := wm.write.writeFrame(sc)
  582. sc.wroteFrameCh <- frameWriteResult{wm, err}
  583. }
  584. func (sc *serverConn) closeAllStreamsOnConnClose() {
  585. sc.serveG.check()
  586. for _, st := range sc.streams {
  587. sc.closeStream(st, errClientDisconnected)
  588. }
  589. }
  590. func (sc *serverConn) stopShutdownTimer() {
  591. sc.serveG.check()
  592. if t := sc.shutdownTimer; t != nil {
  593. t.Stop()
  594. }
  595. }
  596. func (sc *serverConn) notePanic() {
  597. // Note: this is for serverConn.serve panicking, not http.Handler code.
  598. if testHookOnPanicMu != nil {
  599. testHookOnPanicMu.Lock()
  600. defer testHookOnPanicMu.Unlock()
  601. }
  602. if testHookOnPanic != nil {
  603. if e := recover(); e != nil {
  604. if testHookOnPanic(sc, e) {
  605. panic(e)
  606. }
  607. }
  608. }
  609. }
  610. func (sc *serverConn) serve() {
  611. sc.serveG.check()
  612. defer sc.notePanic()
  613. defer sc.conn.Close()
  614. defer sc.closeAllStreamsOnConnClose()
  615. defer sc.stopShutdownTimer()
  616. defer close(sc.doneServing) // unblocks handlers trying to send
  617. sc.vlogf("HTTP/2 connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
  618. sc.writeFrame(frameWriteMsg{
  619. write: writeSettings{
  620. {SettingMaxFrameSize, sc.srv.maxReadFrameSize()},
  621. {SettingMaxConcurrentStreams, sc.advMaxStreams},
  622. {SettingMaxHeaderListSize, sc.maxHeaderListSize()},
  623. // TODO: more actual settings, notably
  624. // SettingInitialWindowSize, but then we also
  625. // want to bump up the conn window size the
  626. // same amount here right after the settings
  627. },
  628. })
  629. sc.unackedSettings++
  630. if err := sc.readPreface(); err != nil {
  631. sc.condlogf(err, "error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
  632. return
  633. }
  634. // Now that we've got the preface, get us out of the
  635. // "StateNew" state. We can't go directly to idle, though.
  636. // Active means we read some data and anticipate a request. We'll
  637. // do another Active when we get a HEADERS frame.
  638. sc.setConnState(http.StateActive)
  639. sc.setConnState(http.StateIdle)
  640. go sc.readFrames() // closed by defer sc.conn.Close above
  641. settingsTimer := time.NewTimer(firstSettingsTimeout)
  642. loopNum := 0
  643. for {
  644. loopNum++
  645. select {
  646. case wm := <-sc.wantWriteFrameCh:
  647. sc.writeFrame(wm)
  648. case res := <-sc.wroteFrameCh:
  649. sc.wroteFrame(res)
  650. case res := <-sc.readFrameCh:
  651. if !sc.processFrameFromReader(res) {
  652. return
  653. }
  654. res.readMore()
  655. if settingsTimer.C != nil {
  656. settingsTimer.Stop()
  657. settingsTimer.C = nil
  658. }
  659. case m := <-sc.bodyReadCh:
  660. sc.noteBodyRead(m.st, m.n)
  661. case <-settingsTimer.C:
  662. sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
  663. return
  664. case <-sc.shutdownTimerCh:
  665. sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
  666. return
  667. case fn := <-sc.testHookCh:
  668. fn(loopNum)
  669. }
  670. }
  671. }
  672. // readPreface reads the ClientPreface greeting from the peer
  673. // or returns an error on timeout or an invalid greeting.
  674. func (sc *serverConn) readPreface() error {
  675. errc := make(chan error, 1)
  676. go func() {
  677. // Read the client preface
  678. buf := make([]byte, len(ClientPreface))
  679. if _, err := io.ReadFull(sc.conn, buf); err != nil {
  680. errc <- err
  681. } else if !bytes.Equal(buf, clientPreface) {
  682. errc <- fmt.Errorf("bogus greeting %q", buf)
  683. } else {
  684. errc <- nil
  685. }
  686. }()
  687. timer := time.NewTimer(prefaceTimeout) // TODO: configurable on *Server?
  688. defer timer.Stop()
  689. select {
  690. case <-timer.C:
  691. return errors.New("timeout waiting for client preface")
  692. case err := <-errc:
  693. if err == nil {
  694. sc.vlogf("client %v said hello", sc.conn.RemoteAddr())
  695. }
  696. return err
  697. }
  698. }
  699. var errChanPool = sync.Pool{
  700. New: func() interface{} { return make(chan error, 1) },
  701. }
  702. var writeDataPool = sync.Pool{
  703. New: func() interface{} { return new(writeData) },
  704. }
  705. // writeDataFromHandler writes DATA response frames from a handler on
  706. // the given stream.
  707. func (sc *serverConn) writeDataFromHandler(stream *stream, data []byte, endStream bool) error {
  708. ch := errChanPool.Get().(chan error)
  709. writeArg := writeDataPool.Get().(*writeData)
  710. *writeArg = writeData{stream.id, data, endStream}
  711. err := sc.writeFrameFromHandler(frameWriteMsg{
  712. write: writeArg,
  713. stream: stream,
  714. done: ch,
  715. })
  716. if err != nil {
  717. return err
  718. }
  719. var frameWriteDone bool // the frame write is done (successfully or not)
  720. select {
  721. case err = <-ch:
  722. frameWriteDone = true
  723. case <-sc.doneServing:
  724. return errClientDisconnected
  725. case <-stream.cw:
  726. // If both ch and stream.cw were ready (as might
  727. // happen on the final Write after an http.Handler
  728. // ends), prefer the write result. Otherwise this
  729. // might just be us successfully closing the stream.
  730. // The writeFrameAsync and serve goroutines guarantee
  731. // that the ch send will happen before the stream.cw
  732. // close.
  733. select {
  734. case err = <-ch:
  735. frameWriteDone = true
  736. default:
  737. return errStreamClosed
  738. }
  739. }
  740. errChanPool.Put(ch)
  741. if frameWriteDone {
  742. writeDataPool.Put(writeArg)
  743. }
  744. return err
  745. }
  746. // writeFrameFromHandler sends wm to sc.wantWriteFrameCh, but aborts
  747. // if the connection has gone away.
  748. //
  749. // This must not be run from the serve goroutine itself, else it might
  750. // deadlock writing to sc.wantWriteFrameCh (which is only mildly
  751. // buffered and is read by serve itself). If you're on the serve
  752. // goroutine, call writeFrame instead.
  753. func (sc *serverConn) writeFrameFromHandler(wm frameWriteMsg) error {
  754. sc.serveG.checkNotOn() // NOT
  755. select {
  756. case sc.wantWriteFrameCh <- wm:
  757. return nil
  758. case <-sc.doneServing:
  759. // Serve loop is gone.
  760. // Client has closed their connection to the server.
  761. return errClientDisconnected
  762. }
  763. }
  764. // writeFrame schedules a frame to write and sends it if there's nothing
  765. // already being written.
  766. //
  767. // There is no pushback here (the serve goroutine never blocks). It's
  768. // the http.Handlers that block, waiting for their previous frames to
  769. // make it onto the wire
  770. //
  771. // If you're not on the serve goroutine, use writeFrameFromHandler instead.
  772. func (sc *serverConn) writeFrame(wm frameWriteMsg) {
  773. sc.serveG.check()
  774. sc.writeSched.add(wm)
  775. sc.scheduleFrameWrite()
  776. }
  777. // startFrameWrite starts a goroutine to write wm (in a separate
  778. // goroutine since that might block on the network), and updates the
  779. // serve goroutine's state about the world, updated from info in wm.
  780. func (sc *serverConn) startFrameWrite(wm frameWriteMsg) {
  781. sc.serveG.check()
  782. if sc.writingFrame {
  783. panic("internal error: can only be writing one frame at a time")
  784. }
  785. st := wm.stream
  786. if st != nil {
  787. switch st.state {
  788. case stateHalfClosedLocal:
  789. panic("internal error: attempt to send frame on half-closed-local stream")
  790. case stateClosed:
  791. if st.sentReset || st.gotReset {
  792. // Skip this frame.
  793. sc.scheduleFrameWrite()
  794. return
  795. }
  796. panic(fmt.Sprintf("internal error: attempt to send a write %v on a closed stream", wm))
  797. }
  798. }
  799. sc.writingFrame = true
  800. sc.needsFrameFlush = true
  801. go sc.writeFrameAsync(wm)
  802. }
  803. // errHandlerPanicked is the error given to any callers blocked in a read from
  804. // Request.Body when the main goroutine panics. Since most handlers read in the
  805. // the main ServeHTTP goroutine, this will show up rarely.
  806. var errHandlerPanicked = errors.New("http2: handler panicked")
  807. // wroteFrame is called on the serve goroutine with the result of
  808. // whatever happened on writeFrameAsync.
  809. func (sc *serverConn) wroteFrame(res frameWriteResult) {
  810. sc.serveG.check()
  811. if !sc.writingFrame {
  812. panic("internal error: expected to be already writing a frame")
  813. }
  814. sc.writingFrame = false
  815. wm := res.wm
  816. st := wm.stream
  817. closeStream := endsStream(wm.write)
  818. if _, ok := wm.write.(handlerPanicRST); ok {
  819. sc.closeStream(st, errHandlerPanicked)
  820. }
  821. // Reply (if requested) to the blocked ServeHTTP goroutine.
  822. if ch := wm.done; ch != nil {
  823. select {
  824. case ch <- res.err:
  825. default:
  826. panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wm.write))
  827. }
  828. }
  829. wm.write = nil // prevent use (assume it's tainted after wm.done send)
  830. if closeStream {
  831. if st == nil {
  832. panic("internal error: expecting non-nil stream")
  833. }
  834. switch st.state {
  835. case stateOpen:
  836. // Here we would go to stateHalfClosedLocal in
  837. // theory, but since our handler is done and
  838. // the net/http package provides no mechanism
  839. // for finishing writing to a ResponseWriter
  840. // while still reading data (see possible TODO
  841. // at top of this file), we go into closed
  842. // state here anyway, after telling the peer
  843. // we're hanging up on them.
  844. st.state = stateHalfClosedLocal // won't last long, but necessary for closeStream via resetStream
  845. errCancel := StreamError{st.id, ErrCodeCancel}
  846. sc.resetStream(errCancel)
  847. case stateHalfClosedRemote:
  848. sc.closeStream(st, errHandlerComplete)
  849. }
  850. }
  851. sc.scheduleFrameWrite()
  852. }
  853. // scheduleFrameWrite tickles the frame writing scheduler.
  854. //
  855. // If a frame is already being written, nothing happens. This will be called again
  856. // when the frame is done being written.
  857. //
  858. // If a frame isn't being written we need to send one, the best frame
  859. // to send is selected, preferring first things that aren't
  860. // stream-specific (e.g. ACKing settings), and then finding the
  861. // highest priority stream.
  862. //
  863. // If a frame isn't being written and there's nothing else to send, we
  864. // flush the write buffer.
  865. func (sc *serverConn) scheduleFrameWrite() {
  866. sc.serveG.check()
  867. if sc.writingFrame {
  868. return
  869. }
  870. if sc.needToSendGoAway {
  871. sc.needToSendGoAway = false
  872. sc.startFrameWrite(frameWriteMsg{
  873. write: &writeGoAway{
  874. maxStreamID: sc.maxStreamID,
  875. code: sc.goAwayCode,
  876. },
  877. })
  878. return
  879. }
  880. if sc.needToSendSettingsAck {
  881. sc.needToSendSettingsAck = false
  882. sc.startFrameWrite(frameWriteMsg{write: writeSettingsAck{}})
  883. return
  884. }
  885. if !sc.inGoAway {
  886. if wm, ok := sc.writeSched.take(); ok {
  887. sc.startFrameWrite(wm)
  888. return
  889. }
  890. }
  891. if sc.needsFrameFlush {
  892. sc.startFrameWrite(frameWriteMsg{write: flushFrameWriter{}})
  893. sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
  894. return
  895. }
  896. }
  897. func (sc *serverConn) goAway(code ErrCode) {
  898. sc.serveG.check()
  899. if sc.inGoAway {
  900. return
  901. }
  902. if code != ErrCodeNo {
  903. sc.shutDownIn(250 * time.Millisecond)
  904. } else {
  905. // TODO: configurable
  906. sc.shutDownIn(1 * time.Second)
  907. }
  908. sc.inGoAway = true
  909. sc.needToSendGoAway = true
  910. sc.goAwayCode = code
  911. sc.scheduleFrameWrite()
  912. }
  913. func (sc *serverConn) shutDownIn(d time.Duration) {
  914. sc.serveG.check()
  915. sc.shutdownTimer = time.NewTimer(d)
  916. sc.shutdownTimerCh = sc.shutdownTimer.C
  917. }
  918. func (sc *serverConn) resetStream(se StreamError) {
  919. sc.serveG.check()
  920. sc.writeFrame(frameWriteMsg{write: se})
  921. if st, ok := sc.streams[se.StreamID]; ok {
  922. st.sentReset = true
  923. sc.closeStream(st, se)
  924. }
  925. }
  926. // curHeaderStreamID returns the stream ID of the header block we're
  927. // currently in the middle of reading. If this returns non-zero, the
  928. // next frame must be a CONTINUATION with this stream id.
  929. func (sc *serverConn) curHeaderStreamID() uint32 {
  930. sc.serveG.check()
  931. st := sc.req.stream
  932. if st == nil {
  933. return 0
  934. }
  935. return st.id
  936. }
  937. // processFrameFromReader processes the serve loop's read from readFrameCh from the
  938. // frame-reading goroutine.
  939. // processFrameFromReader returns whether the connection should be kept open.
  940. func (sc *serverConn) processFrameFromReader(res readFrameResult) bool {
  941. sc.serveG.check()
  942. err := res.err
  943. if err != nil {
  944. if err == ErrFrameTooLarge {
  945. sc.goAway(ErrCodeFrameSize)
  946. return true // goAway will close the loop
  947. }
  948. clientGone := err == io.EOF || strings.Contains(err.Error(), "use of closed network connection")
  949. if clientGone {
  950. // TODO: could we also get into this state if
  951. // the peer does a half close
  952. // (e.g. CloseWrite) because they're done
  953. // sending frames but they're still wanting
  954. // our open replies? Investigate.
  955. // TODO: add CloseWrite to crypto/tls.Conn first
  956. // so we have a way to test this? I suppose
  957. // just for testing we could have a non-TLS mode.
  958. return false
  959. }
  960. } else {
  961. f := res.f
  962. sc.vlogf("got %v: %#v", f.Header(), f)
  963. err = sc.processFrame(f)
  964. if err == nil {
  965. return true
  966. }
  967. }
  968. switch ev := err.(type) {
  969. case StreamError:
  970. sc.resetStream(ev)
  971. return true
  972. case goAwayFlowError:
  973. sc.goAway(ErrCodeFlowControl)
  974. return true
  975. case ConnectionError:
  976. sc.logf("%v: %v", sc.conn.RemoteAddr(), ev)
  977. sc.goAway(ErrCode(ev))
  978. return true // goAway will handle shutdown
  979. default:
  980. if res.err != nil {
  981. sc.logf("disconnecting; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
  982. } else {
  983. sc.logf("disconnection due to other error: %v", err)
  984. }
  985. return false
  986. }
  987. }
  988. func (sc *serverConn) processFrame(f Frame) error {
  989. sc.serveG.check()
  990. // First frame received must be SETTINGS.
  991. if !sc.sawFirstSettings {
  992. if _, ok := f.(*SettingsFrame); !ok {
  993. return ConnectionError(ErrCodeProtocol)
  994. }
  995. sc.sawFirstSettings = true
  996. }
  997. if s := sc.curHeaderStreamID(); s != 0 {
  998. if cf, ok := f.(*ContinuationFrame); !ok {
  999. return ConnectionError(ErrCodeProtocol)
  1000. } else if cf.Header().StreamID != s {
  1001. return ConnectionError(ErrCodeProtocol)
  1002. }
  1003. }
  1004. switch f := f.(type) {
  1005. case *SettingsFrame:
  1006. return sc.processSettings(f)
  1007. case *HeadersFrame:
  1008. return sc.processHeaders(f)
  1009. case *ContinuationFrame:
  1010. return sc.processContinuation(f)
  1011. case *WindowUpdateFrame:
  1012. return sc.processWindowUpdate(f)
  1013. case *PingFrame:
  1014. return sc.processPing(f)
  1015. case *DataFrame:
  1016. return sc.processData(f)
  1017. case *RSTStreamFrame:
  1018. return sc.processResetStream(f)
  1019. case *PriorityFrame:
  1020. return sc.processPriority(f)
  1021. case *PushPromiseFrame:
  1022. // A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE
  1023. // frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1024. return ConnectionError(ErrCodeProtocol)
  1025. default:
  1026. sc.vlogf("Ignoring frame: %v", f.Header())
  1027. return nil
  1028. }
  1029. }
  1030. func (sc *serverConn) processPing(f *PingFrame) error {
  1031. sc.serveG.check()
  1032. if f.IsAck() {
  1033. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  1034. // containing this flag."
  1035. return nil
  1036. }
  1037. if f.StreamID != 0 {
  1038. // "PING frames are not associated with any individual
  1039. // stream. If a PING frame is received with a stream
  1040. // identifier field value other than 0x0, the recipient MUST
  1041. // respond with a connection error (Section 5.4.1) of type
  1042. // PROTOCOL_ERROR."
  1043. return ConnectionError(ErrCodeProtocol)
  1044. }
  1045. sc.writeFrame(frameWriteMsg{write: writePingAck{f}})
  1046. return nil
  1047. }
  1048. func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  1049. sc.serveG.check()
  1050. switch {
  1051. case f.StreamID != 0: // stream-level flow control
  1052. st := sc.streams[f.StreamID]
  1053. if st == nil {
  1054. // "WINDOW_UPDATE can be sent by a peer that has sent a
  1055. // frame bearing the END_STREAM flag. This means that a
  1056. // receiver could receive a WINDOW_UPDATE frame on a "half
  1057. // closed (remote)" or "closed" stream. A receiver MUST
  1058. // NOT treat this as an error, see Section 5.1."
  1059. return nil
  1060. }
  1061. if !st.flow.add(int32(f.Increment)) {
  1062. return StreamError{f.StreamID, ErrCodeFlowControl}
  1063. }
  1064. default: // connection-level flow control
  1065. if !sc.flow.add(int32(f.Increment)) {
  1066. return goAwayFlowError{}
  1067. }
  1068. }
  1069. sc.scheduleFrameWrite()
  1070. return nil
  1071. }
  1072. func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
  1073. sc.serveG.check()
  1074. state, st := sc.state(f.StreamID)
  1075. if state == stateIdle {
  1076. // 6.4 "RST_STREAM frames MUST NOT be sent for a
  1077. // stream in the "idle" state. If a RST_STREAM frame
  1078. // identifying an idle stream is received, the
  1079. // recipient MUST treat this as a connection error
  1080. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1081. return ConnectionError(ErrCodeProtocol)
  1082. }
  1083. if st != nil {
  1084. st.gotReset = true
  1085. sc.closeStream(st, StreamError{f.StreamID, f.ErrCode})
  1086. }
  1087. return nil
  1088. }
  1089. func (sc *serverConn) closeStream(st *stream, err error) {
  1090. sc.serveG.check()
  1091. if st.state == stateIdle || st.state == stateClosed {
  1092. panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
  1093. }
  1094. st.state = stateClosed
  1095. sc.curOpenStreams--
  1096. if sc.curOpenStreams == 0 {
  1097. sc.setConnState(http.StateIdle)
  1098. }
  1099. delete(sc.streams, st.id)
  1100. if p := st.body; p != nil {
  1101. p.CloseWithError(err)
  1102. }
  1103. st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc
  1104. sc.writeSched.forgetStream(st.id)
  1105. }
  1106. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  1107. sc.serveG.check()
  1108. if f.IsAck() {
  1109. sc.unackedSettings--
  1110. if sc.unackedSettings < 0 {
  1111. // Why is the peer ACKing settings we never sent?
  1112. // The spec doesn't mention this case, but
  1113. // hang up on them anyway.
  1114. return ConnectionError(ErrCodeProtocol)
  1115. }
  1116. return nil
  1117. }
  1118. if err := f.ForeachSetting(sc.processSetting); err != nil {
  1119. return err
  1120. }
  1121. sc.needToSendSettingsAck = true
  1122. sc.scheduleFrameWrite()
  1123. return nil
  1124. }
  1125. func (sc *serverConn) processSetting(s Setting) error {
  1126. sc.serveG.check()
  1127. if err := s.Valid(); err != nil {
  1128. return err
  1129. }
  1130. sc.vlogf("processing setting %v", s)
  1131. switch s.ID {
  1132. case SettingHeaderTableSize:
  1133. sc.headerTableSize = s.Val
  1134. sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
  1135. case SettingEnablePush:
  1136. sc.pushEnabled = s.Val != 0
  1137. case SettingMaxConcurrentStreams:
  1138. sc.clientMaxStreams = s.Val
  1139. case SettingInitialWindowSize:
  1140. return sc.processSettingInitialWindowSize(s.Val)
  1141. case SettingMaxFrameSize:
  1142. sc.writeSched.maxFrameSize = s.Val
  1143. case SettingMaxHeaderListSize:
  1144. sc.peerMaxHeaderListSize = s.Val
  1145. default:
  1146. // Unknown setting: "An endpoint that receives a SETTINGS
  1147. // frame with any unknown or unsupported identifier MUST
  1148. // ignore that setting."
  1149. }
  1150. return nil
  1151. }
  1152. func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  1153. sc.serveG.check()
  1154. // Note: val already validated to be within range by
  1155. // processSetting's Valid call.
  1156. // "A SETTINGS frame can alter the initial flow control window
  1157. // size for all current streams. When the value of
  1158. // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  1159. // adjust the size of all stream flow control windows that it
  1160. // maintains by the difference between the new value and the
  1161. // old value."
  1162. old := sc.initialWindowSize
  1163. sc.initialWindowSize = int32(val)
  1164. growth := sc.initialWindowSize - old // may be negative
  1165. for _, st := range sc.streams {
  1166. if !st.flow.add(growth) {
  1167. // 6.9.2 Initial Flow Control Window Size
  1168. // "An endpoint MUST treat a change to
  1169. // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  1170. // control window to exceed the maximum size as a
  1171. // connection error (Section 5.4.1) of type
  1172. // FLOW_CONTROL_ERROR."
  1173. return ConnectionError(ErrCodeFlowControl)
  1174. }
  1175. }
  1176. return nil
  1177. }
  1178. func (sc *serverConn) processData(f *DataFrame) error {
  1179. sc.serveG.check()
  1180. // "If a DATA frame is received whose stream is not in "open"
  1181. // or "half closed (local)" state, the recipient MUST respond
  1182. // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  1183. id := f.Header().StreamID
  1184. st, ok := sc.streams[id]
  1185. if !ok || st.state != stateOpen || st.gotTrailerHeader {
  1186. // This includes sending a RST_STREAM if the stream is
  1187. // in stateHalfClosedLocal (which currently means that
  1188. // the http.Handler returned, so it's done reading &
  1189. // done writing). Try to stop the client from sending
  1190. // more DATA.
  1191. return StreamError{id, ErrCodeStreamClosed}
  1192. }
  1193. if st.body == nil {
  1194. panic("internal error: should have a body in this state")
  1195. }
  1196. data := f.Data()
  1197. // Sender sending more than they'd declared?
  1198. if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  1199. st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  1200. return StreamError{id, ErrCodeStreamClosed}
  1201. }
  1202. if len(data) > 0 {
  1203. // Check whether the client has flow control quota.
  1204. if int(st.inflow.available()) < len(data) {
  1205. return StreamError{id, ErrCodeFlowControl}
  1206. }
  1207. st.inflow.take(int32(len(data)))
  1208. wrote, err := st.body.Write(data)
  1209. if err != nil {
  1210. return StreamError{id, ErrCodeStreamClosed}
  1211. }
  1212. if wrote != len(data) {
  1213. panic("internal error: bad Writer")
  1214. }
  1215. st.bodyBytes += int64(len(data))
  1216. }
  1217. if f.StreamEnded() {
  1218. st.endStream()
  1219. }
  1220. return nil
  1221. }
  1222. // endStream closes a Request.Body's pipe. It is called when a DATA
  1223. // frame says a request body is over (or after trailers).
  1224. func (st *stream) endStream() {
  1225. sc := st.sc
  1226. sc.serveG.check()
  1227. if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  1228. st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
  1229. st.declBodyBytes, st.bodyBytes))
  1230. } else {
  1231. st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest)
  1232. st.body.CloseWithError(io.EOF)
  1233. }
  1234. st.state = stateHalfClosedRemote
  1235. }
  1236. // copyTrailersToHandlerRequest is run in the Handler's goroutine in
  1237. // its Request.Body.Read just before it gets io.EOF.
  1238. func (st *stream) copyTrailersToHandlerRequest() {
  1239. for k, vv := range st.trailer {
  1240. if _, ok := st.reqTrailer[k]; ok {
  1241. // Only copy it over it was pre-declared.
  1242. st.reqTrailer[k] = vv
  1243. }
  1244. }
  1245. }
  1246. func (sc *serverConn) processHeaders(f *HeadersFrame) error {
  1247. sc.serveG.check()
  1248. id := f.Header().StreamID
  1249. if sc.inGoAway {
  1250. // Ignore.
  1251. return nil
  1252. }
  1253. // http://http2.github.io/http2-spec/#rfc.section.5.1.1
  1254. // Streams initiated by a client MUST use odd-numbered stream
  1255. // identifiers. [...] An endpoint that receives an unexpected
  1256. // stream identifier MUST respond with a connection error
  1257. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1258. if id%2 != 1 {
  1259. return ConnectionError(ErrCodeProtocol)
  1260. }
  1261. // A HEADERS frame can be used to create a new stream or
  1262. // send a trailer for an open one. If we already have a stream
  1263. // open, let it process its own HEADERS frame (trailers at this
  1264. // point, if it's valid).
  1265. st := sc.streams[f.Header().StreamID]
  1266. if st != nil {
  1267. return st.processTrailerHeaders(f)
  1268. }
  1269. // [...] The identifier of a newly established stream MUST be
  1270. // numerically greater than all streams that the initiating
  1271. // endpoint has opened or reserved. [...] An endpoint that
  1272. // receives an unexpected stream identifier MUST respond with
  1273. // a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1274. if id <= sc.maxStreamID || sc.req.stream != nil {
  1275. return ConnectionError(ErrCodeProtocol)
  1276. }
  1277. if id > sc.maxStreamID {
  1278. sc.maxStreamID = id
  1279. }
  1280. st = &stream{
  1281. sc: sc,
  1282. id: id,
  1283. state: stateOpen,
  1284. }
  1285. if f.StreamEnded() {
  1286. st.state = stateHalfClosedRemote
  1287. }
  1288. st.cw.Init()
  1289. st.flow.conn = &sc.flow // link to conn-level counter
  1290. st.flow.add(sc.initialWindowSize)
  1291. st.inflow.conn = &sc.inflow // link to conn-level counter
  1292. st.inflow.add(initialWindowSize) // TODO: update this when we send a higher initial window size in the initial settings
  1293. sc.streams[id] = st
  1294. if f.HasPriority() {
  1295. adjustStreamPriority(sc.streams, st.id, f.Priority)
  1296. }
  1297. sc.curOpenStreams++
  1298. if sc.curOpenStreams == 1 {
  1299. sc.setConnState(http.StateActive)
  1300. }
  1301. sc.req = requestParam{
  1302. stream: st,
  1303. header: make(http.Header),
  1304. }
  1305. sc.hpackDecoder.SetEmitFunc(sc.onNewHeaderField)
  1306. sc.hpackDecoder.SetEmitEnabled(true)
  1307. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  1308. }
  1309. func (st *stream) processTrailerHeaders(f *HeadersFrame) error {
  1310. sc := st.sc
  1311. sc.serveG.check()
  1312. if st.gotTrailerHeader {
  1313. return ConnectionError(ErrCodeProtocol)
  1314. }
  1315. st.gotTrailerHeader = true
  1316. return st.processTrailerHeaderBlockFragment(f.HeaderBlockFragment(), f.HeadersEnded())
  1317. }
  1318. func (sc *serverConn) processContinuation(f *ContinuationFrame) error {
  1319. sc.serveG.check()
  1320. st := sc.streams[f.Header().StreamID]
  1321. if st == nil || sc.curHeaderStreamID() != st.id {
  1322. return ConnectionError(ErrCodeProtocol)
  1323. }
  1324. if st.gotTrailerHeader {
  1325. return st.processTrailerHeaderBlockFragment(f.HeaderBlockFragment(), f.HeadersEnded())
  1326. }
  1327. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  1328. }
  1329. func (sc *serverConn) processHeaderBlockFragment(st *stream, frag []byte, end bool) error {
  1330. sc.serveG.check()
  1331. if _, err := sc.hpackDecoder.Write(frag); err != nil {
  1332. return ConnectionError(ErrCodeCompression)
  1333. }
  1334. if !end {
  1335. return nil
  1336. }
  1337. if err := sc.hpackDecoder.Close(); err != nil {
  1338. return ConnectionError(ErrCodeCompression)
  1339. }
  1340. defer sc.resetPendingRequest()
  1341. if sc.curOpenStreams > sc.advMaxStreams {
  1342. // "Endpoints MUST NOT exceed the limit set by their
  1343. // peer. An endpoint that receives a HEADERS frame
  1344. // that causes their advertised concurrent stream
  1345. // limit to be exceeded MUST treat this as a stream
  1346. // error (Section 5.4.2) of type PROTOCOL_ERROR or
  1347. // REFUSED_STREAM."
  1348. if sc.unackedSettings == 0 {
  1349. // They should know better.
  1350. return StreamError{st.id, ErrCodeProtocol}
  1351. }
  1352. // Assume it's a network race, where they just haven't
  1353. // received our last SETTINGS update. But actually
  1354. // this can't happen yet, because we don't yet provide
  1355. // a way for users to adjust server parameters at
  1356. // runtime.
  1357. return StreamError{st.id, ErrCodeRefusedStream}
  1358. }
  1359. rw, req, err := sc.newWriterAndRequest()
  1360. if err != nil {
  1361. return err
  1362. }
  1363. st.reqTrailer = req.Trailer
  1364. if st.reqTrailer != nil {
  1365. st.trailer = make(http.Header)
  1366. }
  1367. st.body = req.Body.(*requestBody).pipe // may be nil
  1368. st.declBodyBytes = req.ContentLength
  1369. handler := sc.handler.ServeHTTP
  1370. if !sc.hpackDecoder.EmitEnabled() {
  1371. // Their header list was too long. Send a 431 error.
  1372. handler = handleHeaderListTooLong
  1373. }
  1374. go sc.runHandler(rw, req, handler)
  1375. return nil
  1376. }
  1377. func (st *stream) processTrailerHeaderBlockFragment(frag []byte, end bool) error {
  1378. sc := st.sc
  1379. sc.serveG.check()
  1380. sc.hpackDecoder.SetEmitFunc(st.onNewTrailerField)
  1381. if _, err := sc.hpackDecoder.Write(frag); err != nil {
  1382. return ConnectionError(ErrCodeCompression)
  1383. }
  1384. if !end {
  1385. return nil
  1386. }
  1387. err := sc.hpackDecoder.Close()
  1388. st.endStream()
  1389. if err != nil {
  1390. return ConnectionError(ErrCodeCompression)
  1391. }
  1392. return nil
  1393. }
  1394. func (sc *serverConn) processPriority(f *PriorityFrame) error {
  1395. adjustStreamPriority(sc.streams, f.StreamID, f.PriorityParam)
  1396. return nil
  1397. }
  1398. func adjustStreamPriority(streams map[uint32]*stream, streamID uint32, priority PriorityParam) {
  1399. st, ok := streams[streamID]
  1400. if !ok {
  1401. // TODO: not quite correct (this streamID might
  1402. // already exist in the dep tree, but be closed), but
  1403. // close enough for now.
  1404. return
  1405. }
  1406. st.weight = priority.Weight
  1407. parent := streams[priority.StreamDep] // might be nil
  1408. if parent == st {
  1409. // if client tries to set this stream to be the parent of itself
  1410. // ignore and keep going
  1411. return
  1412. }
  1413. // section 5.3.3: If a stream is made dependent on one of its
  1414. // own dependencies, the formerly dependent stream is first
  1415. // moved to be dependent on the reprioritized stream's previous
  1416. // parent. The moved dependency retains its weight.
  1417. for piter := parent; piter != nil; piter = piter.parent {
  1418. if piter == st {
  1419. parent.parent = st.parent
  1420. break
  1421. }
  1422. }
  1423. st.parent = parent
  1424. if priority.Exclusive && (st.parent != nil || priority.StreamDep == 0) {
  1425. for _, openStream := range streams {
  1426. if openStream != st && openStream.parent == st.parent {
  1427. openStream.parent = st
  1428. }
  1429. }
  1430. }
  1431. }
  1432. // resetPendingRequest zeros out all state related to a HEADERS frame
  1433. // and its zero or more CONTINUATION frames sent to start a new
  1434. // request.
  1435. func (sc *serverConn) resetPendingRequest() {
  1436. sc.serveG.check()
  1437. sc.req = requestParam{}
  1438. }
  1439. func (sc *serverConn) newWriterAndRequest() (*responseWriter, *http.Request, error) {
  1440. sc.serveG.check()
  1441. rp := &sc.req
  1442. if rp.invalidHeader || rp.method == "" || rp.path == "" ||
  1443. (rp.scheme != "https" && rp.scheme != "http") {
  1444. // See 8.1.2.6 Malformed Requests and Responses:
  1445. //
  1446. // Malformed requests or responses that are detected
  1447. // MUST be treated as a stream error (Section 5.4.2)
  1448. // of type PROTOCOL_ERROR."
  1449. //
  1450. // 8.1.2.3 Request Pseudo-Header Fields
  1451. // "All HTTP/2 requests MUST include exactly one valid
  1452. // value for the :method, :scheme, and :path
  1453. // pseudo-header fields"
  1454. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1455. }
  1456. bodyOpen := rp.stream.state == stateOpen
  1457. if rp.method == "HEAD" && bodyOpen {
  1458. // HEAD requests can't have bodies
  1459. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1460. }
  1461. var tlsState *tls.ConnectionState // nil if not scheme https
  1462. if rp.scheme == "https" {
  1463. tlsState = sc.tlsState
  1464. }
  1465. authority := rp.authority
  1466. if authority == "" {
  1467. authority = rp.header.Get("Host")
  1468. }
  1469. needsContinue := rp.header.Get("Expect") == "100-continue"
  1470. if needsContinue {
  1471. rp.header.Del("Expect")
  1472. }
  1473. // Merge Cookie headers into one "; "-delimited value.
  1474. if cookies := rp.header["Cookie"]; len(cookies) > 1 {
  1475. rp.header.Set("Cookie", strings.Join(cookies, "; "))
  1476. }
  1477. // Setup Trailers
  1478. var trailer http.Header
  1479. for _, v := range rp.header["Trailer"] {
  1480. for _, key := range strings.Split(v, ",") {
  1481. key = http.CanonicalHeaderKey(strings.TrimSpace(key))
  1482. switch key {
  1483. case "Transfer-Encoding", "Trailer", "Content-Length":
  1484. // Bogus. (copy of http1 rules)
  1485. // Ignore.
  1486. default:
  1487. if trailer == nil {
  1488. trailer = make(http.Header)
  1489. }
  1490. trailer[key] = nil
  1491. }
  1492. }
  1493. }
  1494. delete(rp.header, "Trailer")
  1495. body := &requestBody{
  1496. conn: sc,
  1497. stream: rp.stream,
  1498. needsContinue: needsContinue,
  1499. }
  1500. // TODO: handle asterisk '*' requests + test
  1501. url, err := url.ParseRequestURI(rp.path)
  1502. if err != nil {
  1503. // TODO: find the right error code?
  1504. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1505. }
  1506. req := &http.Request{
  1507. Method: rp.method,
  1508. URL: url,
  1509. RemoteAddr: sc.remoteAddrStr,
  1510. Header: rp.header,
  1511. RequestURI: rp.path,
  1512. Proto: "HTTP/2.0",
  1513. ProtoMajor: 2,
  1514. ProtoMinor: 0,
  1515. TLS: tlsState,
  1516. Host: authority,
  1517. Body: body,
  1518. Trailer: trailer,
  1519. }
  1520. if bodyOpen {
  1521. body.pipe = &pipe{
  1522. b: &fixedBuffer{buf: make([]byte, initialWindowSize)}, // TODO: garbage
  1523. }
  1524. if vv, ok := rp.header["Content-Length"]; ok {
  1525. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  1526. } else {
  1527. req.ContentLength = -1
  1528. }
  1529. }
  1530. rws := responseWriterStatePool.Get().(*responseWriterState)
  1531. bwSave := rws.bw
  1532. *rws = responseWriterState{} // zero all the fields
  1533. rws.conn = sc
  1534. rws.bw = bwSave
  1535. rws.bw.Reset(chunkWriter{rws})
  1536. rws.stream = rp.stream
  1537. rws.req = req
  1538. rws.body = body
  1539. rw := &responseWriter{rws: rws}
  1540. return rw, req, nil
  1541. }
  1542. // Run on its own goroutine.
  1543. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) {
  1544. didPanic := true
  1545. defer func() {
  1546. if didPanic {
  1547. e := recover()
  1548. // Same as net/http:
  1549. const size = 64 << 10
  1550. buf := make([]byte, size)
  1551. buf = buf[:runtime.Stack(buf, false)]
  1552. sc.writeFrameFromHandler(frameWriteMsg{
  1553. write: handlerPanicRST{rw.rws.stream.id},
  1554. stream: rw.rws.stream,
  1555. })
  1556. sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf)
  1557. return
  1558. }
  1559. rw.handlerDone()
  1560. }()
  1561. handler(rw, req)
  1562. didPanic = false
  1563. }
  1564. func handleHeaderListTooLong(w http.ResponseWriter, r *http.Request) {
  1565. // 10.5.1 Limits on Header Block Size:
  1566. // .. "A server that receives a larger header block than it is
  1567. // willing to handle can send an HTTP 431 (Request Header Fields Too
  1568. // Large) status code"
  1569. const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+
  1570. w.WriteHeader(statusRequestHeaderFieldsTooLarge)
  1571. io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
  1572. }
  1573. // called from handler goroutines.
  1574. // h may be nil.
  1575. func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error {
  1576. sc.serveG.checkNotOn() // NOT on
  1577. var errc chan error
  1578. if headerData.h != nil {
  1579. // If there's a header map (which we don't own), so we have to block on
  1580. // waiting for this frame to be written, so an http.Flush mid-handler
  1581. // writes out the correct value of keys, before a handler later potentially
  1582. // mutates it.
  1583. errc = errChanPool.Get().(chan error)
  1584. }
  1585. if err := sc.writeFrameFromHandler(frameWriteMsg{
  1586. write: headerData,
  1587. stream: st,
  1588. done: errc,
  1589. }); err != nil {
  1590. return err
  1591. }
  1592. if errc != nil {
  1593. select {
  1594. case err := <-errc:
  1595. errChanPool.Put(errc)
  1596. return err
  1597. case <-sc.doneServing:
  1598. return errClientDisconnected
  1599. case <-st.cw:
  1600. return errStreamClosed
  1601. }
  1602. }
  1603. return nil
  1604. }
  1605. // called from handler goroutines.
  1606. func (sc *serverConn) write100ContinueHeaders(st *stream) {
  1607. sc.writeFrameFromHandler(frameWriteMsg{
  1608. write: write100ContinueHeadersFrame{st.id},
  1609. stream: st,
  1610. })
  1611. }
  1612. // A bodyReadMsg tells the server loop that the http.Handler read n
  1613. // bytes of the DATA from the client on the given stream.
  1614. type bodyReadMsg struct {
  1615. st *stream
  1616. n int
  1617. }
  1618. // called from handler goroutines.
  1619. // Notes that the handler for the given stream ID read n bytes of its body
  1620. // and schedules flow control tokens to be sent.
  1621. func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int) {
  1622. sc.serveG.checkNotOn() // NOT on
  1623. select {
  1624. case sc.bodyReadCh <- bodyReadMsg{st, n}:
  1625. case <-sc.doneServing:
  1626. }
  1627. }
  1628. func (sc *serverConn) noteBodyRead(st *stream, n int) {
  1629. sc.serveG.check()
  1630. sc.sendWindowUpdate(nil, n) // conn-level
  1631. if st.state != stateHalfClosedRemote && st.state != stateClosed {
  1632. // Don't send this WINDOW_UPDATE if the stream is closed
  1633. // remotely.
  1634. sc.sendWindowUpdate(st, n)
  1635. }
  1636. }
  1637. // st may be nil for conn-level
  1638. func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
  1639. sc.serveG.check()
  1640. // "The legal range for the increment to the flow control
  1641. // window is 1 to 2^31-1 (2,147,483,647) octets."
  1642. // A Go Read call on 64-bit machines could in theory read
  1643. // a larger Read than this. Very unlikely, but we handle it here
  1644. // rather than elsewhere for now.
  1645. const maxUint31 = 1<<31 - 1
  1646. for n >= maxUint31 {
  1647. sc.sendWindowUpdate32(st, maxUint31)
  1648. n -= maxUint31
  1649. }
  1650. sc.sendWindowUpdate32(st, int32(n))
  1651. }
  1652. // st may be nil for conn-level
  1653. func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) {
  1654. sc.serveG.check()
  1655. if n == 0 {
  1656. return
  1657. }
  1658. if n < 0 {
  1659. panic("negative update")
  1660. }
  1661. var streamID uint32
  1662. if st != nil {
  1663. streamID = st.id
  1664. }
  1665. sc.writeFrame(frameWriteMsg{
  1666. write: writeWindowUpdate{streamID: streamID, n: uint32(n)},
  1667. stream: st,
  1668. })
  1669. var ok bool
  1670. if st == nil {
  1671. ok = sc.inflow.add(n)
  1672. } else {
  1673. ok = st.inflow.add(n)
  1674. }
  1675. if !ok {
  1676. panic("internal error; sent too many window updates without decrements?")
  1677. }
  1678. }
  1679. type requestBody struct {
  1680. stream *stream
  1681. conn *serverConn
  1682. closed bool
  1683. pipe *pipe // non-nil if we have a HTTP entity message body
  1684. needsContinue bool // need to send a 100-continue
  1685. }
  1686. func (b *requestBody) Close() error {
  1687. if b.pipe != nil {
  1688. b.pipe.CloseWithError(errClosedBody)
  1689. }
  1690. b.closed = true
  1691. return nil
  1692. }
  1693. func (b *requestBody) Read(p []byte) (n int, err error) {
  1694. if b.needsContinue {
  1695. b.needsContinue = false
  1696. b.conn.write100ContinueHeaders(b.stream)
  1697. }
  1698. if b.pipe == nil {
  1699. return 0, io.EOF
  1700. }
  1701. n, err = b.pipe.Read(p)
  1702. if n > 0 {
  1703. b.conn.noteBodyReadFromHandler(b.stream, n)
  1704. }
  1705. return
  1706. }
  1707. // responseWriter is the http.ResponseWriter implementation. It's
  1708. // intentionally small (1 pointer wide) to minimize garbage. The
  1709. // responseWriterState pointer inside is zeroed at the end of a
  1710. // request (in handlerDone) and calls on the responseWriter thereafter
  1711. // simply crash (caller's mistake), but the much larger responseWriterState
  1712. // and buffers are reused between multiple requests.
  1713. type responseWriter struct {
  1714. rws *responseWriterState
  1715. }
  1716. // Optional http.ResponseWriter interfaces implemented.
  1717. var (
  1718. _ http.CloseNotifier = (*responseWriter)(nil)
  1719. _ http.Flusher = (*responseWriter)(nil)
  1720. _ stringWriter = (*responseWriter)(nil)
  1721. )
  1722. type responseWriterState struct {
  1723. // immutable within a request:
  1724. stream *stream
  1725. req *http.Request
  1726. body *requestBody // to close at end of request, if DATA frames didn't
  1727. conn *serverConn
  1728. // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
  1729. bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
  1730. // mutated by http.Handler goroutine:
  1731. handlerHeader http.Header // nil until called
  1732. snapHeader http.Header // snapshot of handlerHeader at WriteHeader time
  1733. trailers []string // set in writeChunk
  1734. status int // status code passed to WriteHeader
  1735. wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
  1736. sentHeader bool // have we sent the header frame?
  1737. handlerDone bool // handler has finished
  1738. sentContentLen int64 // non-zero if handler set a Content-Length header
  1739. wroteBytes int64
  1740. closeNotifierMu sync.Mutex // guards closeNotifierCh
  1741. closeNotifierCh chan bool // nil until first used
  1742. }
  1743. type chunkWriter struct{ rws *responseWriterState }
  1744. func (cw chunkWriter) Write(p []byte) (n int, err error) { return cw.rws.writeChunk(p) }
  1745. func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) != 0 }
  1746. // declareTrailer is called for each Trailer header when the
  1747. // response header is written. It notes that a header will need to be
  1748. // written in the trailers at the end of the response.
  1749. func (rws *responseWriterState) declareTrailer(k string) {
  1750. k = http.CanonicalHeaderKey(k)
  1751. switch k {
  1752. case "Transfer-Encoding", "Content-Length", "Trailer":
  1753. // Forbidden by RFC 2616 14.40.
  1754. return
  1755. }
  1756. rws.trailers = append(rws.trailers, k)
  1757. }
  1758. // writeChunk writes chunks from the bufio.Writer. But because
  1759. // bufio.Writer may bypass its chunking, sometimes p may be
  1760. // arbitrarily large.
  1761. //
  1762. // writeChunk is also responsible (on the first chunk) for sending the
  1763. // HEADER response.
  1764. func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
  1765. if !rws.wroteHeader {
  1766. rws.writeHeader(200)
  1767. }
  1768. isHeadResp := rws.req.Method == "HEAD"
  1769. if !rws.sentHeader {
  1770. rws.sentHeader = true
  1771. var ctype, clen string
  1772. if clen = rws.snapHeader.Get("Content-Length"); clen != "" {
  1773. rws.snapHeader.Del("Content-Length")
  1774. clen64, err := strconv.ParseInt(clen, 10, 64)
  1775. if err == nil && clen64 >= 0 {
  1776. rws.sentContentLen = clen64
  1777. } else {
  1778. clen = ""
  1779. }
  1780. }
  1781. if clen == "" && rws.handlerDone && bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) {
  1782. clen = strconv.Itoa(len(p))
  1783. }
  1784. _, hasContentType := rws.snapHeader["Content-Type"]
  1785. if !hasContentType && bodyAllowedForStatus(rws.status) {
  1786. ctype = http.DetectContentType(p)
  1787. }
  1788. var date string
  1789. if _, ok := rws.snapHeader["Date"]; !ok {
  1790. // TODO(bradfitz): be faster here, like net/http? measure.
  1791. date = time.Now().UTC().Format(http.TimeFormat)
  1792. }
  1793. for _, v := range rws.snapHeader["Trailer"] {
  1794. foreachHeaderElement(v, rws.declareTrailer)
  1795. }
  1796. endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp
  1797. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  1798. streamID: rws.stream.id,
  1799. httpResCode: rws.status,
  1800. h: rws.snapHeader,
  1801. endStream: endStream,
  1802. contentType: ctype,
  1803. contentLength: clen,
  1804. date: date,
  1805. })
  1806. if err != nil {
  1807. return 0, err
  1808. }
  1809. if endStream {
  1810. return 0, nil
  1811. }
  1812. }
  1813. if isHeadResp {
  1814. return len(p), nil
  1815. }
  1816. if len(p) == 0 && !rws.handlerDone {
  1817. return 0, nil
  1818. }
  1819. endStream := rws.handlerDone && !rws.hasTrailers()
  1820. if len(p) > 0 || endStream {
  1821. // only send a 0 byte DATA frame if we're ending the stream.
  1822. if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil {
  1823. return 0, err
  1824. }
  1825. }
  1826. if rws.handlerDone && rws.hasTrailers() {
  1827. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  1828. streamID: rws.stream.id,
  1829. h: rws.handlerHeader,
  1830. trailers: rws.trailers,
  1831. endStream: true,
  1832. })
  1833. return len(p), err
  1834. }
  1835. return len(p), nil
  1836. }
  1837. func (w *responseWriter) Flush() {
  1838. rws := w.rws
  1839. if rws == nil {
  1840. panic("Header called after Handler finished")
  1841. }
  1842. if rws.bw.Buffered() > 0 {
  1843. if err := rws.bw.Flush(); err != nil {
  1844. // Ignore the error. The frame writer already knows.
  1845. return
  1846. }
  1847. } else {
  1848. // The bufio.Writer won't call chunkWriter.Write
  1849. // (writeChunk with zero bytes, so we have to do it
  1850. // ourselves to force the HTTP response header and/or
  1851. // final DATA frame (with END_STREAM) to be sent.
  1852. rws.writeChunk(nil)
  1853. }
  1854. }
  1855. func (w *responseWriter) CloseNotify() <-chan bool {
  1856. rws := w.rws
  1857. if rws == nil {
  1858. panic("CloseNotify called after Handler finished")
  1859. }
  1860. rws.closeNotifierMu.Lock()
  1861. ch := rws.closeNotifierCh
  1862. if ch == nil {
  1863. ch = make(chan bool, 1)
  1864. rws.closeNotifierCh = ch
  1865. go func() {
  1866. rws.stream.cw.Wait() // wait for close
  1867. ch <- true
  1868. }()
  1869. }
  1870. rws.closeNotifierMu.Unlock()
  1871. return ch
  1872. }
  1873. func (w *responseWriter) Header() http.Header {
  1874. rws := w.rws
  1875. if rws == nil {
  1876. panic("Header called after Handler finished")
  1877. }
  1878. if rws.handlerHeader == nil {
  1879. rws.handlerHeader = make(http.Header)
  1880. }
  1881. return rws.handlerHeader
  1882. }
  1883. func (w *responseWriter) WriteHeader(code int) {
  1884. rws := w.rws
  1885. if rws == nil {
  1886. panic("WriteHeader called after Handler finished")
  1887. }
  1888. rws.writeHeader(code)
  1889. }
  1890. func (rws *responseWriterState) writeHeader(code int) {
  1891. if !rws.wroteHeader {
  1892. rws.wroteHeader = true
  1893. rws.status = code
  1894. if len(rws.handlerHeader) > 0 {
  1895. rws.snapHeader = cloneHeader(rws.handlerHeader)
  1896. }
  1897. }
  1898. }
  1899. func cloneHeader(h http.Header) http.Header {
  1900. h2 := make(http.Header, len(h))
  1901. for k, vv := range h {
  1902. vv2 := make([]string, len(vv))
  1903. copy(vv2, vv)
  1904. h2[k] = vv2
  1905. }
  1906. return h2
  1907. }
  1908. // The Life Of A Write is like this:
  1909. //
  1910. // * Handler calls w.Write or w.WriteString ->
  1911. // * -> rws.bw (*bufio.Writer) ->
  1912. // * (Handler migth call Flush)
  1913. // * -> chunkWriter{rws}
  1914. // * -> responseWriterState.writeChunk(p []byte)
  1915. // * -> responseWriterState.writeChunk (most of the magic; see comment there)
  1916. func (w *responseWriter) Write(p []byte) (n int, err error) {
  1917. return w.write(len(p), p, "")
  1918. }
  1919. func (w *responseWriter) WriteString(s string) (n int, err error) {
  1920. return w.write(len(s), nil, s)
  1921. }
  1922. // either dataB or dataS is non-zero.
  1923. func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  1924. rws := w.rws
  1925. if rws == nil {
  1926. panic("Write called after Handler finished")
  1927. }
  1928. if !rws.wroteHeader {
  1929. w.WriteHeader(200)
  1930. }
  1931. if !bodyAllowedForStatus(rws.status) {
  1932. return 0, http.ErrBodyNotAllowed
  1933. }
  1934. rws.wroteBytes += int64(len(dataB)) + int64(len(dataS)) // only one can be set
  1935. if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen {
  1936. // TODO: send a RST_STREAM
  1937. return 0, errors.New("http2: handler wrote more than declared Content-Length")
  1938. }
  1939. if dataB != nil {
  1940. return rws.bw.Write(dataB)
  1941. } else {
  1942. return rws.bw.WriteString(dataS)
  1943. }
  1944. }
  1945. func (w *responseWriter) handlerDone() {
  1946. rws := w.rws
  1947. rws.handlerDone = true
  1948. w.Flush()
  1949. w.rws = nil
  1950. responseWriterStatePool.Put(rws)
  1951. }
  1952. // foreachHeaderElement splits v according to the "#rule" construction
  1953. // in RFC 2616 section 2.1 and calls fn for each non-empty element.
  1954. func foreachHeaderElement(v string, fn func(string)) {
  1955. v = textproto.TrimString(v)
  1956. if v == "" {
  1957. return
  1958. }
  1959. if !strings.Contains(v, ",") {
  1960. fn(v)
  1961. return
  1962. }
  1963. for _, f := range strings.Split(v, ",") {
  1964. if f = textproto.TrimString(f); f != "" {
  1965. fn(f)
  1966. }
  1967. }
  1968. }