server.go 89 KB

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