server.go 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863
  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: turn off the serve goroutine when idle, so
  5. // an idle conn only has the readFrames goroutine active. (which could
  6. // also be optimized probably to pin less memory in crypto/tls). This
  7. // would involve tracking when the serve goroutine is active (atomic
  8. // int32 read/CAS probably?) and starting it up when frames arrive,
  9. // and shutting it down when all handlers exit. the occasional PING
  10. // packets could use time.AfterFunc to call sc.wakeStartServeLoop()
  11. // (which is a no-op if already running) and then queue the PING write
  12. // as normal. The serve loop would then exit in most cases (if no
  13. // Handlers running) and not be woken up again until the PING packet
  14. // returns.
  15. // TODO (maybe): add a mechanism for Handlers to going into
  16. // half-closed-local mode (rw.(io.Closer) test?) but not exit their
  17. // handler, and continue to be able to read from the
  18. // Request.Body. This would be a somewhat semantic change from HTTP/1
  19. // (or at least what we expose in net/http), so I'd probably want to
  20. // add it there too. For now, this package says that returning from
  21. // the Handler ServeHTTP function means you're both done reading and
  22. // done writing, without a way to stop just one or the other.
  23. package http2
  24. import (
  25. "bufio"
  26. "bytes"
  27. "crypto/tls"
  28. "errors"
  29. "fmt"
  30. "io"
  31. "log"
  32. "math"
  33. "net"
  34. "net/http"
  35. "net/textproto"
  36. "net/url"
  37. "os"
  38. "reflect"
  39. "runtime"
  40. "strconv"
  41. "strings"
  42. "sync"
  43. "time"
  44. "golang.org/x/net/http2/hpack"
  45. )
  46. const (
  47. prefaceTimeout = 10 * time.Second
  48. firstSettingsTimeout = 2 * time.Second // should be in-flight with preface anyway
  49. handlerChunkWriteSize = 4 << 10
  50. defaultMaxStreams = 250 // TODO: make this 100 as the GFE seems to?
  51. )
  52. var (
  53. errClientDisconnected = errors.New("client disconnected")
  54. errClosedBody = errors.New("body closed by handler")
  55. errHandlerComplete = errors.New("http2: request body closed due to handler exiting")
  56. errStreamClosed = errors.New("http2: stream closed")
  57. )
  58. var responseWriterStatePool = sync.Pool{
  59. New: func() interface{} {
  60. rws := &responseWriterState{}
  61. rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize)
  62. return rws
  63. },
  64. }
  65. // Test hooks.
  66. var (
  67. testHookOnConn func()
  68. testHookGetServerConn func(*serverConn)
  69. testHookOnPanicMu *sync.Mutex // nil except in tests
  70. testHookOnPanic func(sc *serverConn, panicVal interface{}) (rePanic bool)
  71. )
  72. // Server is an HTTP/2 server.
  73. type Server struct {
  74. // MaxHandlers limits the number of http.Handler ServeHTTP goroutines
  75. // which may run at a time over all connections.
  76. // Negative or zero no limit.
  77. // TODO: implement
  78. MaxHandlers int
  79. // MaxConcurrentStreams optionally specifies the number of
  80. // concurrent streams that each client may have open at a
  81. // time. This is unrelated to the number of http.Handler goroutines
  82. // which may be active globally, which is MaxHandlers.
  83. // If zero, MaxConcurrentStreams defaults to at least 100, per
  84. // the HTTP/2 spec's recommendations.
  85. MaxConcurrentStreams uint32
  86. // MaxReadFrameSize optionally specifies the largest frame
  87. // this server is willing to read. A valid value is between
  88. // 16k and 16M, inclusive. If zero or otherwise invalid, a
  89. // default value is used.
  90. MaxReadFrameSize uint32
  91. // PermitProhibitedCipherSuites, if true, permits the use of
  92. // cipher suites prohibited by the HTTP/2 spec.
  93. PermitProhibitedCipherSuites bool
  94. // IdleTimeout specifies how long until idle clients should be
  95. // closed with a GOAWAY frame. PING frames are not considered
  96. // activity for the purposes of IdleTimeout.
  97. IdleTimeout time.Duration
  98. // MaxUploadBufferPerConnection is the size of the initial flow
  99. // control window for each connections. The HTTP/2 spec does not
  100. // allow this to be smaller than 65535 or larger than 2^32-1.
  101. // If the value is outside this range, a default value will be
  102. // used instead.
  103. MaxUploadBufferPerConnection int32
  104. // MaxUploadBufferPerStream is the size of the initial flow control
  105. // window for each stream. The HTTP/2 spec does not allow this to
  106. // be larger than 2^32-1. If the value is zero or larger than the
  107. // maximum, a default value will be used instead.
  108. MaxUploadBufferPerStream int32
  109. // NewWriteScheduler constructs a write scheduler for a connection.
  110. // If nil, a default scheduler is chosen.
  111. NewWriteScheduler func() WriteScheduler
  112. // Internal state. This is a pointer (rather than embedded directly)
  113. // so that we don't embed a Mutex in this struct, which will make the
  114. // struct non-copyable, which might break some callers.
  115. state *serverInternalState
  116. }
  117. func (s *Server) initialConnRecvWindowSize() int32 {
  118. if s.MaxUploadBufferPerConnection > initialWindowSize {
  119. return s.MaxUploadBufferPerConnection
  120. }
  121. return 1 << 20
  122. }
  123. func (s *Server) initialStreamRecvWindowSize() int32 {
  124. if s.MaxUploadBufferPerStream > 0 {
  125. return s.MaxUploadBufferPerStream
  126. }
  127. return 1 << 20
  128. }
  129. func (s *Server) maxReadFrameSize() uint32 {
  130. if v := s.MaxReadFrameSize; v >= minMaxFrameSize && v <= maxFrameSize {
  131. return v
  132. }
  133. return defaultMaxReadFrameSize
  134. }
  135. func (s *Server) maxConcurrentStreams() uint32 {
  136. if v := s.MaxConcurrentStreams; v > 0 {
  137. return v
  138. }
  139. return defaultMaxStreams
  140. }
  141. type serverInternalState struct {
  142. mu sync.Mutex
  143. activeConns map[*serverConn]struct{}
  144. }
  145. func (s *serverInternalState) registerConn(sc *serverConn) {
  146. if s == nil {
  147. return // if the Server was used without calling ConfigureServer
  148. }
  149. s.mu.Lock()
  150. s.activeConns[sc] = struct{}{}
  151. s.mu.Unlock()
  152. }
  153. func (s *serverInternalState) unregisterConn(sc *serverConn) {
  154. if s == nil {
  155. return // if the Server was used without calling ConfigureServer
  156. }
  157. s.mu.Lock()
  158. delete(s.activeConns, sc)
  159. s.mu.Unlock()
  160. }
  161. func (s *serverInternalState) startGracefulShutdown() {
  162. if s == nil {
  163. return // if the Server was used without calling ConfigureServer
  164. }
  165. s.mu.Lock()
  166. for sc := range s.activeConns {
  167. sc.startGracefulShutdown()
  168. }
  169. s.mu.Unlock()
  170. }
  171. // ConfigureServer adds HTTP/2 support to a net/http Server.
  172. //
  173. // The configuration conf may be nil.
  174. //
  175. // ConfigureServer must be called before s begins serving.
  176. func ConfigureServer(s *http.Server, conf *Server) error {
  177. if s == nil {
  178. panic("nil *http.Server")
  179. }
  180. if conf == nil {
  181. conf = new(Server)
  182. }
  183. conf.state = &serverInternalState{activeConns: make(map[*serverConn]struct{})}
  184. if err := configureServer18(s, conf); err != nil {
  185. return err
  186. }
  187. if err := configureServer19(s, conf); err != nil {
  188. return err
  189. }
  190. if s.TLSConfig == nil {
  191. s.TLSConfig = new(tls.Config)
  192. } else if s.TLSConfig.CipherSuites != nil {
  193. // If they already provided a CipherSuite list, return
  194. // an error if it has a bad order or is missing
  195. // ECDHE_RSA_WITH_AES_128_GCM_SHA256.
  196. const requiredCipher = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  197. haveRequired := false
  198. sawBad := false
  199. for i, cs := range s.TLSConfig.CipherSuites {
  200. if cs == requiredCipher {
  201. haveRequired = true
  202. }
  203. if isBadCipher(cs) {
  204. sawBad = true
  205. } else if sawBad {
  206. 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)
  207. }
  208. }
  209. if !haveRequired {
  210. return fmt.Errorf("http2: TLSConfig.CipherSuites is missing HTTP/2-required TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256")
  211. }
  212. }
  213. // Note: not setting MinVersion to tls.VersionTLS12,
  214. // as we don't want to interfere with HTTP/1.1 traffic
  215. // on the user's server. We enforce TLS 1.2 later once
  216. // we accept a connection. Ideally this should be done
  217. // during next-proto selection, but using TLS <1.2 with
  218. // HTTP/2 is still the client's bug.
  219. s.TLSConfig.PreferServerCipherSuites = true
  220. haveNPN := false
  221. for _, p := range s.TLSConfig.NextProtos {
  222. if p == NextProtoTLS {
  223. haveNPN = true
  224. break
  225. }
  226. }
  227. if !haveNPN {
  228. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, NextProtoTLS)
  229. }
  230. if s.TLSNextProto == nil {
  231. s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
  232. }
  233. protoHandler := func(hs *http.Server, c *tls.Conn, h http.Handler) {
  234. if testHookOnConn != nil {
  235. testHookOnConn()
  236. }
  237. conf.ServeConn(c, &ServeConnOpts{
  238. Handler: h,
  239. BaseConfig: hs,
  240. })
  241. }
  242. s.TLSNextProto[NextProtoTLS] = protoHandler
  243. return nil
  244. }
  245. // ServeConnOpts are options for the Server.ServeConn method.
  246. type ServeConnOpts struct {
  247. // BaseConfig optionally sets the base configuration
  248. // for values. If nil, defaults are used.
  249. BaseConfig *http.Server
  250. // Handler specifies which handler to use for processing
  251. // requests. If nil, BaseConfig.Handler is used. If BaseConfig
  252. // or BaseConfig.Handler is nil, http.DefaultServeMux is used.
  253. Handler http.Handler
  254. }
  255. func (o *ServeConnOpts) baseConfig() *http.Server {
  256. if o != nil && o.BaseConfig != nil {
  257. return o.BaseConfig
  258. }
  259. return new(http.Server)
  260. }
  261. func (o *ServeConnOpts) handler() http.Handler {
  262. if o != nil {
  263. if o.Handler != nil {
  264. return o.Handler
  265. }
  266. if o.BaseConfig != nil && o.BaseConfig.Handler != nil {
  267. return o.BaseConfig.Handler
  268. }
  269. }
  270. return http.DefaultServeMux
  271. }
  272. // ServeConn serves HTTP/2 requests on the provided connection and
  273. // blocks until the connection is no longer readable.
  274. //
  275. // ServeConn starts speaking HTTP/2 assuming that c has not had any
  276. // reads or writes. It writes its initial settings frame and expects
  277. // to be able to read the preface and settings frame from the
  278. // client. If c has a ConnectionState method like a *tls.Conn, the
  279. // ConnectionState is used to verify the TLS ciphersuite and to set
  280. // the Request.TLS field in Handlers.
  281. //
  282. // ServeConn does not support h2c by itself. Any h2c support must be
  283. // implemented in terms of providing a suitably-behaving net.Conn.
  284. //
  285. // The opts parameter is optional. If nil, default values are used.
  286. func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) {
  287. baseCtx, cancel := serverConnBaseContext(c, opts)
  288. defer cancel()
  289. sc := &serverConn{
  290. srv: s,
  291. hs: opts.baseConfig(),
  292. conn: c,
  293. baseCtx: baseCtx,
  294. remoteAddrStr: c.RemoteAddr().String(),
  295. bw: newBufferedWriter(c),
  296. handler: opts.handler(),
  297. streams: make(map[uint32]*stream),
  298. readFrameCh: make(chan readFrameResult),
  299. wantWriteFrameCh: make(chan FrameWriteRequest, 8),
  300. serveMsgCh: make(chan interface{}, 8),
  301. wroteFrameCh: make(chan frameWriteResult, 1), // buffered; one send in writeFrameAsync
  302. bodyReadCh: make(chan bodyReadMsg), // buffering doesn't matter either way
  303. doneServing: make(chan struct{}),
  304. clientMaxStreams: math.MaxUint32, // Section 6.5.2: "Initially, there is no limit to this value"
  305. advMaxStreams: s.maxConcurrentStreams(),
  306. initialStreamSendWindowSize: initialWindowSize,
  307. maxFrameSize: initialMaxFrameSize,
  308. headerTableSize: initialHeaderTableSize,
  309. serveG: newGoroutineLock(),
  310. pushEnabled: true,
  311. }
  312. s.state.registerConn(sc)
  313. defer s.state.unregisterConn(sc)
  314. // The net/http package sets the write deadline from the
  315. // http.Server.WriteTimeout during the TLS handshake, but then
  316. // passes the connection off to us with the deadline already set.
  317. // Write deadlines are set per stream in serverConn.newStream.
  318. // Disarm the net.Conn write deadline here.
  319. if sc.hs.WriteTimeout != 0 {
  320. sc.conn.SetWriteDeadline(time.Time{})
  321. }
  322. if s.NewWriteScheduler != nil {
  323. sc.writeSched = s.NewWriteScheduler()
  324. } else {
  325. sc.writeSched = NewRandomWriteScheduler()
  326. }
  327. // These start at the RFC-specified defaults. If there is a higher
  328. // configured value for inflow, that will be updated when we send a
  329. // WINDOW_UPDATE shortly after sending SETTINGS.
  330. sc.flow.add(initialWindowSize)
  331. sc.inflow.add(initialWindowSize)
  332. sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
  333. fr := NewFramer(sc.bw, c)
  334. fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil)
  335. fr.MaxHeaderListSize = sc.maxHeaderListSize()
  336. fr.SetMaxReadFrameSize(s.maxReadFrameSize())
  337. sc.framer = fr
  338. if tc, ok := c.(connectionStater); ok {
  339. sc.tlsState = new(tls.ConnectionState)
  340. *sc.tlsState = tc.ConnectionState()
  341. // 9.2 Use of TLS Features
  342. // An implementation of HTTP/2 over TLS MUST use TLS
  343. // 1.2 or higher with the restrictions on feature set
  344. // and cipher suite described in this section. Due to
  345. // implementation limitations, it might not be
  346. // possible to fail TLS negotiation. An endpoint MUST
  347. // immediately terminate an HTTP/2 connection that
  348. // does not meet the TLS requirements described in
  349. // this section with a connection error (Section
  350. // 5.4.1) of type INADEQUATE_SECURITY.
  351. if sc.tlsState.Version < tls.VersionTLS12 {
  352. sc.rejectConn(ErrCodeInadequateSecurity, "TLS version too low")
  353. return
  354. }
  355. if sc.tlsState.ServerName == "" {
  356. // Client must use SNI, but we don't enforce that anymore,
  357. // since it was causing problems when connecting to bare IP
  358. // addresses during development.
  359. //
  360. // TODO: optionally enforce? Or enforce at the time we receive
  361. // a new request, and verify the the ServerName matches the :authority?
  362. // But that precludes proxy situations, perhaps.
  363. //
  364. // So for now, do nothing here again.
  365. }
  366. if !s.PermitProhibitedCipherSuites && isBadCipher(sc.tlsState.CipherSuite) {
  367. // "Endpoints MAY choose to generate a connection error
  368. // (Section 5.4.1) of type INADEQUATE_SECURITY if one of
  369. // the prohibited cipher suites are negotiated."
  370. //
  371. // We choose that. In my opinion, the spec is weak
  372. // here. It also says both parties must support at least
  373. // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 so there's no
  374. // excuses here. If we really must, we could allow an
  375. // "AllowInsecureWeakCiphers" option on the server later.
  376. // Let's see how it plays out first.
  377. sc.rejectConn(ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite))
  378. return
  379. }
  380. }
  381. if hook := testHookGetServerConn; hook != nil {
  382. hook(sc)
  383. }
  384. sc.serve()
  385. }
  386. func (sc *serverConn) rejectConn(err ErrCode, debug string) {
  387. sc.vlogf("http2: server rejecting conn: %v, %s", err, debug)
  388. // ignoring errors. hanging up anyway.
  389. sc.framer.WriteGoAway(0, err, []byte(debug))
  390. sc.bw.Flush()
  391. sc.conn.Close()
  392. }
  393. type serverConn struct {
  394. // Immutable:
  395. srv *Server
  396. hs *http.Server
  397. conn net.Conn
  398. bw *bufferedWriter // writing to conn
  399. handler http.Handler
  400. baseCtx contextContext
  401. framer *Framer
  402. doneServing chan struct{} // closed when serverConn.serve ends
  403. readFrameCh chan readFrameResult // written by serverConn.readFrames
  404. wantWriteFrameCh chan FrameWriteRequest // from handlers -> serve
  405. wroteFrameCh chan frameWriteResult // from writeFrameAsync -> serve, tickles more frame writes
  406. bodyReadCh chan bodyReadMsg // from handlers -> serve
  407. serveMsgCh chan interface{} // misc messages & code to send to / run on the serve loop
  408. flow flow // conn-wide (not stream-specific) outbound flow control
  409. inflow flow // conn-wide inbound flow control
  410. tlsState *tls.ConnectionState // shared by all handlers, like net/http
  411. remoteAddrStr string
  412. writeSched WriteScheduler
  413. // Everything following is owned by the serve loop; use serveG.check():
  414. serveG goroutineLock // used to verify funcs are on serve()
  415. pushEnabled bool
  416. sawFirstSettings bool // got the initial SETTINGS frame after the preface
  417. needToSendSettingsAck bool
  418. unackedSettings int // how many SETTINGS have we sent without ACKs?
  419. clientMaxStreams uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)
  420. advMaxStreams uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client
  421. curClientStreams uint32 // number of open streams initiated by the client
  422. curPushedStreams uint32 // number of open streams initiated by server push
  423. maxClientStreamID uint32 // max ever seen from client (odd), or 0 if there have been no client requests
  424. maxPushPromiseID uint32 // ID of the last push promise (even), or 0 if there have been no pushes
  425. streams map[uint32]*stream
  426. initialStreamSendWindowSize int32
  427. maxFrameSize int32
  428. headerTableSize uint32
  429. peerMaxHeaderListSize uint32 // zero means unknown (default)
  430. canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case
  431. writingFrame bool // started writing a frame (on serve goroutine or separate)
  432. writingFrameAsync bool // started a frame on its own goroutine but haven't heard back on wroteFrameCh
  433. needsFrameFlush bool // last frame write wasn't a flush
  434. inGoAway bool // we've started to or sent GOAWAY
  435. inFrameScheduleLoop bool // whether we're in the scheduleFrameWrite loop
  436. needToSendGoAway bool // we need to schedule a GOAWAY frame write
  437. goAwayCode ErrCode
  438. shutdownTimer *time.Timer // nil until used
  439. idleTimer *time.Timer // nil if unused
  440. // Owned by the writeFrameAsync goroutine:
  441. headerWriteBuf bytes.Buffer
  442. hpackEncoder *hpack.Encoder
  443. // Used by startGracefulShutdown.
  444. shutdownOnce sync.Once
  445. }
  446. func (sc *serverConn) maxHeaderListSize() uint32 {
  447. n := sc.hs.MaxHeaderBytes
  448. if n <= 0 {
  449. n = http.DefaultMaxHeaderBytes
  450. }
  451. // http2's count is in a slightly different unit and includes 32 bytes per pair.
  452. // So, take the net/http.Server value and pad it up a bit, assuming 10 headers.
  453. const perFieldOverhead = 32 // per http2 spec
  454. const typicalHeaders = 10 // conservative
  455. return uint32(n + typicalHeaders*perFieldOverhead)
  456. }
  457. func (sc *serverConn) curOpenStreams() uint32 {
  458. sc.serveG.check()
  459. return sc.curClientStreams + sc.curPushedStreams
  460. }
  461. // stream represents a stream. This is the minimal metadata needed by
  462. // the serve goroutine. Most of the actual stream state is owned by
  463. // the http.Handler's goroutine in the responseWriter. Because the
  464. // responseWriter's responseWriterState is recycled at the end of a
  465. // handler, this struct intentionally has no pointer to the
  466. // *responseWriter{,State} itself, as the Handler ending nils out the
  467. // responseWriter's state field.
  468. type stream struct {
  469. // immutable:
  470. sc *serverConn
  471. id uint32
  472. body *pipe // non-nil if expecting DATA frames
  473. cw closeWaiter // closed wait stream transitions to closed state
  474. ctx contextContext
  475. cancelCtx func()
  476. // owned by serverConn's serve loop:
  477. bodyBytes int64 // body bytes seen so far
  478. declBodyBytes int64 // or -1 if undeclared
  479. flow flow // limits writing from Handler to client
  480. inflow flow // what the client is allowed to POST/etc to us
  481. parent *stream // or nil
  482. numTrailerValues int64
  483. weight uint8
  484. state streamState
  485. resetQueued bool // RST_STREAM queued for write; set by sc.resetStream
  486. gotTrailerHeader bool // HEADER frame for trailers was seen
  487. wroteHeaders bool // whether we wrote headers (not status 100)
  488. writeDeadline *time.Timer // nil if unused
  489. trailer http.Header // accumulated trailers
  490. reqTrailer http.Header // handler's Request.Trailer
  491. }
  492. func (sc *serverConn) Framer() *Framer { return sc.framer }
  493. func (sc *serverConn) CloseConn() error { return sc.conn.Close() }
  494. func (sc *serverConn) Flush() error { return sc.bw.Flush() }
  495. func (sc *serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) {
  496. return sc.hpackEncoder, &sc.headerWriteBuf
  497. }
  498. func (sc *serverConn) state(streamID uint32) (streamState, *stream) {
  499. sc.serveG.check()
  500. // http://tools.ietf.org/html/rfc7540#section-5.1
  501. if st, ok := sc.streams[streamID]; ok {
  502. return st.state, st
  503. }
  504. // "The first use of a new stream identifier implicitly closes all
  505. // streams in the "idle" state that might have been initiated by
  506. // that peer with a lower-valued stream identifier. For example, if
  507. // a client sends a HEADERS frame on stream 7 without ever sending a
  508. // frame on stream 5, then stream 5 transitions to the "closed"
  509. // state when the first frame for stream 7 is sent or received."
  510. if streamID%2 == 1 {
  511. if streamID <= sc.maxClientStreamID {
  512. return stateClosed, nil
  513. }
  514. } else {
  515. if streamID <= sc.maxPushPromiseID {
  516. return stateClosed, nil
  517. }
  518. }
  519. return stateIdle, nil
  520. }
  521. // setConnState calls the net/http ConnState hook for this connection, if configured.
  522. // Note that the net/http package does StateNew and StateClosed for us.
  523. // There is currently no plan for StateHijacked or hijacking HTTP/2 connections.
  524. func (sc *serverConn) setConnState(state http.ConnState) {
  525. if sc.hs.ConnState != nil {
  526. sc.hs.ConnState(sc.conn, state)
  527. }
  528. }
  529. func (sc *serverConn) vlogf(format string, args ...interface{}) {
  530. if VerboseLogs {
  531. sc.logf(format, args...)
  532. }
  533. }
  534. func (sc *serverConn) logf(format string, args ...interface{}) {
  535. if lg := sc.hs.ErrorLog; lg != nil {
  536. lg.Printf(format, args...)
  537. } else {
  538. log.Printf(format, args...)
  539. }
  540. }
  541. // errno returns v's underlying uintptr, else 0.
  542. //
  543. // TODO: remove this helper function once http2 can use build
  544. // tags. See comment in isClosedConnError.
  545. func errno(v error) uintptr {
  546. if rv := reflect.ValueOf(v); rv.Kind() == reflect.Uintptr {
  547. return uintptr(rv.Uint())
  548. }
  549. return 0
  550. }
  551. // isClosedConnError reports whether err is an error from use of a closed
  552. // network connection.
  553. func isClosedConnError(err error) bool {
  554. if err == nil {
  555. return false
  556. }
  557. // TODO: remove this string search and be more like the Windows
  558. // case below. That might involve modifying the standard library
  559. // to return better error types.
  560. str := err.Error()
  561. if strings.Contains(str, "use of closed network connection") {
  562. return true
  563. }
  564. // TODO(bradfitz): x/tools/cmd/bundle doesn't really support
  565. // build tags, so I can't make an http2_windows.go file with
  566. // Windows-specific stuff. Fix that and move this, once we
  567. // have a way to bundle this into std's net/http somehow.
  568. if runtime.GOOS == "windows" {
  569. if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
  570. if se, ok := oe.Err.(*os.SyscallError); ok && se.Syscall == "wsarecv" {
  571. const WSAECONNABORTED = 10053
  572. const WSAECONNRESET = 10054
  573. if n := errno(se.Err); n == WSAECONNRESET || n == WSAECONNABORTED {
  574. return true
  575. }
  576. }
  577. }
  578. }
  579. return false
  580. }
  581. func (sc *serverConn) condlogf(err error, format string, args ...interface{}) {
  582. if err == nil {
  583. return
  584. }
  585. if err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) {
  586. // Boring, expected errors.
  587. sc.vlogf(format, args...)
  588. } else {
  589. sc.logf(format, args...)
  590. }
  591. }
  592. func (sc *serverConn) canonicalHeader(v string) string {
  593. sc.serveG.check()
  594. cv, ok := commonCanonHeader[v]
  595. if ok {
  596. return cv
  597. }
  598. cv, ok = sc.canonHeader[v]
  599. if ok {
  600. return cv
  601. }
  602. if sc.canonHeader == nil {
  603. sc.canonHeader = make(map[string]string)
  604. }
  605. cv = http.CanonicalHeaderKey(v)
  606. sc.canonHeader[v] = cv
  607. return cv
  608. }
  609. type readFrameResult struct {
  610. f Frame // valid until readMore is called
  611. err error
  612. // readMore should be called once the consumer no longer needs or
  613. // retains f. After readMore, f is invalid and more frames can be
  614. // read.
  615. readMore func()
  616. }
  617. // readFrames is the loop that reads incoming frames.
  618. // It takes care to only read one frame at a time, blocking until the
  619. // consumer is done with the frame.
  620. // It's run on its own goroutine.
  621. func (sc *serverConn) readFrames() {
  622. gate := make(gate)
  623. gateDone := gate.Done
  624. for {
  625. f, err := sc.framer.ReadFrame()
  626. select {
  627. case sc.readFrameCh <- readFrameResult{f, err, gateDone}:
  628. case <-sc.doneServing:
  629. return
  630. }
  631. select {
  632. case <-gate:
  633. case <-sc.doneServing:
  634. return
  635. }
  636. if terminalReadFrameError(err) {
  637. return
  638. }
  639. }
  640. }
  641. // frameWriteResult is the message passed from writeFrameAsync to the serve goroutine.
  642. type frameWriteResult struct {
  643. wr FrameWriteRequest // what was written (or attempted)
  644. err error // result of the writeFrame call
  645. }
  646. // writeFrameAsync runs in its own goroutine and writes a single frame
  647. // and then reports when it's done.
  648. // At most one goroutine can be running writeFrameAsync at a time per
  649. // serverConn.
  650. func (sc *serverConn) writeFrameAsync(wr FrameWriteRequest) {
  651. err := wr.write.writeFrame(sc)
  652. sc.wroteFrameCh <- frameWriteResult{wr, err}
  653. }
  654. func (sc *serverConn) closeAllStreamsOnConnClose() {
  655. sc.serveG.check()
  656. for _, st := range sc.streams {
  657. sc.closeStream(st, errClientDisconnected)
  658. }
  659. }
  660. func (sc *serverConn) stopShutdownTimer() {
  661. sc.serveG.check()
  662. if t := sc.shutdownTimer; t != nil {
  663. t.Stop()
  664. }
  665. }
  666. func (sc *serverConn) notePanic() {
  667. // Note: this is for serverConn.serve panicking, not http.Handler code.
  668. if testHookOnPanicMu != nil {
  669. testHookOnPanicMu.Lock()
  670. defer testHookOnPanicMu.Unlock()
  671. }
  672. if testHookOnPanic != nil {
  673. if e := recover(); e != nil {
  674. if testHookOnPanic(sc, e) {
  675. panic(e)
  676. }
  677. }
  678. }
  679. }
  680. func (sc *serverConn) serve() {
  681. sc.serveG.check()
  682. defer sc.notePanic()
  683. defer sc.conn.Close()
  684. defer sc.closeAllStreamsOnConnClose()
  685. defer sc.stopShutdownTimer()
  686. defer close(sc.doneServing) // unblocks handlers trying to send
  687. if VerboseLogs {
  688. sc.vlogf("http2: server connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
  689. }
  690. sc.writeFrame(FrameWriteRequest{
  691. write: writeSettings{
  692. {SettingMaxFrameSize, sc.srv.maxReadFrameSize()},
  693. {SettingMaxConcurrentStreams, sc.advMaxStreams},
  694. {SettingMaxHeaderListSize, sc.maxHeaderListSize()},
  695. {SettingInitialWindowSize, uint32(sc.srv.initialStreamRecvWindowSize())},
  696. },
  697. })
  698. sc.unackedSettings++
  699. // Each connection starts with intialWindowSize inflow tokens.
  700. // If a higher value is configured, we add more tokens.
  701. if diff := sc.srv.initialConnRecvWindowSize() - initialWindowSize; diff > 0 {
  702. sc.sendWindowUpdate(nil, int(diff))
  703. }
  704. if err := sc.readPreface(); err != nil {
  705. sc.condlogf(err, "http2: server: error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
  706. return
  707. }
  708. // Now that we've got the preface, get us out of the
  709. // "StateNew" state. We can't go directly to idle, though.
  710. // Active means we read some data and anticipate a request. We'll
  711. // do another Active when we get a HEADERS frame.
  712. sc.setConnState(http.StateActive)
  713. sc.setConnState(http.StateIdle)
  714. if sc.srv.IdleTimeout != 0 {
  715. sc.idleTimer = time.AfterFunc(sc.srv.IdleTimeout, sc.onIdleTimer)
  716. defer sc.idleTimer.Stop()
  717. }
  718. go sc.readFrames() // closed by defer sc.conn.Close above
  719. settingsTimer := time.AfterFunc(firstSettingsTimeout, sc.onSettingsTimer)
  720. defer settingsTimer.Stop()
  721. loopNum := 0
  722. for {
  723. loopNum++
  724. select {
  725. case wr := <-sc.wantWriteFrameCh:
  726. if se, ok := wr.write.(StreamError); ok {
  727. sc.resetStream(se)
  728. break
  729. }
  730. sc.writeFrame(wr)
  731. case res := <-sc.wroteFrameCh:
  732. sc.wroteFrame(res)
  733. case res := <-sc.readFrameCh:
  734. if !sc.processFrameFromReader(res) {
  735. return
  736. }
  737. res.readMore()
  738. if settingsTimer != nil {
  739. settingsTimer.Stop()
  740. settingsTimer = nil
  741. }
  742. case m := <-sc.bodyReadCh:
  743. sc.noteBodyRead(m.st, m.n)
  744. case msg := <-sc.serveMsgCh:
  745. switch v := msg.(type) {
  746. case func(int):
  747. v(loopNum) // for testing
  748. case *serverMessage:
  749. switch v {
  750. case settingsTimerMsg:
  751. sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
  752. return
  753. case idleTimerMsg:
  754. sc.vlogf("connection is idle")
  755. sc.goAway(ErrCodeNo)
  756. case shutdownTimerMsg:
  757. sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
  758. return
  759. case gracefulShutdownMsg:
  760. sc.startGracefulShutdownInternal()
  761. default:
  762. panic("unknown timer")
  763. }
  764. case *startPushRequest:
  765. sc.startPush(v)
  766. default:
  767. panic(fmt.Sprintf("unexpected type %T", v))
  768. }
  769. }
  770. // Start the shutdown timer after sending a GOAWAY. When sending GOAWAY
  771. // with no error code (graceful shutdown), don't start the timer until
  772. // all open streams have been completed.
  773. sentGoAway := sc.inGoAway && !sc.needToSendGoAway && !sc.writingFrame
  774. gracefulShutdownComplete := sc.goAwayCode == ErrCodeNo && sc.curOpenStreams() == 0
  775. if sentGoAway && sc.shutdownTimer == nil && (sc.goAwayCode != ErrCodeNo || gracefulShutdownComplete) {
  776. sc.shutDownIn(goAwayTimeout)
  777. }
  778. }
  779. }
  780. func (sc *serverConn) awaitGracefulShutdown(sharedCh <-chan struct{}, privateCh chan struct{}) {
  781. select {
  782. case <-sc.doneServing:
  783. case <-sharedCh:
  784. close(privateCh)
  785. }
  786. }
  787. type serverMessage int
  788. // Message values sent to serveMsgCh.
  789. var (
  790. settingsTimerMsg = new(serverMessage)
  791. idleTimerMsg = new(serverMessage)
  792. shutdownTimerMsg = new(serverMessage)
  793. gracefulShutdownMsg = new(serverMessage)
  794. )
  795. func (sc *serverConn) onSettingsTimer() { sc.sendServeMsg(settingsTimerMsg) }
  796. func (sc *serverConn) onIdleTimer() { sc.sendServeMsg(idleTimerMsg) }
  797. func (sc *serverConn) onShutdownTimer() { sc.sendServeMsg(shutdownTimerMsg) }
  798. func (sc *serverConn) sendServeMsg(msg interface{}) {
  799. sc.serveG.checkNotOn() // NOT
  800. select {
  801. case sc.serveMsgCh <- msg:
  802. case <-sc.doneServing:
  803. }
  804. }
  805. // readPreface reads the ClientPreface greeting from the peer
  806. // or returns an error on timeout or an invalid greeting.
  807. func (sc *serverConn) readPreface() error {
  808. errc := make(chan error, 1)
  809. go func() {
  810. // Read the client preface
  811. buf := make([]byte, len(ClientPreface))
  812. if _, err := io.ReadFull(sc.conn, buf); err != nil {
  813. errc <- err
  814. } else if !bytes.Equal(buf, clientPreface) {
  815. errc <- fmt.Errorf("bogus greeting %q", buf)
  816. } else {
  817. errc <- nil
  818. }
  819. }()
  820. timer := time.NewTimer(prefaceTimeout) // TODO: configurable on *Server?
  821. defer timer.Stop()
  822. select {
  823. case <-timer.C:
  824. return errors.New("timeout waiting for client preface")
  825. case err := <-errc:
  826. if err == nil {
  827. if VerboseLogs {
  828. sc.vlogf("http2: server: client %v said hello", sc.conn.RemoteAddr())
  829. }
  830. }
  831. return err
  832. }
  833. }
  834. var errChanPool = sync.Pool{
  835. New: func() interface{} { return make(chan error, 1) },
  836. }
  837. var writeDataPool = sync.Pool{
  838. New: func() interface{} { return new(writeData) },
  839. }
  840. // writeDataFromHandler writes DATA response frames from a handler on
  841. // the given stream.
  842. func (sc *serverConn) writeDataFromHandler(stream *stream, data []byte, endStream bool) error {
  843. ch := errChanPool.Get().(chan error)
  844. writeArg := writeDataPool.Get().(*writeData)
  845. *writeArg = writeData{stream.id, data, endStream}
  846. err := sc.writeFrameFromHandler(FrameWriteRequest{
  847. write: writeArg,
  848. stream: stream,
  849. done: ch,
  850. })
  851. if err != nil {
  852. return err
  853. }
  854. var frameWriteDone bool // the frame write is done (successfully or not)
  855. select {
  856. case err = <-ch:
  857. frameWriteDone = true
  858. case <-sc.doneServing:
  859. return errClientDisconnected
  860. case <-stream.cw:
  861. // If both ch and stream.cw were ready (as might
  862. // happen on the final Write after an http.Handler
  863. // ends), prefer the write result. Otherwise this
  864. // might just be us successfully closing the stream.
  865. // The writeFrameAsync and serve goroutines guarantee
  866. // that the ch send will happen before the stream.cw
  867. // close.
  868. select {
  869. case err = <-ch:
  870. frameWriteDone = true
  871. default:
  872. return errStreamClosed
  873. }
  874. }
  875. errChanPool.Put(ch)
  876. if frameWriteDone {
  877. writeDataPool.Put(writeArg)
  878. }
  879. return err
  880. }
  881. // writeFrameFromHandler sends wr to sc.wantWriteFrameCh, but aborts
  882. // if the connection has gone away.
  883. //
  884. // This must not be run from the serve goroutine itself, else it might
  885. // deadlock writing to sc.wantWriteFrameCh (which is only mildly
  886. // buffered and is read by serve itself). If you're on the serve
  887. // goroutine, call writeFrame instead.
  888. func (sc *serverConn) writeFrameFromHandler(wr FrameWriteRequest) error {
  889. sc.serveG.checkNotOn() // NOT
  890. select {
  891. case sc.wantWriteFrameCh <- wr:
  892. return nil
  893. case <-sc.doneServing:
  894. // Serve loop is gone.
  895. // Client has closed their connection to the server.
  896. return errClientDisconnected
  897. }
  898. }
  899. // writeFrame schedules a frame to write and sends it if there's nothing
  900. // already being written.
  901. //
  902. // There is no pushback here (the serve goroutine never blocks). It's
  903. // the http.Handlers that block, waiting for their previous frames to
  904. // make it onto the wire
  905. //
  906. // If you're not on the serve goroutine, use writeFrameFromHandler instead.
  907. func (sc *serverConn) writeFrame(wr FrameWriteRequest) {
  908. sc.serveG.check()
  909. // If true, wr will not be written and wr.done will not be signaled.
  910. var ignoreWrite bool
  911. // We are not allowed to write frames on closed streams. RFC 7540 Section
  912. // 5.1.1 says: "An endpoint MUST NOT send frames other than PRIORITY on
  913. // a closed stream." Our server never sends PRIORITY, so that exception
  914. // does not apply.
  915. //
  916. // The serverConn might close an open stream while the stream's handler
  917. // is still running. For example, the server might close a stream when it
  918. // receives bad data from the client. If this happens, the handler might
  919. // attempt to write a frame after the stream has been closed (since the
  920. // handler hasn't yet been notified of the close). In this case, we simply
  921. // ignore the frame. The handler will notice that the stream is closed when
  922. // it waits for the frame to be written.
  923. //
  924. // As an exception to this rule, we allow sending RST_STREAM after close.
  925. // This allows us to immediately reject new streams without tracking any
  926. // state for those streams (except for the queued RST_STREAM frame). This
  927. // may result in duplicate RST_STREAMs in some cases, but the client should
  928. // ignore those.
  929. if wr.StreamID() != 0 {
  930. _, isReset := wr.write.(StreamError)
  931. if state, _ := sc.state(wr.StreamID()); state == stateClosed && !isReset {
  932. ignoreWrite = true
  933. }
  934. }
  935. // Don't send a 100-continue response if we've already sent headers.
  936. // See golang.org/issue/14030.
  937. switch wr.write.(type) {
  938. case *writeResHeaders:
  939. wr.stream.wroteHeaders = true
  940. case write100ContinueHeadersFrame:
  941. if wr.stream.wroteHeaders {
  942. // We do not need to notify wr.done because this frame is
  943. // never written with wr.done != nil.
  944. if wr.done != nil {
  945. panic("wr.done != nil for write100ContinueHeadersFrame")
  946. }
  947. ignoreWrite = true
  948. }
  949. }
  950. if !ignoreWrite {
  951. sc.writeSched.Push(wr)
  952. }
  953. sc.scheduleFrameWrite()
  954. }
  955. // startFrameWrite starts a goroutine to write wr (in a separate
  956. // goroutine since that might block on the network), and updates the
  957. // serve goroutine's state about the world, updated from info in wr.
  958. func (sc *serverConn) startFrameWrite(wr FrameWriteRequest) {
  959. sc.serveG.check()
  960. if sc.writingFrame {
  961. panic("internal error: can only be writing one frame at a time")
  962. }
  963. st := wr.stream
  964. if st != nil {
  965. switch st.state {
  966. case stateHalfClosedLocal:
  967. switch wr.write.(type) {
  968. case StreamError, handlerPanicRST, writeWindowUpdate:
  969. // RFC 7540 Section 5.1 allows sending RST_STREAM, PRIORITY, and WINDOW_UPDATE
  970. // in this state. (We never send PRIORITY from the server, so that is not checked.)
  971. default:
  972. panic(fmt.Sprintf("internal error: attempt to send frame on a half-closed-local stream: %v", wr))
  973. }
  974. case stateClosed:
  975. panic(fmt.Sprintf("internal error: attempt to send frame on a closed stream: %v", wr))
  976. }
  977. }
  978. if wpp, ok := wr.write.(*writePushPromise); ok {
  979. var err error
  980. wpp.promisedID, err = wpp.allocatePromisedID()
  981. if err != nil {
  982. sc.writingFrameAsync = false
  983. wr.replyToWriter(err)
  984. return
  985. }
  986. }
  987. sc.writingFrame = true
  988. sc.needsFrameFlush = true
  989. if wr.write.staysWithinBuffer(sc.bw.Available()) {
  990. sc.writingFrameAsync = false
  991. err := wr.write.writeFrame(sc)
  992. sc.wroteFrame(frameWriteResult{wr, err})
  993. } else {
  994. sc.writingFrameAsync = true
  995. go sc.writeFrameAsync(wr)
  996. }
  997. }
  998. // errHandlerPanicked is the error given to any callers blocked in a read from
  999. // Request.Body when the main goroutine panics. Since most handlers read in the
  1000. // the main ServeHTTP goroutine, this will show up rarely.
  1001. var errHandlerPanicked = errors.New("http2: handler panicked")
  1002. // wroteFrame is called on the serve goroutine with the result of
  1003. // whatever happened on writeFrameAsync.
  1004. func (sc *serverConn) wroteFrame(res frameWriteResult) {
  1005. sc.serveG.check()
  1006. if !sc.writingFrame {
  1007. panic("internal error: expected to be already writing a frame")
  1008. }
  1009. sc.writingFrame = false
  1010. sc.writingFrameAsync = false
  1011. wr := res.wr
  1012. if writeEndsStream(wr.write) {
  1013. st := wr.stream
  1014. if st == nil {
  1015. panic("internal error: expecting non-nil stream")
  1016. }
  1017. switch st.state {
  1018. case stateOpen:
  1019. // Here we would go to stateHalfClosedLocal in
  1020. // theory, but since our handler is done and
  1021. // the net/http package provides no mechanism
  1022. // for closing a ResponseWriter while still
  1023. // reading data (see possible TODO at top of
  1024. // this file), we go into closed state here
  1025. // anyway, after telling the peer we're
  1026. // hanging up on them. We'll transition to
  1027. // stateClosed after the RST_STREAM frame is
  1028. // written.
  1029. st.state = stateHalfClosedLocal
  1030. // Section 8.1: a server MAY request that the client abort
  1031. // transmission of a request without error by sending a
  1032. // RST_STREAM with an error code of NO_ERROR after sending
  1033. // a complete response.
  1034. sc.resetStream(streamError(st.id, ErrCodeNo))
  1035. case stateHalfClosedRemote:
  1036. sc.closeStream(st, errHandlerComplete)
  1037. }
  1038. } else {
  1039. switch v := wr.write.(type) {
  1040. case StreamError:
  1041. // st may be unknown if the RST_STREAM was generated to reject bad input.
  1042. if st, ok := sc.streams[v.StreamID]; ok {
  1043. sc.closeStream(st, v)
  1044. }
  1045. case handlerPanicRST:
  1046. sc.closeStream(wr.stream, errHandlerPanicked)
  1047. }
  1048. }
  1049. // Reply (if requested) to unblock the ServeHTTP goroutine.
  1050. wr.replyToWriter(res.err)
  1051. sc.scheduleFrameWrite()
  1052. }
  1053. // scheduleFrameWrite tickles the frame writing scheduler.
  1054. //
  1055. // If a frame is already being written, nothing happens. This will be called again
  1056. // when the frame is done being written.
  1057. //
  1058. // If a frame isn't being written we need to send one, the best frame
  1059. // to send is selected, preferring first things that aren't
  1060. // stream-specific (e.g. ACKing settings), and then finding the
  1061. // highest priority stream.
  1062. //
  1063. // If a frame isn't being written and there's nothing else to send, we
  1064. // flush the write buffer.
  1065. func (sc *serverConn) scheduleFrameWrite() {
  1066. sc.serveG.check()
  1067. if sc.writingFrame || sc.inFrameScheduleLoop {
  1068. return
  1069. }
  1070. sc.inFrameScheduleLoop = true
  1071. for !sc.writingFrameAsync {
  1072. if sc.needToSendGoAway {
  1073. sc.needToSendGoAway = false
  1074. sc.startFrameWrite(FrameWriteRequest{
  1075. write: &writeGoAway{
  1076. maxStreamID: sc.maxClientStreamID,
  1077. code: sc.goAwayCode,
  1078. },
  1079. })
  1080. continue
  1081. }
  1082. if sc.needToSendSettingsAck {
  1083. sc.needToSendSettingsAck = false
  1084. sc.startFrameWrite(FrameWriteRequest{write: writeSettingsAck{}})
  1085. continue
  1086. }
  1087. if !sc.inGoAway || sc.goAwayCode == ErrCodeNo {
  1088. if wr, ok := sc.writeSched.Pop(); ok {
  1089. sc.startFrameWrite(wr)
  1090. continue
  1091. }
  1092. }
  1093. if sc.needsFrameFlush {
  1094. sc.startFrameWrite(FrameWriteRequest{write: flushFrameWriter{}})
  1095. sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
  1096. continue
  1097. }
  1098. break
  1099. }
  1100. sc.inFrameScheduleLoop = false
  1101. }
  1102. // startGracefulShutdown gracefully shuts down a connection. This
  1103. // sends GOAWAY with ErrCodeNo to tell the client we're gracefully
  1104. // shutting down. The connection isn't closed until all current
  1105. // streams are done.
  1106. //
  1107. // startGracefulShutdown returns immediately; it does not wait until
  1108. // the connection has shut down.
  1109. func (sc *serverConn) startGracefulShutdown() {
  1110. sc.serveG.checkNotOn() // NOT
  1111. sc.shutdownOnce.Do(func() { sc.sendServeMsg(gracefulShutdownMsg) })
  1112. }
  1113. // After sending GOAWAY, the connection will close after goAwayTimeout.
  1114. // If we close the connection immediately after sending GOAWAY, there may
  1115. // be unsent data in our kernel receive buffer, which will cause the kernel
  1116. // to send a TCP RST on close() instead of a FIN. This RST will abort the
  1117. // connection immediately, whether or not the client had received the GOAWAY.
  1118. //
  1119. // Ideally we should delay for at least 1 RTT + epsilon so the client has
  1120. // a chance to read the GOAWAY and stop sending messages. Measuring RTT
  1121. // is hard, so we approximate with 1 second. See golang.org/issue/18701.
  1122. //
  1123. // This is a var so it can be shorter in tests, where all requests uses the
  1124. // loopback interface making the expected RTT very small.
  1125. //
  1126. // TODO: configurable?
  1127. var goAwayTimeout = 1 * time.Second
  1128. func (sc *serverConn) startGracefulShutdownInternal() {
  1129. sc.goAway(ErrCodeNo)
  1130. }
  1131. func (sc *serverConn) goAway(code ErrCode) {
  1132. sc.serveG.check()
  1133. if sc.inGoAway {
  1134. return
  1135. }
  1136. sc.inGoAway = true
  1137. sc.needToSendGoAway = true
  1138. sc.goAwayCode = code
  1139. sc.scheduleFrameWrite()
  1140. }
  1141. func (sc *serverConn) shutDownIn(d time.Duration) {
  1142. sc.serveG.check()
  1143. sc.shutdownTimer = time.AfterFunc(d, sc.onShutdownTimer)
  1144. }
  1145. func (sc *serverConn) resetStream(se StreamError) {
  1146. sc.serveG.check()
  1147. sc.writeFrame(FrameWriteRequest{write: se})
  1148. if st, ok := sc.streams[se.StreamID]; ok {
  1149. st.resetQueued = true
  1150. }
  1151. }
  1152. // processFrameFromReader processes the serve loop's read from readFrameCh from the
  1153. // frame-reading goroutine.
  1154. // processFrameFromReader returns whether the connection should be kept open.
  1155. func (sc *serverConn) processFrameFromReader(res readFrameResult) bool {
  1156. sc.serveG.check()
  1157. err := res.err
  1158. if err != nil {
  1159. if err == ErrFrameTooLarge {
  1160. sc.goAway(ErrCodeFrameSize)
  1161. return true // goAway will close the loop
  1162. }
  1163. clientGone := err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err)
  1164. if clientGone {
  1165. // TODO: could we also get into this state if
  1166. // the peer does a half close
  1167. // (e.g. CloseWrite) because they're done
  1168. // sending frames but they're still wanting
  1169. // our open replies? Investigate.
  1170. // TODO: add CloseWrite to crypto/tls.Conn first
  1171. // so we have a way to test this? I suppose
  1172. // just for testing we could have a non-TLS mode.
  1173. return false
  1174. }
  1175. } else {
  1176. f := res.f
  1177. if VerboseLogs {
  1178. sc.vlogf("http2: server read frame %v", summarizeFrame(f))
  1179. }
  1180. err = sc.processFrame(f)
  1181. if err == nil {
  1182. return true
  1183. }
  1184. }
  1185. switch ev := err.(type) {
  1186. case StreamError:
  1187. sc.resetStream(ev)
  1188. return true
  1189. case goAwayFlowError:
  1190. sc.goAway(ErrCodeFlowControl)
  1191. return true
  1192. case ConnectionError:
  1193. sc.logf("http2: server connection error from %v: %v", sc.conn.RemoteAddr(), ev)
  1194. sc.goAway(ErrCode(ev))
  1195. return true // goAway will handle shutdown
  1196. default:
  1197. if res.err != nil {
  1198. sc.vlogf("http2: server closing client connection; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
  1199. } else {
  1200. sc.logf("http2: server closing client connection: %v", err)
  1201. }
  1202. return false
  1203. }
  1204. }
  1205. func (sc *serverConn) processFrame(f Frame) error {
  1206. sc.serveG.check()
  1207. // First frame received must be SETTINGS.
  1208. if !sc.sawFirstSettings {
  1209. if _, ok := f.(*SettingsFrame); !ok {
  1210. return ConnectionError(ErrCodeProtocol)
  1211. }
  1212. sc.sawFirstSettings = true
  1213. }
  1214. switch f := f.(type) {
  1215. case *SettingsFrame:
  1216. return sc.processSettings(f)
  1217. case *MetaHeadersFrame:
  1218. return sc.processHeaders(f)
  1219. case *WindowUpdateFrame:
  1220. return sc.processWindowUpdate(f)
  1221. case *PingFrame:
  1222. return sc.processPing(f)
  1223. case *DataFrame:
  1224. return sc.processData(f)
  1225. case *RSTStreamFrame:
  1226. return sc.processResetStream(f)
  1227. case *PriorityFrame:
  1228. return sc.processPriority(f)
  1229. case *GoAwayFrame:
  1230. return sc.processGoAway(f)
  1231. case *PushPromiseFrame:
  1232. // A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE
  1233. // frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1234. return ConnectionError(ErrCodeProtocol)
  1235. default:
  1236. sc.vlogf("http2: server ignoring frame: %v", f.Header())
  1237. return nil
  1238. }
  1239. }
  1240. func (sc *serverConn) processPing(f *PingFrame) error {
  1241. sc.serveG.check()
  1242. if f.IsAck() {
  1243. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  1244. // containing this flag."
  1245. return nil
  1246. }
  1247. if f.StreamID != 0 {
  1248. // "PING frames are not associated with any individual
  1249. // stream. If a PING frame is received with a stream
  1250. // identifier field value other than 0x0, the recipient MUST
  1251. // respond with a connection error (Section 5.4.1) of type
  1252. // PROTOCOL_ERROR."
  1253. return ConnectionError(ErrCodeProtocol)
  1254. }
  1255. if sc.inGoAway && sc.goAwayCode != ErrCodeNo {
  1256. return nil
  1257. }
  1258. sc.writeFrame(FrameWriteRequest{write: writePingAck{f}})
  1259. return nil
  1260. }
  1261. func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  1262. sc.serveG.check()
  1263. switch {
  1264. case f.StreamID != 0: // stream-level flow control
  1265. state, st := sc.state(f.StreamID)
  1266. if state == stateIdle {
  1267. // Section 5.1: "Receiving any frame other than HEADERS
  1268. // or PRIORITY on a stream in this state MUST be
  1269. // treated as a connection error (Section 5.4.1) of
  1270. // type PROTOCOL_ERROR."
  1271. return ConnectionError(ErrCodeProtocol)
  1272. }
  1273. if st == nil {
  1274. // "WINDOW_UPDATE can be sent by a peer that has sent a
  1275. // frame bearing the END_STREAM flag. This means that a
  1276. // receiver could receive a WINDOW_UPDATE frame on a "half
  1277. // closed (remote)" or "closed" stream. A receiver MUST
  1278. // NOT treat this as an error, see Section 5.1."
  1279. return nil
  1280. }
  1281. if !st.flow.add(int32(f.Increment)) {
  1282. return streamError(f.StreamID, ErrCodeFlowControl)
  1283. }
  1284. default: // connection-level flow control
  1285. if !sc.flow.add(int32(f.Increment)) {
  1286. return goAwayFlowError{}
  1287. }
  1288. }
  1289. sc.scheduleFrameWrite()
  1290. return nil
  1291. }
  1292. func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
  1293. sc.serveG.check()
  1294. state, st := sc.state(f.StreamID)
  1295. if state == stateIdle {
  1296. // 6.4 "RST_STREAM frames MUST NOT be sent for a
  1297. // stream in the "idle" state. If a RST_STREAM frame
  1298. // identifying an idle stream is received, the
  1299. // recipient MUST treat this as a connection error
  1300. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1301. return ConnectionError(ErrCodeProtocol)
  1302. }
  1303. if st != nil {
  1304. st.cancelCtx()
  1305. sc.closeStream(st, streamError(f.StreamID, f.ErrCode))
  1306. }
  1307. return nil
  1308. }
  1309. func (sc *serverConn) closeStream(st *stream, err error) {
  1310. sc.serveG.check()
  1311. if st.state == stateIdle || st.state == stateClosed {
  1312. panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
  1313. }
  1314. st.state = stateClosed
  1315. if st.writeDeadline != nil {
  1316. st.writeDeadline.Stop()
  1317. }
  1318. if st.isPushed() {
  1319. sc.curPushedStreams--
  1320. } else {
  1321. sc.curClientStreams--
  1322. }
  1323. delete(sc.streams, st.id)
  1324. if len(sc.streams) == 0 {
  1325. sc.setConnState(http.StateIdle)
  1326. if sc.srv.IdleTimeout != 0 {
  1327. sc.idleTimer.Reset(sc.srv.IdleTimeout)
  1328. }
  1329. if h1ServerKeepAlivesDisabled(sc.hs) {
  1330. sc.startGracefulShutdownInternal()
  1331. }
  1332. }
  1333. if p := st.body; p != nil {
  1334. // Return any buffered unread bytes worth of conn-level flow control.
  1335. // See golang.org/issue/16481
  1336. sc.sendWindowUpdate(nil, p.Len())
  1337. p.CloseWithError(err)
  1338. }
  1339. st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc
  1340. sc.writeSched.CloseStream(st.id)
  1341. }
  1342. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  1343. sc.serveG.check()
  1344. if f.IsAck() {
  1345. sc.unackedSettings--
  1346. if sc.unackedSettings < 0 {
  1347. // Why is the peer ACKing settings we never sent?
  1348. // The spec doesn't mention this case, but
  1349. // hang up on them anyway.
  1350. return ConnectionError(ErrCodeProtocol)
  1351. }
  1352. return nil
  1353. }
  1354. if err := f.ForeachSetting(sc.processSetting); err != nil {
  1355. return err
  1356. }
  1357. sc.needToSendSettingsAck = true
  1358. sc.scheduleFrameWrite()
  1359. return nil
  1360. }
  1361. func (sc *serverConn) processSetting(s Setting) error {
  1362. sc.serveG.check()
  1363. if err := s.Valid(); err != nil {
  1364. return err
  1365. }
  1366. if VerboseLogs {
  1367. sc.vlogf("http2: server processing setting %v", s)
  1368. }
  1369. switch s.ID {
  1370. case SettingHeaderTableSize:
  1371. sc.headerTableSize = s.Val
  1372. sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
  1373. case SettingEnablePush:
  1374. sc.pushEnabled = s.Val != 0
  1375. case SettingMaxConcurrentStreams:
  1376. sc.clientMaxStreams = s.Val
  1377. case SettingInitialWindowSize:
  1378. return sc.processSettingInitialWindowSize(s.Val)
  1379. case SettingMaxFrameSize:
  1380. sc.maxFrameSize = int32(s.Val) // the maximum valid s.Val is < 2^31
  1381. case SettingMaxHeaderListSize:
  1382. sc.peerMaxHeaderListSize = s.Val
  1383. default:
  1384. // Unknown setting: "An endpoint that receives a SETTINGS
  1385. // frame with any unknown or unsupported identifier MUST
  1386. // ignore that setting."
  1387. if VerboseLogs {
  1388. sc.vlogf("http2: server ignoring unknown setting %v", s)
  1389. }
  1390. }
  1391. return nil
  1392. }
  1393. func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  1394. sc.serveG.check()
  1395. // Note: val already validated to be within range by
  1396. // processSetting's Valid call.
  1397. // "A SETTINGS frame can alter the initial flow control window
  1398. // size for all current streams. When the value of
  1399. // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  1400. // adjust the size of all stream flow control windows that it
  1401. // maintains by the difference between the new value and the
  1402. // old value."
  1403. old := sc.initialStreamSendWindowSize
  1404. sc.initialStreamSendWindowSize = int32(val)
  1405. growth := int32(val) - old // may be negative
  1406. for _, st := range sc.streams {
  1407. if !st.flow.add(growth) {
  1408. // 6.9.2 Initial Flow Control Window Size
  1409. // "An endpoint MUST treat a change to
  1410. // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  1411. // control window to exceed the maximum size as a
  1412. // connection error (Section 5.4.1) of type
  1413. // FLOW_CONTROL_ERROR."
  1414. return ConnectionError(ErrCodeFlowControl)
  1415. }
  1416. }
  1417. return nil
  1418. }
  1419. func (sc *serverConn) processData(f *DataFrame) error {
  1420. sc.serveG.check()
  1421. if sc.inGoAway && sc.goAwayCode != ErrCodeNo {
  1422. return nil
  1423. }
  1424. data := f.Data()
  1425. // "If a DATA frame is received whose stream is not in "open"
  1426. // or "half closed (local)" state, the recipient MUST respond
  1427. // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  1428. id := f.Header().StreamID
  1429. state, st := sc.state(id)
  1430. if id == 0 || state == stateIdle {
  1431. // Section 5.1: "Receiving any frame other than HEADERS
  1432. // or PRIORITY on a stream in this state MUST be
  1433. // treated as a connection error (Section 5.4.1) of
  1434. // type PROTOCOL_ERROR."
  1435. return ConnectionError(ErrCodeProtocol)
  1436. }
  1437. if st == nil || state != stateOpen || st.gotTrailerHeader || st.resetQueued {
  1438. // This includes sending a RST_STREAM if the stream is
  1439. // in stateHalfClosedLocal (which currently means that
  1440. // the http.Handler returned, so it's done reading &
  1441. // done writing). Try to stop the client from sending
  1442. // more DATA.
  1443. // But still enforce their connection-level flow control,
  1444. // and return any flow control bytes since we're not going
  1445. // to consume them.
  1446. if sc.inflow.available() < int32(f.Length) {
  1447. return streamError(id, ErrCodeFlowControl)
  1448. }
  1449. // Deduct the flow control from inflow, since we're
  1450. // going to immediately add it back in
  1451. // sendWindowUpdate, which also schedules sending the
  1452. // frames.
  1453. sc.inflow.take(int32(f.Length))
  1454. sc.sendWindowUpdate(nil, int(f.Length)) // conn-level
  1455. if st != nil && st.resetQueued {
  1456. // Already have a stream error in flight. Don't send another.
  1457. return nil
  1458. }
  1459. return streamError(id, ErrCodeStreamClosed)
  1460. }
  1461. if st.body == nil {
  1462. panic("internal error: should have a body in this state")
  1463. }
  1464. // Sender sending more than they'd declared?
  1465. if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  1466. st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  1467. return streamError(id, ErrCodeStreamClosed)
  1468. }
  1469. if f.Length > 0 {
  1470. // Check whether the client has flow control quota.
  1471. if st.inflow.available() < int32(f.Length) {
  1472. return streamError(id, ErrCodeFlowControl)
  1473. }
  1474. st.inflow.take(int32(f.Length))
  1475. if len(data) > 0 {
  1476. wrote, err := st.body.Write(data)
  1477. if err != nil {
  1478. return streamError(id, ErrCodeStreamClosed)
  1479. }
  1480. if wrote != len(data) {
  1481. panic("internal error: bad Writer")
  1482. }
  1483. st.bodyBytes += int64(len(data))
  1484. }
  1485. // Return any padded flow control now, since we won't
  1486. // refund it later on body reads.
  1487. if pad := int32(f.Length) - int32(len(data)); pad > 0 {
  1488. sc.sendWindowUpdate32(nil, pad)
  1489. sc.sendWindowUpdate32(st, pad)
  1490. }
  1491. }
  1492. if f.StreamEnded() {
  1493. st.endStream()
  1494. }
  1495. return nil
  1496. }
  1497. func (sc *serverConn) processGoAway(f *GoAwayFrame) error {
  1498. sc.serveG.check()
  1499. if f.ErrCode != ErrCodeNo {
  1500. sc.logf("http2: received GOAWAY %+v, starting graceful shutdown", f)
  1501. } else {
  1502. sc.vlogf("http2: received GOAWAY %+v, starting graceful shutdown", f)
  1503. }
  1504. sc.startGracefulShutdownInternal()
  1505. // http://tools.ietf.org/html/rfc7540#section-6.8
  1506. // We should not create any new streams, which means we should disable push.
  1507. sc.pushEnabled = false
  1508. return nil
  1509. }
  1510. // isPushed reports whether the stream is server-initiated.
  1511. func (st *stream) isPushed() bool {
  1512. return st.id%2 == 0
  1513. }
  1514. // endStream closes a Request.Body's pipe. It is called when a DATA
  1515. // frame says a request body is over (or after trailers).
  1516. func (st *stream) endStream() {
  1517. sc := st.sc
  1518. sc.serveG.check()
  1519. if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  1520. st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
  1521. st.declBodyBytes, st.bodyBytes))
  1522. } else {
  1523. st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest)
  1524. st.body.CloseWithError(io.EOF)
  1525. }
  1526. st.state = stateHalfClosedRemote
  1527. }
  1528. // copyTrailersToHandlerRequest is run in the Handler's goroutine in
  1529. // its Request.Body.Read just before it gets io.EOF.
  1530. func (st *stream) copyTrailersToHandlerRequest() {
  1531. for k, vv := range st.trailer {
  1532. if _, ok := st.reqTrailer[k]; ok {
  1533. // Only copy it over it was pre-declared.
  1534. st.reqTrailer[k] = vv
  1535. }
  1536. }
  1537. }
  1538. // onWriteTimeout is run on its own goroutine (from time.AfterFunc)
  1539. // when the stream's WriteTimeout has fired.
  1540. func (st *stream) onWriteTimeout() {
  1541. st.sc.writeFrameFromHandler(FrameWriteRequest{write: streamError(st.id, ErrCodeInternal)})
  1542. }
  1543. func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error {
  1544. sc.serveG.check()
  1545. id := f.StreamID
  1546. if sc.inGoAway {
  1547. // Ignore.
  1548. return nil
  1549. }
  1550. // http://tools.ietf.org/html/rfc7540#section-5.1.1
  1551. // Streams initiated by a client MUST use odd-numbered stream
  1552. // identifiers. [...] An endpoint that receives an unexpected
  1553. // stream identifier MUST respond with a connection error
  1554. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1555. if id%2 != 1 {
  1556. return ConnectionError(ErrCodeProtocol)
  1557. }
  1558. // A HEADERS frame can be used to create a new stream or
  1559. // send a trailer for an open one. If we already have a stream
  1560. // open, let it process its own HEADERS frame (trailers at this
  1561. // point, if it's valid).
  1562. if st := sc.streams[f.StreamID]; st != nil {
  1563. if st.resetQueued {
  1564. // We're sending RST_STREAM to close the stream, so don't bother
  1565. // processing this frame.
  1566. return nil
  1567. }
  1568. return st.processTrailerHeaders(f)
  1569. }
  1570. // [...] The identifier of a newly established stream MUST be
  1571. // numerically greater than all streams that the initiating
  1572. // endpoint has opened or reserved. [...] An endpoint that
  1573. // receives an unexpected stream identifier MUST respond with
  1574. // a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1575. if id <= sc.maxClientStreamID {
  1576. return ConnectionError(ErrCodeProtocol)
  1577. }
  1578. sc.maxClientStreamID = id
  1579. if sc.idleTimer != nil {
  1580. sc.idleTimer.Stop()
  1581. }
  1582. // http://tools.ietf.org/html/rfc7540#section-5.1.2
  1583. // [...] Endpoints MUST NOT exceed the limit set by their peer. An
  1584. // endpoint that receives a HEADERS frame that causes their
  1585. // advertised concurrent stream limit to be exceeded MUST treat
  1586. // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR
  1587. // or REFUSED_STREAM.
  1588. if sc.curClientStreams+1 > sc.advMaxStreams {
  1589. if sc.unackedSettings == 0 {
  1590. // They should know better.
  1591. return streamError(id, ErrCodeProtocol)
  1592. }
  1593. // Assume it's a network race, where they just haven't
  1594. // received our last SETTINGS update. But actually
  1595. // this can't happen yet, because we don't yet provide
  1596. // a way for users to adjust server parameters at
  1597. // runtime.
  1598. return streamError(id, ErrCodeRefusedStream)
  1599. }
  1600. initialState := stateOpen
  1601. if f.StreamEnded() {
  1602. initialState = stateHalfClosedRemote
  1603. }
  1604. st := sc.newStream(id, 0, initialState)
  1605. if f.HasPriority() {
  1606. if err := checkPriority(f.StreamID, f.Priority); err != nil {
  1607. return err
  1608. }
  1609. sc.writeSched.AdjustStream(st.id, f.Priority)
  1610. }
  1611. rw, req, err := sc.newWriterAndRequest(st, f)
  1612. if err != nil {
  1613. return err
  1614. }
  1615. st.reqTrailer = req.Trailer
  1616. if st.reqTrailer != nil {
  1617. st.trailer = make(http.Header)
  1618. }
  1619. st.body = req.Body.(*requestBody).pipe // may be nil
  1620. st.declBodyBytes = req.ContentLength
  1621. handler := sc.handler.ServeHTTP
  1622. if f.Truncated {
  1623. // Their header list was too long. Send a 431 error.
  1624. handler = handleHeaderListTooLong
  1625. } else if err := checkValidHTTP2RequestHeaders(req.Header); err != nil {
  1626. handler = new400Handler(err)
  1627. }
  1628. // The net/http package sets the read deadline from the
  1629. // http.Server.ReadTimeout during the TLS handshake, but then
  1630. // passes the connection off to us with the deadline already
  1631. // set. Disarm it here after the request headers are read,
  1632. // similar to how the http1 server works. Here it's
  1633. // technically more like the http1 Server's ReadHeaderTimeout
  1634. // (in Go 1.8), though. That's a more sane option anyway.
  1635. if sc.hs.ReadTimeout != 0 {
  1636. sc.conn.SetReadDeadline(time.Time{})
  1637. }
  1638. go sc.runHandler(rw, req, handler)
  1639. return nil
  1640. }
  1641. func (st *stream) processTrailerHeaders(f *MetaHeadersFrame) error {
  1642. sc := st.sc
  1643. sc.serveG.check()
  1644. if st.gotTrailerHeader {
  1645. return ConnectionError(ErrCodeProtocol)
  1646. }
  1647. st.gotTrailerHeader = true
  1648. if !f.StreamEnded() {
  1649. return streamError(st.id, ErrCodeProtocol)
  1650. }
  1651. if len(f.PseudoFields()) > 0 {
  1652. return streamError(st.id, ErrCodeProtocol)
  1653. }
  1654. if st.trailer != nil {
  1655. for _, hf := range f.RegularFields() {
  1656. key := sc.canonicalHeader(hf.Name)
  1657. if !ValidTrailerHeader(key) {
  1658. // TODO: send more details to the peer somehow. But http2 has
  1659. // no way to send debug data at a stream level. Discuss with
  1660. // HTTP folk.
  1661. return streamError(st.id, ErrCodeProtocol)
  1662. }
  1663. st.trailer[key] = append(st.trailer[key], hf.Value)
  1664. }
  1665. }
  1666. st.endStream()
  1667. return nil
  1668. }
  1669. func checkPriority(streamID uint32, p PriorityParam) error {
  1670. if streamID == p.StreamDep {
  1671. // Section 5.3.1: "A stream cannot depend on itself. An endpoint MUST treat
  1672. // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR."
  1673. // Section 5.3.3 says that a stream can depend on one of its dependencies,
  1674. // so it's only self-dependencies that are forbidden.
  1675. return streamError(streamID, ErrCodeProtocol)
  1676. }
  1677. return nil
  1678. }
  1679. func (sc *serverConn) processPriority(f *PriorityFrame) error {
  1680. if sc.inGoAway {
  1681. return nil
  1682. }
  1683. if err := checkPriority(f.StreamID, f.PriorityParam); err != nil {
  1684. return err
  1685. }
  1686. sc.writeSched.AdjustStream(f.StreamID, f.PriorityParam)
  1687. return nil
  1688. }
  1689. func (sc *serverConn) newStream(id, pusherID uint32, state streamState) *stream {
  1690. sc.serveG.check()
  1691. if id == 0 {
  1692. panic("internal error: cannot create stream with id 0")
  1693. }
  1694. ctx, cancelCtx := contextWithCancel(sc.baseCtx)
  1695. st := &stream{
  1696. sc: sc,
  1697. id: id,
  1698. state: state,
  1699. ctx: ctx,
  1700. cancelCtx: cancelCtx,
  1701. }
  1702. st.cw.Init()
  1703. st.flow.conn = &sc.flow // link to conn-level counter
  1704. st.flow.add(sc.initialStreamSendWindowSize)
  1705. st.inflow.conn = &sc.inflow // link to conn-level counter
  1706. st.inflow.add(sc.srv.initialStreamRecvWindowSize())
  1707. if sc.hs.WriteTimeout != 0 {
  1708. st.writeDeadline = time.AfterFunc(sc.hs.WriteTimeout, st.onWriteTimeout)
  1709. }
  1710. sc.streams[id] = st
  1711. sc.writeSched.OpenStream(st.id, OpenStreamOptions{PusherID: pusherID})
  1712. if st.isPushed() {
  1713. sc.curPushedStreams++
  1714. } else {
  1715. sc.curClientStreams++
  1716. }
  1717. if sc.curOpenStreams() == 1 {
  1718. sc.setConnState(http.StateActive)
  1719. }
  1720. return st
  1721. }
  1722. func (sc *serverConn) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*responseWriter, *http.Request, error) {
  1723. sc.serveG.check()
  1724. rp := requestParam{
  1725. method: f.PseudoValue("method"),
  1726. scheme: f.PseudoValue("scheme"),
  1727. authority: f.PseudoValue("authority"),
  1728. path: f.PseudoValue("path"),
  1729. }
  1730. isConnect := rp.method == "CONNECT"
  1731. if isConnect {
  1732. if rp.path != "" || rp.scheme != "" || rp.authority == "" {
  1733. return nil, nil, streamError(f.StreamID, ErrCodeProtocol)
  1734. }
  1735. } else if rp.method == "" || rp.path == "" || (rp.scheme != "https" && rp.scheme != "http") {
  1736. // See 8.1.2.6 Malformed Requests and Responses:
  1737. //
  1738. // Malformed requests or responses that are detected
  1739. // MUST be treated as a stream error (Section 5.4.2)
  1740. // of type PROTOCOL_ERROR."
  1741. //
  1742. // 8.1.2.3 Request Pseudo-Header Fields
  1743. // "All HTTP/2 requests MUST include exactly one valid
  1744. // value for the :method, :scheme, and :path
  1745. // pseudo-header fields"
  1746. return nil, nil, streamError(f.StreamID, ErrCodeProtocol)
  1747. }
  1748. bodyOpen := !f.StreamEnded()
  1749. if rp.method == "HEAD" && bodyOpen {
  1750. // HEAD requests can't have bodies
  1751. return nil, nil, streamError(f.StreamID, ErrCodeProtocol)
  1752. }
  1753. rp.header = make(http.Header)
  1754. for _, hf := range f.RegularFields() {
  1755. rp.header.Add(sc.canonicalHeader(hf.Name), hf.Value)
  1756. }
  1757. if rp.authority == "" {
  1758. rp.authority = rp.header.Get("Host")
  1759. }
  1760. rw, req, err := sc.newWriterAndRequestNoBody(st, rp)
  1761. if err != nil {
  1762. return nil, nil, err
  1763. }
  1764. if bodyOpen {
  1765. if vv, ok := rp.header["Content-Length"]; ok {
  1766. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  1767. } else {
  1768. req.ContentLength = -1
  1769. }
  1770. req.Body.(*requestBody).pipe = &pipe{
  1771. b: &dataBuffer{expected: req.ContentLength},
  1772. }
  1773. }
  1774. return rw, req, nil
  1775. }
  1776. type requestParam struct {
  1777. method string
  1778. scheme, authority, path string
  1779. header http.Header
  1780. }
  1781. func (sc *serverConn) newWriterAndRequestNoBody(st *stream, rp requestParam) (*responseWriter, *http.Request, error) {
  1782. sc.serveG.check()
  1783. var tlsState *tls.ConnectionState // nil if not scheme https
  1784. if rp.scheme == "https" {
  1785. tlsState = sc.tlsState
  1786. }
  1787. needsContinue := rp.header.Get("Expect") == "100-continue"
  1788. if needsContinue {
  1789. rp.header.Del("Expect")
  1790. }
  1791. // Merge Cookie headers into one "; "-delimited value.
  1792. if cookies := rp.header["Cookie"]; len(cookies) > 1 {
  1793. rp.header.Set("Cookie", strings.Join(cookies, "; "))
  1794. }
  1795. // Setup Trailers
  1796. var trailer http.Header
  1797. for _, v := range rp.header["Trailer"] {
  1798. for _, key := range strings.Split(v, ",") {
  1799. key = http.CanonicalHeaderKey(strings.TrimSpace(key))
  1800. switch key {
  1801. case "Transfer-Encoding", "Trailer", "Content-Length":
  1802. // Bogus. (copy of http1 rules)
  1803. // Ignore.
  1804. default:
  1805. if trailer == nil {
  1806. trailer = make(http.Header)
  1807. }
  1808. trailer[key] = nil
  1809. }
  1810. }
  1811. }
  1812. delete(rp.header, "Trailer")
  1813. var url_ *url.URL
  1814. var requestURI string
  1815. if rp.method == "CONNECT" {
  1816. url_ = &url.URL{Host: rp.authority}
  1817. requestURI = rp.authority // mimic HTTP/1 server behavior
  1818. } else {
  1819. var err error
  1820. url_, err = url.ParseRequestURI(rp.path)
  1821. if err != nil {
  1822. return nil, nil, streamError(st.id, ErrCodeProtocol)
  1823. }
  1824. requestURI = rp.path
  1825. }
  1826. body := &requestBody{
  1827. conn: sc,
  1828. stream: st,
  1829. needsContinue: needsContinue,
  1830. }
  1831. req := &http.Request{
  1832. Method: rp.method,
  1833. URL: url_,
  1834. RemoteAddr: sc.remoteAddrStr,
  1835. Header: rp.header,
  1836. RequestURI: requestURI,
  1837. Proto: "HTTP/2.0",
  1838. ProtoMajor: 2,
  1839. ProtoMinor: 0,
  1840. TLS: tlsState,
  1841. Host: rp.authority,
  1842. Body: body,
  1843. Trailer: trailer,
  1844. }
  1845. req = requestWithContext(req, st.ctx)
  1846. rws := responseWriterStatePool.Get().(*responseWriterState)
  1847. bwSave := rws.bw
  1848. *rws = responseWriterState{} // zero all the fields
  1849. rws.conn = sc
  1850. rws.bw = bwSave
  1851. rws.bw.Reset(chunkWriter{rws})
  1852. rws.stream = st
  1853. rws.req = req
  1854. rws.body = body
  1855. rw := &responseWriter{rws: rws}
  1856. return rw, req, nil
  1857. }
  1858. // Run on its own goroutine.
  1859. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) {
  1860. didPanic := true
  1861. defer func() {
  1862. rw.rws.stream.cancelCtx()
  1863. if didPanic {
  1864. e := recover()
  1865. sc.writeFrameFromHandler(FrameWriteRequest{
  1866. write: handlerPanicRST{rw.rws.stream.id},
  1867. stream: rw.rws.stream,
  1868. })
  1869. // Same as net/http:
  1870. if shouldLogPanic(e) {
  1871. const size = 64 << 10
  1872. buf := make([]byte, size)
  1873. buf = buf[:runtime.Stack(buf, false)]
  1874. sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf)
  1875. }
  1876. return
  1877. }
  1878. rw.handlerDone()
  1879. }()
  1880. handler(rw, req)
  1881. didPanic = false
  1882. }
  1883. func handleHeaderListTooLong(w http.ResponseWriter, r *http.Request) {
  1884. // 10.5.1 Limits on Header Block Size:
  1885. // .. "A server that receives a larger header block than it is
  1886. // willing to handle can send an HTTP 431 (Request Header Fields Too
  1887. // Large) status code"
  1888. const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+
  1889. w.WriteHeader(statusRequestHeaderFieldsTooLarge)
  1890. io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
  1891. }
  1892. // called from handler goroutines.
  1893. // h may be nil.
  1894. func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error {
  1895. sc.serveG.checkNotOn() // NOT on
  1896. var errc chan error
  1897. if headerData.h != nil {
  1898. // If there's a header map (which we don't own), so we have to block on
  1899. // waiting for this frame to be written, so an http.Flush mid-handler
  1900. // writes out the correct value of keys, before a handler later potentially
  1901. // mutates it.
  1902. errc = errChanPool.Get().(chan error)
  1903. }
  1904. if err := sc.writeFrameFromHandler(FrameWriteRequest{
  1905. write: headerData,
  1906. stream: st,
  1907. done: errc,
  1908. }); err != nil {
  1909. return err
  1910. }
  1911. if errc != nil {
  1912. select {
  1913. case err := <-errc:
  1914. errChanPool.Put(errc)
  1915. return err
  1916. case <-sc.doneServing:
  1917. return errClientDisconnected
  1918. case <-st.cw:
  1919. return errStreamClosed
  1920. }
  1921. }
  1922. return nil
  1923. }
  1924. // called from handler goroutines.
  1925. func (sc *serverConn) write100ContinueHeaders(st *stream) {
  1926. sc.writeFrameFromHandler(FrameWriteRequest{
  1927. write: write100ContinueHeadersFrame{st.id},
  1928. stream: st,
  1929. })
  1930. }
  1931. // A bodyReadMsg tells the server loop that the http.Handler read n
  1932. // bytes of the DATA from the client on the given stream.
  1933. type bodyReadMsg struct {
  1934. st *stream
  1935. n int
  1936. }
  1937. // called from handler goroutines.
  1938. // Notes that the handler for the given stream ID read n bytes of its body
  1939. // and schedules flow control tokens to be sent.
  1940. func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int, err error) {
  1941. sc.serveG.checkNotOn() // NOT on
  1942. if n > 0 {
  1943. select {
  1944. case sc.bodyReadCh <- bodyReadMsg{st, n}:
  1945. case <-sc.doneServing:
  1946. }
  1947. }
  1948. }
  1949. func (sc *serverConn) noteBodyRead(st *stream, n int) {
  1950. sc.serveG.check()
  1951. sc.sendWindowUpdate(nil, n) // conn-level
  1952. if st.state != stateHalfClosedRemote && st.state != stateClosed {
  1953. // Don't send this WINDOW_UPDATE if the stream is closed
  1954. // remotely.
  1955. sc.sendWindowUpdate(st, n)
  1956. }
  1957. }
  1958. // st may be nil for conn-level
  1959. func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
  1960. sc.serveG.check()
  1961. // "The legal range for the increment to the flow control
  1962. // window is 1 to 2^31-1 (2,147,483,647) octets."
  1963. // A Go Read call on 64-bit machines could in theory read
  1964. // a larger Read than this. Very unlikely, but we handle it here
  1965. // rather than elsewhere for now.
  1966. const maxUint31 = 1<<31 - 1
  1967. for n >= maxUint31 {
  1968. sc.sendWindowUpdate32(st, maxUint31)
  1969. n -= maxUint31
  1970. }
  1971. sc.sendWindowUpdate32(st, int32(n))
  1972. }
  1973. // st may be nil for conn-level
  1974. func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) {
  1975. sc.serveG.check()
  1976. if n == 0 {
  1977. return
  1978. }
  1979. if n < 0 {
  1980. panic("negative update")
  1981. }
  1982. var streamID uint32
  1983. if st != nil {
  1984. streamID = st.id
  1985. }
  1986. sc.writeFrame(FrameWriteRequest{
  1987. write: writeWindowUpdate{streamID: streamID, n: uint32(n)},
  1988. stream: st,
  1989. })
  1990. var ok bool
  1991. if st == nil {
  1992. ok = sc.inflow.add(n)
  1993. } else {
  1994. ok = st.inflow.add(n)
  1995. }
  1996. if !ok {
  1997. panic("internal error; sent too many window updates without decrements?")
  1998. }
  1999. }
  2000. // requestBody is the Handler's Request.Body type.
  2001. // Read and Close may be called concurrently.
  2002. type requestBody struct {
  2003. stream *stream
  2004. conn *serverConn
  2005. closed bool // for use by Close only
  2006. sawEOF bool // for use by Read only
  2007. pipe *pipe // non-nil if we have a HTTP entity message body
  2008. needsContinue bool // need to send a 100-continue
  2009. }
  2010. func (b *requestBody) Close() error {
  2011. if b.pipe != nil && !b.closed {
  2012. b.pipe.BreakWithError(errClosedBody)
  2013. }
  2014. b.closed = true
  2015. return nil
  2016. }
  2017. func (b *requestBody) Read(p []byte) (n int, err error) {
  2018. if b.needsContinue {
  2019. b.needsContinue = false
  2020. b.conn.write100ContinueHeaders(b.stream)
  2021. }
  2022. if b.pipe == nil || b.sawEOF {
  2023. return 0, io.EOF
  2024. }
  2025. n, err = b.pipe.Read(p)
  2026. if err == io.EOF {
  2027. b.sawEOF = true
  2028. }
  2029. if b.conn == nil && inTests {
  2030. return
  2031. }
  2032. b.conn.noteBodyReadFromHandler(b.stream, n, err)
  2033. return
  2034. }
  2035. // responseWriter is the http.ResponseWriter implementation. It's
  2036. // intentionally small (1 pointer wide) to minimize garbage. The
  2037. // responseWriterState pointer inside is zeroed at the end of a
  2038. // request (in handlerDone) and calls on the responseWriter thereafter
  2039. // simply crash (caller's mistake), but the much larger responseWriterState
  2040. // and buffers are reused between multiple requests.
  2041. type responseWriter struct {
  2042. rws *responseWriterState
  2043. }
  2044. // Optional http.ResponseWriter interfaces implemented.
  2045. var (
  2046. _ http.CloseNotifier = (*responseWriter)(nil)
  2047. _ http.Flusher = (*responseWriter)(nil)
  2048. _ stringWriter = (*responseWriter)(nil)
  2049. )
  2050. type responseWriterState struct {
  2051. // immutable within a request:
  2052. stream *stream
  2053. req *http.Request
  2054. body *requestBody // to close at end of request, if DATA frames didn't
  2055. conn *serverConn
  2056. // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
  2057. bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
  2058. // mutated by http.Handler goroutine:
  2059. handlerHeader http.Header // nil until called
  2060. snapHeader http.Header // snapshot of handlerHeader at WriteHeader time
  2061. trailers []string // set in writeChunk
  2062. status int // status code passed to WriteHeader
  2063. wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
  2064. sentHeader bool // have we sent the header frame?
  2065. handlerDone bool // handler has finished
  2066. dirty bool // a Write failed; don't reuse this responseWriterState
  2067. sentContentLen int64 // non-zero if handler set a Content-Length header
  2068. wroteBytes int64
  2069. closeNotifierMu sync.Mutex // guards closeNotifierCh
  2070. closeNotifierCh chan bool // nil until first used
  2071. }
  2072. type chunkWriter struct{ rws *responseWriterState }
  2073. func (cw chunkWriter) Write(p []byte) (n int, err error) { return cw.rws.writeChunk(p) }
  2074. func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) != 0 }
  2075. // declareTrailer is called for each Trailer header when the
  2076. // response header is written. It notes that a header will need to be
  2077. // written in the trailers at the end of the response.
  2078. func (rws *responseWriterState) declareTrailer(k string) {
  2079. k = http.CanonicalHeaderKey(k)
  2080. if !ValidTrailerHeader(k) {
  2081. // Forbidden by RFC 2616 14.40.
  2082. rws.conn.logf("ignoring invalid trailer %q", k)
  2083. return
  2084. }
  2085. if !strSliceContains(rws.trailers, k) {
  2086. rws.trailers = append(rws.trailers, k)
  2087. }
  2088. }
  2089. // writeChunk writes chunks from the bufio.Writer. But because
  2090. // bufio.Writer may bypass its chunking, sometimes p may be
  2091. // arbitrarily large.
  2092. //
  2093. // writeChunk is also responsible (on the first chunk) for sending the
  2094. // HEADER response.
  2095. func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
  2096. if !rws.wroteHeader {
  2097. rws.writeHeader(200)
  2098. }
  2099. isHeadResp := rws.req.Method == "HEAD"
  2100. if !rws.sentHeader {
  2101. rws.sentHeader = true
  2102. var ctype, clen string
  2103. if clen = rws.snapHeader.Get("Content-Length"); clen != "" {
  2104. rws.snapHeader.Del("Content-Length")
  2105. clen64, err := strconv.ParseInt(clen, 10, 64)
  2106. if err == nil && clen64 >= 0 {
  2107. rws.sentContentLen = clen64
  2108. } else {
  2109. clen = ""
  2110. }
  2111. }
  2112. if clen == "" && rws.handlerDone && bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) {
  2113. clen = strconv.Itoa(len(p))
  2114. }
  2115. _, hasContentType := rws.snapHeader["Content-Type"]
  2116. if !hasContentType && bodyAllowedForStatus(rws.status) {
  2117. ctype = http.DetectContentType(p)
  2118. }
  2119. var date string
  2120. if _, ok := rws.snapHeader["Date"]; !ok {
  2121. // TODO(bradfitz): be faster here, like net/http? measure.
  2122. date = time.Now().UTC().Format(http.TimeFormat)
  2123. }
  2124. for _, v := range rws.snapHeader["Trailer"] {
  2125. foreachHeaderElement(v, rws.declareTrailer)
  2126. }
  2127. endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp
  2128. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  2129. streamID: rws.stream.id,
  2130. httpResCode: rws.status,
  2131. h: rws.snapHeader,
  2132. endStream: endStream,
  2133. contentType: ctype,
  2134. contentLength: clen,
  2135. date: date,
  2136. })
  2137. if err != nil {
  2138. rws.dirty = true
  2139. return 0, err
  2140. }
  2141. if endStream {
  2142. return 0, nil
  2143. }
  2144. }
  2145. if isHeadResp {
  2146. return len(p), nil
  2147. }
  2148. if len(p) == 0 && !rws.handlerDone {
  2149. return 0, nil
  2150. }
  2151. if rws.handlerDone {
  2152. rws.promoteUndeclaredTrailers()
  2153. }
  2154. endStream := rws.handlerDone && !rws.hasTrailers()
  2155. if len(p) > 0 || endStream {
  2156. // only send a 0 byte DATA frame if we're ending the stream.
  2157. if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil {
  2158. rws.dirty = true
  2159. return 0, err
  2160. }
  2161. }
  2162. if rws.handlerDone && rws.hasTrailers() {
  2163. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  2164. streamID: rws.stream.id,
  2165. h: rws.handlerHeader,
  2166. trailers: rws.trailers,
  2167. endStream: true,
  2168. })
  2169. if err != nil {
  2170. rws.dirty = true
  2171. }
  2172. return len(p), err
  2173. }
  2174. return len(p), nil
  2175. }
  2176. // TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
  2177. // that, if present, signals that the map entry is actually for
  2178. // the response trailers, and not the response headers. The prefix
  2179. // is stripped after the ServeHTTP call finishes and the values are
  2180. // sent in the trailers.
  2181. //
  2182. // This mechanism is intended only for trailers that are not known
  2183. // prior to the headers being written. If the set of trailers is fixed
  2184. // or known before the header is written, the normal Go trailers mechanism
  2185. // is preferred:
  2186. // https://golang.org/pkg/net/http/#ResponseWriter
  2187. // https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
  2188. const TrailerPrefix = "Trailer:"
  2189. // promoteUndeclaredTrailers permits http.Handlers to set trailers
  2190. // after the header has already been flushed. Because the Go
  2191. // ResponseWriter interface has no way to set Trailers (only the
  2192. // Header), and because we didn't want to expand the ResponseWriter
  2193. // interface, and because nobody used trailers, and because RFC 2616
  2194. // says you SHOULD (but not must) predeclare any trailers in the
  2195. // header, the official ResponseWriter rules said trailers in Go must
  2196. // be predeclared, and then we reuse the same ResponseWriter.Header()
  2197. // map to mean both Headers and Trailers. When it's time to write the
  2198. // Trailers, we pick out the fields of Headers that were declared as
  2199. // trailers. That worked for a while, until we found the first major
  2200. // user of Trailers in the wild: gRPC (using them only over http2),
  2201. // and gRPC libraries permit setting trailers mid-stream without
  2202. // predeclarnig them. So: change of plans. We still permit the old
  2203. // way, but we also permit this hack: if a Header() key begins with
  2204. // "Trailer:", the suffix of that key is a Trailer. Because ':' is an
  2205. // invalid token byte anyway, there is no ambiguity. (And it's already
  2206. // filtered out) It's mildly hacky, but not terrible.
  2207. //
  2208. // This method runs after the Handler is done and promotes any Header
  2209. // fields to be trailers.
  2210. func (rws *responseWriterState) promoteUndeclaredTrailers() {
  2211. for k, vv := range rws.handlerHeader {
  2212. if !strings.HasPrefix(k, TrailerPrefix) {
  2213. continue
  2214. }
  2215. trailerKey := strings.TrimPrefix(k, TrailerPrefix)
  2216. rws.declareTrailer(trailerKey)
  2217. rws.handlerHeader[http.CanonicalHeaderKey(trailerKey)] = vv
  2218. }
  2219. if len(rws.trailers) > 1 {
  2220. sorter := sorterPool.Get().(*sorter)
  2221. sorter.SortStrings(rws.trailers)
  2222. sorterPool.Put(sorter)
  2223. }
  2224. }
  2225. func (w *responseWriter) Flush() {
  2226. rws := w.rws
  2227. if rws == nil {
  2228. panic("Header called after Handler finished")
  2229. }
  2230. if rws.bw.Buffered() > 0 {
  2231. if err := rws.bw.Flush(); err != nil {
  2232. // Ignore the error. The frame writer already knows.
  2233. return
  2234. }
  2235. } else {
  2236. // The bufio.Writer won't call chunkWriter.Write
  2237. // (writeChunk with zero bytes, so we have to do it
  2238. // ourselves to force the HTTP response header and/or
  2239. // final DATA frame (with END_STREAM) to be sent.
  2240. rws.writeChunk(nil)
  2241. }
  2242. }
  2243. func (w *responseWriter) CloseNotify() <-chan bool {
  2244. rws := w.rws
  2245. if rws == nil {
  2246. panic("CloseNotify called after Handler finished")
  2247. }
  2248. rws.closeNotifierMu.Lock()
  2249. ch := rws.closeNotifierCh
  2250. if ch == nil {
  2251. ch = make(chan bool, 1)
  2252. rws.closeNotifierCh = ch
  2253. cw := rws.stream.cw
  2254. go func() {
  2255. cw.Wait() // wait for close
  2256. ch <- true
  2257. }()
  2258. }
  2259. rws.closeNotifierMu.Unlock()
  2260. return ch
  2261. }
  2262. func (w *responseWriter) Header() http.Header {
  2263. rws := w.rws
  2264. if rws == nil {
  2265. panic("Header called after Handler finished")
  2266. }
  2267. if rws.handlerHeader == nil {
  2268. rws.handlerHeader = make(http.Header)
  2269. }
  2270. return rws.handlerHeader
  2271. }
  2272. func (w *responseWriter) WriteHeader(code int) {
  2273. rws := w.rws
  2274. if rws == nil {
  2275. panic("WriteHeader called after Handler finished")
  2276. }
  2277. rws.writeHeader(code)
  2278. }
  2279. func (rws *responseWriterState) writeHeader(code int) {
  2280. if !rws.wroteHeader {
  2281. rws.wroteHeader = true
  2282. rws.status = code
  2283. if len(rws.handlerHeader) > 0 {
  2284. rws.snapHeader = cloneHeader(rws.handlerHeader)
  2285. }
  2286. }
  2287. }
  2288. func cloneHeader(h http.Header) http.Header {
  2289. h2 := make(http.Header, len(h))
  2290. for k, vv := range h {
  2291. vv2 := make([]string, len(vv))
  2292. copy(vv2, vv)
  2293. h2[k] = vv2
  2294. }
  2295. return h2
  2296. }
  2297. // The Life Of A Write is like this:
  2298. //
  2299. // * Handler calls w.Write or w.WriteString ->
  2300. // * -> rws.bw (*bufio.Writer) ->
  2301. // * (Handler might call Flush)
  2302. // * -> chunkWriter{rws}
  2303. // * -> responseWriterState.writeChunk(p []byte)
  2304. // * -> responseWriterState.writeChunk (most of the magic; see comment there)
  2305. func (w *responseWriter) Write(p []byte) (n int, err error) {
  2306. return w.write(len(p), p, "")
  2307. }
  2308. func (w *responseWriter) WriteString(s string) (n int, err error) {
  2309. return w.write(len(s), nil, s)
  2310. }
  2311. // either dataB or dataS is non-zero.
  2312. func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  2313. rws := w.rws
  2314. if rws == nil {
  2315. panic("Write called after Handler finished")
  2316. }
  2317. if !rws.wroteHeader {
  2318. w.WriteHeader(200)
  2319. }
  2320. if !bodyAllowedForStatus(rws.status) {
  2321. return 0, http.ErrBodyNotAllowed
  2322. }
  2323. rws.wroteBytes += int64(len(dataB)) + int64(len(dataS)) // only one can be set
  2324. if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen {
  2325. // TODO: send a RST_STREAM
  2326. return 0, errors.New("http2: handler wrote more than declared Content-Length")
  2327. }
  2328. if dataB != nil {
  2329. return rws.bw.Write(dataB)
  2330. } else {
  2331. return rws.bw.WriteString(dataS)
  2332. }
  2333. }
  2334. func (w *responseWriter) handlerDone() {
  2335. rws := w.rws
  2336. dirty := rws.dirty
  2337. rws.handlerDone = true
  2338. w.Flush()
  2339. w.rws = nil
  2340. if !dirty {
  2341. // Only recycle the pool if all prior Write calls to
  2342. // the serverConn goroutine completed successfully. If
  2343. // they returned earlier due to resets from the peer
  2344. // there might still be write goroutines outstanding
  2345. // from the serverConn referencing the rws memory. See
  2346. // issue 20704.
  2347. responseWriterStatePool.Put(rws)
  2348. }
  2349. }
  2350. // Push errors.
  2351. var (
  2352. ErrRecursivePush = errors.New("http2: recursive push not allowed")
  2353. ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS")
  2354. )
  2355. // pushOptions is the internal version of http.PushOptions, which we
  2356. // cannot include here because it's only defined in Go 1.8 and later.
  2357. type pushOptions struct {
  2358. Method string
  2359. Header http.Header
  2360. }
  2361. func (w *responseWriter) push(target string, opts pushOptions) error {
  2362. st := w.rws.stream
  2363. sc := st.sc
  2364. sc.serveG.checkNotOn()
  2365. // No recursive pushes: "PUSH_PROMISE frames MUST only be sent on a peer-initiated stream."
  2366. // http://tools.ietf.org/html/rfc7540#section-6.6
  2367. if st.isPushed() {
  2368. return ErrRecursivePush
  2369. }
  2370. // Default options.
  2371. if opts.Method == "" {
  2372. opts.Method = "GET"
  2373. }
  2374. if opts.Header == nil {
  2375. opts.Header = http.Header{}
  2376. }
  2377. wantScheme := "http"
  2378. if w.rws.req.TLS != nil {
  2379. wantScheme = "https"
  2380. }
  2381. // Validate the request.
  2382. u, err := url.Parse(target)
  2383. if err != nil {
  2384. return err
  2385. }
  2386. if u.Scheme == "" {
  2387. if !strings.HasPrefix(target, "/") {
  2388. return fmt.Errorf("target must be an absolute URL or an absolute path: %q", target)
  2389. }
  2390. u.Scheme = wantScheme
  2391. u.Host = w.rws.req.Host
  2392. } else {
  2393. if u.Scheme != wantScheme {
  2394. return fmt.Errorf("cannot push URL with scheme %q from request with scheme %q", u.Scheme, wantScheme)
  2395. }
  2396. if u.Host == "" {
  2397. return errors.New("URL must have a host")
  2398. }
  2399. }
  2400. for k := range opts.Header {
  2401. if strings.HasPrefix(k, ":") {
  2402. return fmt.Errorf("promised request headers cannot include pseudo header %q", k)
  2403. }
  2404. // These headers are meaningful only if the request has a body,
  2405. // but PUSH_PROMISE requests cannot have a body.
  2406. // http://tools.ietf.org/html/rfc7540#section-8.2
  2407. // Also disallow Host, since the promised URL must be absolute.
  2408. switch strings.ToLower(k) {
  2409. case "content-length", "content-encoding", "trailer", "te", "expect", "host":
  2410. return fmt.Errorf("promised request headers cannot include %q", k)
  2411. }
  2412. }
  2413. if err := checkValidHTTP2RequestHeaders(opts.Header); err != nil {
  2414. return err
  2415. }
  2416. // The RFC effectively limits promised requests to GET and HEAD:
  2417. // "Promised requests MUST be cacheable [GET, HEAD, or POST], and MUST be safe [GET or HEAD]"
  2418. // http://tools.ietf.org/html/rfc7540#section-8.2
  2419. if opts.Method != "GET" && opts.Method != "HEAD" {
  2420. return fmt.Errorf("method %q must be GET or HEAD", opts.Method)
  2421. }
  2422. msg := &startPushRequest{
  2423. parent: st,
  2424. method: opts.Method,
  2425. url: u,
  2426. header: cloneHeader(opts.Header),
  2427. done: errChanPool.Get().(chan error),
  2428. }
  2429. select {
  2430. case <-sc.doneServing:
  2431. return errClientDisconnected
  2432. case <-st.cw:
  2433. return errStreamClosed
  2434. case sc.serveMsgCh <- msg:
  2435. }
  2436. select {
  2437. case <-sc.doneServing:
  2438. return errClientDisconnected
  2439. case <-st.cw:
  2440. return errStreamClosed
  2441. case err := <-msg.done:
  2442. errChanPool.Put(msg.done)
  2443. return err
  2444. }
  2445. }
  2446. type startPushRequest struct {
  2447. parent *stream
  2448. method string
  2449. url *url.URL
  2450. header http.Header
  2451. done chan error
  2452. }
  2453. func (sc *serverConn) startPush(msg *startPushRequest) {
  2454. sc.serveG.check()
  2455. // http://tools.ietf.org/html/rfc7540#section-6.6.
  2456. // PUSH_PROMISE frames MUST only be sent on a peer-initiated stream that
  2457. // is in either the "open" or "half-closed (remote)" state.
  2458. if msg.parent.state != stateOpen && msg.parent.state != stateHalfClosedRemote {
  2459. // responseWriter.Push checks that the stream is peer-initiaed.
  2460. msg.done <- errStreamClosed
  2461. return
  2462. }
  2463. // http://tools.ietf.org/html/rfc7540#section-6.6.
  2464. if !sc.pushEnabled {
  2465. msg.done <- http.ErrNotSupported
  2466. return
  2467. }
  2468. // PUSH_PROMISE frames must be sent in increasing order by stream ID, so
  2469. // we allocate an ID for the promised stream lazily, when the PUSH_PROMISE
  2470. // is written. Once the ID is allocated, we start the request handler.
  2471. allocatePromisedID := func() (uint32, error) {
  2472. sc.serveG.check()
  2473. // Check this again, just in case. Technically, we might have received
  2474. // an updated SETTINGS by the time we got around to writing this frame.
  2475. if !sc.pushEnabled {
  2476. return 0, http.ErrNotSupported
  2477. }
  2478. // http://tools.ietf.org/html/rfc7540#section-6.5.2.
  2479. if sc.curPushedStreams+1 > sc.clientMaxStreams {
  2480. return 0, ErrPushLimitReached
  2481. }
  2482. // http://tools.ietf.org/html/rfc7540#section-5.1.1.
  2483. // Streams initiated by the server MUST use even-numbered identifiers.
  2484. // A server that is unable to establish a new stream identifier can send a GOAWAY
  2485. // frame so that the client is forced to open a new connection for new streams.
  2486. if sc.maxPushPromiseID+2 >= 1<<31 {
  2487. sc.startGracefulShutdownInternal()
  2488. return 0, ErrPushLimitReached
  2489. }
  2490. sc.maxPushPromiseID += 2
  2491. promisedID := sc.maxPushPromiseID
  2492. // http://tools.ietf.org/html/rfc7540#section-8.2.
  2493. // Strictly speaking, the new stream should start in "reserved (local)", then
  2494. // transition to "half closed (remote)" after sending the initial HEADERS, but
  2495. // we start in "half closed (remote)" for simplicity.
  2496. // See further comments at the definition of stateHalfClosedRemote.
  2497. promised := sc.newStream(promisedID, msg.parent.id, stateHalfClosedRemote)
  2498. rw, req, err := sc.newWriterAndRequestNoBody(promised, requestParam{
  2499. method: msg.method,
  2500. scheme: msg.url.Scheme,
  2501. authority: msg.url.Host,
  2502. path: msg.url.RequestURI(),
  2503. header: cloneHeader(msg.header), // clone since handler runs concurrently with writing the PUSH_PROMISE
  2504. })
  2505. if err != nil {
  2506. // Should not happen, since we've already validated msg.url.
  2507. panic(fmt.Sprintf("newWriterAndRequestNoBody(%+v): %v", msg.url, err))
  2508. }
  2509. go sc.runHandler(rw, req, sc.handler.ServeHTTP)
  2510. return promisedID, nil
  2511. }
  2512. sc.writeFrame(FrameWriteRequest{
  2513. write: &writePushPromise{
  2514. streamID: msg.parent.id,
  2515. method: msg.method,
  2516. url: msg.url,
  2517. h: msg.header,
  2518. allocatePromisedID: allocatePromisedID,
  2519. },
  2520. stream: msg.parent,
  2521. done: msg.done,
  2522. })
  2523. }
  2524. // foreachHeaderElement splits v according to the "#rule" construction
  2525. // in RFC 2616 section 2.1 and calls fn for each non-empty element.
  2526. func foreachHeaderElement(v string, fn func(string)) {
  2527. v = textproto.TrimString(v)
  2528. if v == "" {
  2529. return
  2530. }
  2531. if !strings.Contains(v, ",") {
  2532. fn(v)
  2533. return
  2534. }
  2535. for _, f := range strings.Split(v, ",") {
  2536. if f = textproto.TrimString(f); f != "" {
  2537. fn(f)
  2538. }
  2539. }
  2540. }
  2541. // From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2
  2542. var connHeaders = []string{
  2543. "Connection",
  2544. "Keep-Alive",
  2545. "Proxy-Connection",
  2546. "Transfer-Encoding",
  2547. "Upgrade",
  2548. }
  2549. // checkValidHTTP2RequestHeaders checks whether h is a valid HTTP/2 request,
  2550. // per RFC 7540 Section 8.1.2.2.
  2551. // The returned error is reported to users.
  2552. func checkValidHTTP2RequestHeaders(h http.Header) error {
  2553. for _, k := range connHeaders {
  2554. if _, ok := h[k]; ok {
  2555. return fmt.Errorf("request header %q is not valid in HTTP/2", k)
  2556. }
  2557. }
  2558. te := h["Te"]
  2559. if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) {
  2560. return errors.New(`request header "TE" may only be "trailers" in HTTP/2`)
  2561. }
  2562. return nil
  2563. }
  2564. func new400Handler(err error) http.HandlerFunc {
  2565. return func(w http.ResponseWriter, r *http.Request) {
  2566. http.Error(w, err.Error(), http.StatusBadRequest)
  2567. }
  2568. }
  2569. // ValidTrailerHeader reports whether name is a valid header field name to appear
  2570. // in trailers.
  2571. // See: http://tools.ietf.org/html/rfc7230#section-4.1.2
  2572. func ValidTrailerHeader(name string) bool {
  2573. name = http.CanonicalHeaderKey(name)
  2574. if strings.HasPrefix(name, "If-") || badTrailer[name] {
  2575. return false
  2576. }
  2577. return true
  2578. }
  2579. var badTrailer = map[string]bool{
  2580. "Authorization": true,
  2581. "Cache-Control": true,
  2582. "Connection": true,
  2583. "Content-Encoding": true,
  2584. "Content-Length": true,
  2585. "Content-Range": true,
  2586. "Content-Type": true,
  2587. "Expect": true,
  2588. "Host": true,
  2589. "Keep-Alive": true,
  2590. "Max-Forwards": true,
  2591. "Pragma": true,
  2592. "Proxy-Authenticate": true,
  2593. "Proxy-Authorization": true,
  2594. "Proxy-Connection": true,
  2595. "Range": true,
  2596. "Realm": true,
  2597. "Te": true,
  2598. "Trailer": true,
  2599. "Transfer-Encoding": true,
  2600. "Www-Authenticate": true,
  2601. }
  2602. // h1ServerKeepAlivesDisabled reports whether hs has its keep-alives
  2603. // disabled. See comments on h1ServerShutdownChan above for why
  2604. // the code is written this way.
  2605. func h1ServerKeepAlivesDisabled(hs *http.Server) bool {
  2606. var x interface{} = hs
  2607. type I interface {
  2608. doKeepAlives() bool
  2609. }
  2610. if hs, ok := x.(I); ok {
  2611. return !hs.doKeepAlives()
  2612. }
  2613. return false
  2614. }