server.go 82 KB

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