server.go 68 KB

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