server.go 69 KB

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