server.go 87 KB

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