server.go 67 KB

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