server.go 85 KB

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