server.go 67 KB

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