server.go 86 KB

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