server.go 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743
  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. switch wr.write.(type) {
  854. case StreamError, handlerPanicRST, writeWindowUpdate:
  855. // RFC 7540 Section 5.1 allows sending RST_STREAM, PRIORITY, and WINDOW_UPDATE
  856. // in this state. (We never send PRIORITY from the server, so that is not checked.)
  857. default:
  858. panic(fmt.Sprintf("internal error: attempt to send frame on a half-closed-local stream: %v", wr))
  859. }
  860. case stateClosed:
  861. panic(fmt.Sprintf("internal error: attempt to send frame on a closed stream: %v", wr))
  862. }
  863. }
  864. if wpp, ok := wr.write.(*writePushPromise); ok {
  865. var err error
  866. wpp.promisedID, err = wpp.allocatePromisedID()
  867. if err != nil {
  868. sc.writingFrameAsync = false
  869. wr.replyToWriter(err)
  870. return
  871. }
  872. }
  873. sc.writingFrame = true
  874. sc.needsFrameFlush = true
  875. if wr.write.staysWithinBuffer(sc.bw.Available()) {
  876. sc.writingFrameAsync = false
  877. err := wr.write.writeFrame(sc)
  878. sc.wroteFrame(frameWriteResult{wr, err})
  879. } else {
  880. sc.writingFrameAsync = true
  881. go sc.writeFrameAsync(wr)
  882. }
  883. }
  884. // errHandlerPanicked is the error given to any callers blocked in a read from
  885. // Request.Body when the main goroutine panics. Since most handlers read in the
  886. // the main ServeHTTP goroutine, this will show up rarely.
  887. var errHandlerPanicked = errors.New("http2: handler panicked")
  888. // wroteFrame is called on the serve goroutine with the result of
  889. // whatever happened on writeFrameAsync.
  890. func (sc *serverConn) wroteFrame(res frameWriteResult) {
  891. sc.serveG.check()
  892. if !sc.writingFrame {
  893. panic("internal error: expected to be already writing a frame")
  894. }
  895. sc.writingFrame = false
  896. sc.writingFrameAsync = false
  897. wr := res.wr
  898. if writeEndsStream(wr.write) {
  899. st := wr.stream
  900. if st == nil {
  901. panic("internal error: expecting non-nil stream")
  902. }
  903. switch st.state {
  904. case stateOpen:
  905. // Here we would go to stateHalfClosedLocal in
  906. // theory, but since our handler is done and
  907. // the net/http package provides no mechanism
  908. // for closing a ResponseWriter while still
  909. // reading data (see possible TODO at top of
  910. // this file), we go into closed state here
  911. // anyway, after telling the peer we're
  912. // hanging up on them. We'll transition to
  913. // stateClosed after the RST_STREAM frame is
  914. // written.
  915. st.state = stateHalfClosedLocal
  916. sc.resetStream(streamError(st.id, ErrCodeCancel))
  917. case stateHalfClosedRemote:
  918. sc.closeStream(st, errHandlerComplete)
  919. }
  920. } else {
  921. switch v := wr.write.(type) {
  922. case StreamError:
  923. // st may be unknown if the RST_STREAM was generated to reject bad input.
  924. if st, ok := sc.streams[v.StreamID]; ok {
  925. sc.closeStream(st, v)
  926. }
  927. case handlerPanicRST:
  928. sc.closeStream(wr.stream, errHandlerPanicked)
  929. }
  930. }
  931. // Reply (if requested) to unblock the ServeHTTP goroutine.
  932. wr.replyToWriter(res.err)
  933. sc.scheduleFrameWrite()
  934. }
  935. // scheduleFrameWrite tickles the frame writing scheduler.
  936. //
  937. // If a frame is already being written, nothing happens. This will be called again
  938. // when the frame is done being written.
  939. //
  940. // If a frame isn't being written we need to send one, the best frame
  941. // to send is selected, preferring first things that aren't
  942. // stream-specific (e.g. ACKing settings), and then finding the
  943. // highest priority stream.
  944. //
  945. // If a frame isn't being written and there's nothing else to send, we
  946. // flush the write buffer.
  947. func (sc *serverConn) scheduleFrameWrite() {
  948. sc.serveG.check()
  949. if sc.writingFrame || sc.inFrameScheduleLoop {
  950. return
  951. }
  952. sc.inFrameScheduleLoop = true
  953. for !sc.writingFrameAsync {
  954. if sc.needToSendGoAway {
  955. sc.needToSendGoAway = false
  956. sc.startFrameWrite(FrameWriteRequest{
  957. write: &writeGoAway{
  958. maxStreamID: sc.maxClientStreamID,
  959. code: sc.goAwayCode,
  960. },
  961. })
  962. continue
  963. }
  964. if sc.needToSendSettingsAck {
  965. sc.needToSendSettingsAck = false
  966. sc.startFrameWrite(FrameWriteRequest{write: writeSettingsAck{}})
  967. continue
  968. }
  969. if !sc.inGoAway || sc.goAwayCode == ErrCodeNo {
  970. if wr, ok := sc.writeSched.Pop(); ok {
  971. sc.startFrameWrite(wr)
  972. continue
  973. }
  974. }
  975. if sc.needsFrameFlush {
  976. sc.startFrameWrite(FrameWriteRequest{write: flushFrameWriter{}})
  977. sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
  978. continue
  979. }
  980. break
  981. }
  982. sc.inFrameScheduleLoop = false
  983. }
  984. // startGracefulShutdown sends a GOAWAY with ErrCodeNo to tell the
  985. // client we're gracefully shutting down. The connection isn't closed
  986. // until all current streams are done.
  987. func (sc *serverConn) startGracefulShutdown() {
  988. sc.goAwayIn(ErrCodeNo, 0)
  989. }
  990. func (sc *serverConn) goAway(code ErrCode) {
  991. sc.serveG.check()
  992. var forceCloseIn time.Duration
  993. if code != ErrCodeNo {
  994. forceCloseIn = 250 * time.Millisecond
  995. } else {
  996. // TODO: configurable
  997. forceCloseIn = 1 * time.Second
  998. }
  999. sc.goAwayIn(code, forceCloseIn)
  1000. }
  1001. func (sc *serverConn) goAwayIn(code ErrCode, forceCloseIn time.Duration) {
  1002. sc.serveG.check()
  1003. if sc.inGoAway {
  1004. return
  1005. }
  1006. if forceCloseIn != 0 {
  1007. sc.shutDownIn(forceCloseIn)
  1008. }
  1009. sc.inGoAway = true
  1010. sc.needToSendGoAway = true
  1011. sc.goAwayCode = code
  1012. sc.scheduleFrameWrite()
  1013. }
  1014. func (sc *serverConn) shutDownIn(d time.Duration) {
  1015. sc.serveG.check()
  1016. sc.shutdownTimer = time.NewTimer(d)
  1017. sc.shutdownTimerCh = sc.shutdownTimer.C
  1018. }
  1019. func (sc *serverConn) resetStream(se StreamError) {
  1020. sc.serveG.check()
  1021. sc.writeFrame(FrameWriteRequest{write: se})
  1022. if st, ok := sc.streams[se.StreamID]; ok {
  1023. st.resetQueued = true
  1024. }
  1025. }
  1026. // processFrameFromReader processes the serve loop's read from readFrameCh from the
  1027. // frame-reading goroutine.
  1028. // processFrameFromReader returns whether the connection should be kept open.
  1029. func (sc *serverConn) processFrameFromReader(res readFrameResult) bool {
  1030. sc.serveG.check()
  1031. err := res.err
  1032. if err != nil {
  1033. if err == ErrFrameTooLarge {
  1034. sc.goAway(ErrCodeFrameSize)
  1035. return true // goAway will close the loop
  1036. }
  1037. clientGone := err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err)
  1038. if clientGone {
  1039. // TODO: could we also get into this state if
  1040. // the peer does a half close
  1041. // (e.g. CloseWrite) because they're done
  1042. // sending frames but they're still wanting
  1043. // our open replies? Investigate.
  1044. // TODO: add CloseWrite to crypto/tls.Conn first
  1045. // so we have a way to test this? I suppose
  1046. // just for testing we could have a non-TLS mode.
  1047. return false
  1048. }
  1049. } else {
  1050. f := res.f
  1051. if VerboseLogs {
  1052. sc.vlogf("http2: server read frame %v", summarizeFrame(f))
  1053. }
  1054. err = sc.processFrame(f)
  1055. if err == nil {
  1056. return true
  1057. }
  1058. }
  1059. switch ev := err.(type) {
  1060. case StreamError:
  1061. sc.resetStream(ev)
  1062. return true
  1063. case goAwayFlowError:
  1064. sc.goAway(ErrCodeFlowControl)
  1065. return true
  1066. case ConnectionError:
  1067. sc.logf("http2: server connection error from %v: %v", sc.conn.RemoteAddr(), ev)
  1068. sc.goAway(ErrCode(ev))
  1069. return true // goAway will handle shutdown
  1070. default:
  1071. if res.err != nil {
  1072. sc.vlogf("http2: server closing client connection; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
  1073. } else {
  1074. sc.logf("http2: server closing client connection: %v", err)
  1075. }
  1076. return false
  1077. }
  1078. }
  1079. func (sc *serverConn) processFrame(f Frame) error {
  1080. sc.serveG.check()
  1081. // First frame received must be SETTINGS.
  1082. if !sc.sawFirstSettings {
  1083. if _, ok := f.(*SettingsFrame); !ok {
  1084. return ConnectionError(ErrCodeProtocol)
  1085. }
  1086. sc.sawFirstSettings = true
  1087. }
  1088. switch f := f.(type) {
  1089. case *SettingsFrame:
  1090. return sc.processSettings(f)
  1091. case *MetaHeadersFrame:
  1092. return sc.processHeaders(f)
  1093. case *WindowUpdateFrame:
  1094. return sc.processWindowUpdate(f)
  1095. case *PingFrame:
  1096. return sc.processPing(f)
  1097. case *DataFrame:
  1098. return sc.processData(f)
  1099. case *RSTStreamFrame:
  1100. return sc.processResetStream(f)
  1101. case *PriorityFrame:
  1102. return sc.processPriority(f)
  1103. case *GoAwayFrame:
  1104. return sc.processGoAway(f)
  1105. case *PushPromiseFrame:
  1106. // A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE
  1107. // frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1108. return ConnectionError(ErrCodeProtocol)
  1109. default:
  1110. sc.vlogf("http2: server ignoring frame: %v", f.Header())
  1111. return nil
  1112. }
  1113. }
  1114. func (sc *serverConn) processPing(f *PingFrame) error {
  1115. sc.serveG.check()
  1116. if f.IsAck() {
  1117. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  1118. // containing this flag."
  1119. return nil
  1120. }
  1121. if f.StreamID != 0 {
  1122. // "PING frames are not associated with any individual
  1123. // stream. If a PING frame is received with a stream
  1124. // identifier field value other than 0x0, the recipient MUST
  1125. // respond with a connection error (Section 5.4.1) of type
  1126. // PROTOCOL_ERROR."
  1127. return ConnectionError(ErrCodeProtocol)
  1128. }
  1129. if sc.inGoAway && sc.goAwayCode != ErrCodeNo {
  1130. return nil
  1131. }
  1132. sc.writeFrame(FrameWriteRequest{write: writePingAck{f}})
  1133. return nil
  1134. }
  1135. func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  1136. sc.serveG.check()
  1137. switch {
  1138. case f.StreamID != 0: // stream-level flow control
  1139. state, st := sc.state(f.StreamID)
  1140. if state == stateIdle {
  1141. // Section 5.1: "Receiving any frame other than HEADERS
  1142. // or PRIORITY on a stream in this state MUST be
  1143. // treated as a connection error (Section 5.4.1) of
  1144. // type PROTOCOL_ERROR."
  1145. return ConnectionError(ErrCodeProtocol)
  1146. }
  1147. if st == nil {
  1148. // "WINDOW_UPDATE can be sent by a peer that has sent a
  1149. // frame bearing the END_STREAM flag. This means that a
  1150. // receiver could receive a WINDOW_UPDATE frame on a "half
  1151. // closed (remote)" or "closed" stream. A receiver MUST
  1152. // NOT treat this as an error, see Section 5.1."
  1153. return nil
  1154. }
  1155. if !st.flow.add(int32(f.Increment)) {
  1156. return streamError(f.StreamID, ErrCodeFlowControl)
  1157. }
  1158. default: // connection-level flow control
  1159. if !sc.flow.add(int32(f.Increment)) {
  1160. return goAwayFlowError{}
  1161. }
  1162. }
  1163. sc.scheduleFrameWrite()
  1164. return nil
  1165. }
  1166. func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
  1167. sc.serveG.check()
  1168. state, st := sc.state(f.StreamID)
  1169. if state == stateIdle {
  1170. // 6.4 "RST_STREAM frames MUST NOT be sent for a
  1171. // stream in the "idle" state. If a RST_STREAM frame
  1172. // identifying an idle stream is received, the
  1173. // recipient MUST treat this as a connection error
  1174. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1175. return ConnectionError(ErrCodeProtocol)
  1176. }
  1177. if st != nil {
  1178. st.cancelCtx()
  1179. sc.closeStream(st, streamError(f.StreamID, f.ErrCode))
  1180. }
  1181. return nil
  1182. }
  1183. func (sc *serverConn) closeStream(st *stream, err error) {
  1184. sc.serveG.check()
  1185. if st.state == stateIdle || st.state == stateClosed {
  1186. panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
  1187. }
  1188. st.state = stateClosed
  1189. if st.isPushed() {
  1190. sc.curPushedStreams--
  1191. } else {
  1192. sc.curClientStreams--
  1193. }
  1194. delete(sc.streams, st.id)
  1195. if len(sc.streams) == 0 {
  1196. sc.setConnState(http.StateIdle)
  1197. if sc.srv.IdleTimeout != 0 {
  1198. sc.idleTimer.Reset(sc.srv.IdleTimeout)
  1199. }
  1200. if h1ServerKeepAlivesDisabled(sc.hs) {
  1201. sc.startGracefulShutdown()
  1202. }
  1203. }
  1204. if p := st.body; p != nil {
  1205. // Return any buffered unread bytes worth of conn-level flow control.
  1206. // See golang.org/issue/16481
  1207. sc.sendWindowUpdate(nil, p.Len())
  1208. p.CloseWithError(err)
  1209. }
  1210. st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc
  1211. sc.writeSched.CloseStream(st.id)
  1212. }
  1213. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  1214. sc.serveG.check()
  1215. if f.IsAck() {
  1216. sc.unackedSettings--
  1217. if sc.unackedSettings < 0 {
  1218. // Why is the peer ACKing settings we never sent?
  1219. // The spec doesn't mention this case, but
  1220. // hang up on them anyway.
  1221. return ConnectionError(ErrCodeProtocol)
  1222. }
  1223. return nil
  1224. }
  1225. if err := f.ForeachSetting(sc.processSetting); err != nil {
  1226. return err
  1227. }
  1228. sc.needToSendSettingsAck = true
  1229. sc.scheduleFrameWrite()
  1230. return nil
  1231. }
  1232. func (sc *serverConn) processSetting(s Setting) error {
  1233. sc.serveG.check()
  1234. if err := s.Valid(); err != nil {
  1235. return err
  1236. }
  1237. if VerboseLogs {
  1238. sc.vlogf("http2: server processing setting %v", s)
  1239. }
  1240. switch s.ID {
  1241. case SettingHeaderTableSize:
  1242. sc.headerTableSize = s.Val
  1243. sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
  1244. case SettingEnablePush:
  1245. sc.pushEnabled = s.Val != 0
  1246. case SettingMaxConcurrentStreams:
  1247. sc.clientMaxStreams = s.Val
  1248. case SettingInitialWindowSize:
  1249. return sc.processSettingInitialWindowSize(s.Val)
  1250. case SettingMaxFrameSize:
  1251. sc.maxFrameSize = int32(s.Val) // the maximum valid s.Val is < 2^31
  1252. case SettingMaxHeaderListSize:
  1253. sc.peerMaxHeaderListSize = s.Val
  1254. default:
  1255. // Unknown setting: "An endpoint that receives a SETTINGS
  1256. // frame with any unknown or unsupported identifier MUST
  1257. // ignore that setting."
  1258. if VerboseLogs {
  1259. sc.vlogf("http2: server ignoring unknown setting %v", s)
  1260. }
  1261. }
  1262. return nil
  1263. }
  1264. func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  1265. sc.serveG.check()
  1266. // Note: val already validated to be within range by
  1267. // processSetting's Valid call.
  1268. // "A SETTINGS frame can alter the initial flow control window
  1269. // size for all current streams. When the value of
  1270. // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  1271. // adjust the size of all stream flow control windows that it
  1272. // maintains by the difference between the new value and the
  1273. // old value."
  1274. old := sc.initialWindowSize
  1275. sc.initialWindowSize = int32(val)
  1276. growth := sc.initialWindowSize - old // may be negative
  1277. for _, st := range sc.streams {
  1278. if !st.flow.add(growth) {
  1279. // 6.9.2 Initial Flow Control Window Size
  1280. // "An endpoint MUST treat a change to
  1281. // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  1282. // control window to exceed the maximum size as a
  1283. // connection error (Section 5.4.1) of type
  1284. // FLOW_CONTROL_ERROR."
  1285. return ConnectionError(ErrCodeFlowControl)
  1286. }
  1287. }
  1288. return nil
  1289. }
  1290. func (sc *serverConn) processData(f *DataFrame) error {
  1291. sc.serveG.check()
  1292. if sc.inGoAway && sc.goAwayCode != ErrCodeNo {
  1293. return nil
  1294. }
  1295. data := f.Data()
  1296. // "If a DATA frame is received whose stream is not in "open"
  1297. // or "half closed (local)" state, the recipient MUST respond
  1298. // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  1299. id := f.Header().StreamID
  1300. state, st := sc.state(id)
  1301. if id == 0 || state == stateIdle {
  1302. // Section 5.1: "Receiving any frame other than HEADERS
  1303. // or PRIORITY on a stream in this state MUST be
  1304. // treated as a connection error (Section 5.4.1) of
  1305. // type PROTOCOL_ERROR."
  1306. return ConnectionError(ErrCodeProtocol)
  1307. }
  1308. if st == nil || state != stateOpen || st.gotTrailerHeader || st.resetQueued {
  1309. // This includes sending a RST_STREAM if the stream is
  1310. // in stateHalfClosedLocal (which currently means that
  1311. // the http.Handler returned, so it's done reading &
  1312. // done writing). Try to stop the client from sending
  1313. // more DATA.
  1314. // But still enforce their connection-level flow control,
  1315. // and return any flow control bytes since we're not going
  1316. // to consume them.
  1317. if sc.inflow.available() < int32(f.Length) {
  1318. return streamError(id, ErrCodeFlowControl)
  1319. }
  1320. // Deduct the flow control from inflow, since we're
  1321. // going to immediately add it back in
  1322. // sendWindowUpdate, which also schedules sending the
  1323. // frames.
  1324. sc.inflow.take(int32(f.Length))
  1325. sc.sendWindowUpdate(nil, int(f.Length)) // conn-level
  1326. if st != nil && st.resetQueued {
  1327. // Already have a stream error in flight. Don't send another.
  1328. return nil
  1329. }
  1330. return streamError(id, ErrCodeStreamClosed)
  1331. }
  1332. if st.body == nil {
  1333. panic("internal error: should have a body in this state")
  1334. }
  1335. // Sender sending more than they'd declared?
  1336. if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  1337. st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  1338. return streamError(id, ErrCodeStreamClosed)
  1339. }
  1340. if f.Length > 0 {
  1341. // Check whether the client has flow control quota.
  1342. if st.inflow.available() < int32(f.Length) {
  1343. return streamError(id, ErrCodeFlowControl)
  1344. }
  1345. st.inflow.take(int32(f.Length))
  1346. if len(data) > 0 {
  1347. wrote, err := st.body.Write(data)
  1348. if err != nil {
  1349. return streamError(id, ErrCodeStreamClosed)
  1350. }
  1351. if wrote != len(data) {
  1352. panic("internal error: bad Writer")
  1353. }
  1354. st.bodyBytes += int64(len(data))
  1355. }
  1356. // Return any padded flow control now, since we won't
  1357. // refund it later on body reads.
  1358. if pad := int32(f.Length) - int32(len(data)); pad > 0 {
  1359. sc.sendWindowUpdate32(nil, pad)
  1360. sc.sendWindowUpdate32(st, pad)
  1361. }
  1362. }
  1363. if f.StreamEnded() {
  1364. st.endStream()
  1365. }
  1366. return nil
  1367. }
  1368. func (sc *serverConn) processGoAway(f *GoAwayFrame) error {
  1369. sc.serveG.check()
  1370. if f.ErrCode != ErrCodeNo {
  1371. sc.logf("http2: received GOAWAY %+v, starting graceful shutdown", f)
  1372. } else {
  1373. sc.vlogf("http2: received GOAWAY %+v, starting graceful shutdown", f)
  1374. }
  1375. sc.startGracefulShutdown()
  1376. // http://tools.ietf.org/html/rfc7540#section-6.8
  1377. // We should not create any new streams, which means we should disable push.
  1378. sc.pushEnabled = false
  1379. return nil
  1380. }
  1381. // isPushed reports whether the stream is server-initiated.
  1382. func (st *stream) isPushed() bool {
  1383. return st.id%2 == 0
  1384. }
  1385. // endStream closes a Request.Body's pipe. It is called when a DATA
  1386. // frame says a request body is over (or after trailers).
  1387. func (st *stream) endStream() {
  1388. sc := st.sc
  1389. sc.serveG.check()
  1390. if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  1391. st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
  1392. st.declBodyBytes, st.bodyBytes))
  1393. } else {
  1394. st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest)
  1395. st.body.CloseWithError(io.EOF)
  1396. }
  1397. st.state = stateHalfClosedRemote
  1398. }
  1399. // copyTrailersToHandlerRequest is run in the Handler's goroutine in
  1400. // its Request.Body.Read just before it gets io.EOF.
  1401. func (st *stream) copyTrailersToHandlerRequest() {
  1402. for k, vv := range st.trailer {
  1403. if _, ok := st.reqTrailer[k]; ok {
  1404. // Only copy it over it was pre-declared.
  1405. st.reqTrailer[k] = vv
  1406. }
  1407. }
  1408. }
  1409. func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error {
  1410. sc.serveG.check()
  1411. id := f.StreamID
  1412. if sc.inGoAway {
  1413. // Ignore.
  1414. return nil
  1415. }
  1416. // http://tools.ietf.org/html/rfc7540#section-5.1.1
  1417. // Streams initiated by a client MUST use odd-numbered stream
  1418. // identifiers. [...] An endpoint that receives an unexpected
  1419. // stream identifier MUST respond with a connection error
  1420. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1421. if id%2 != 1 {
  1422. return ConnectionError(ErrCodeProtocol)
  1423. }
  1424. // A HEADERS frame can be used to create a new stream or
  1425. // send a trailer for an open one. If we already have a stream
  1426. // open, let it process its own HEADERS frame (trailers at this
  1427. // point, if it's valid).
  1428. if st := sc.streams[f.StreamID]; st != nil {
  1429. if st.resetQueued {
  1430. // We're sending RST_STREAM to close the stream, so don't bother
  1431. // processing this frame.
  1432. return nil
  1433. }
  1434. return st.processTrailerHeaders(f)
  1435. }
  1436. // [...] The identifier of a newly established stream MUST be
  1437. // numerically greater than all streams that the initiating
  1438. // endpoint has opened or reserved. [...] An endpoint that
  1439. // receives an unexpected stream identifier MUST respond with
  1440. // a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  1441. if id <= sc.maxClientStreamID {
  1442. return ConnectionError(ErrCodeProtocol)
  1443. }
  1444. sc.maxClientStreamID = id
  1445. if sc.idleTimer != nil {
  1446. sc.idleTimer.Stop()
  1447. }
  1448. // http://tools.ietf.org/html/rfc7540#section-5.1.2
  1449. // [...] Endpoints MUST NOT exceed the limit set by their peer. An
  1450. // endpoint that receives a HEADERS frame that causes their
  1451. // advertised concurrent stream limit to be exceeded MUST treat
  1452. // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR
  1453. // or REFUSED_STREAM.
  1454. if sc.curClientStreams+1 > sc.advMaxStreams {
  1455. if sc.unackedSettings == 0 {
  1456. // They should know better.
  1457. return streamError(id, ErrCodeProtocol)
  1458. }
  1459. // Assume it's a network race, where they just haven't
  1460. // received our last SETTINGS update. But actually
  1461. // this can't happen yet, because we don't yet provide
  1462. // a way for users to adjust server parameters at
  1463. // runtime.
  1464. return streamError(id, ErrCodeRefusedStream)
  1465. }
  1466. initialState := stateOpen
  1467. if f.StreamEnded() {
  1468. initialState = stateHalfClosedRemote
  1469. }
  1470. st := sc.newStream(id, 0, initialState)
  1471. if f.HasPriority() {
  1472. if err := checkPriority(f.StreamID, f.Priority); err != nil {
  1473. return err
  1474. }
  1475. sc.writeSched.AdjustStream(st.id, f.Priority)
  1476. }
  1477. rw, req, err := sc.newWriterAndRequest(st, f)
  1478. if err != nil {
  1479. return err
  1480. }
  1481. st.reqTrailer = req.Trailer
  1482. if st.reqTrailer != nil {
  1483. st.trailer = make(http.Header)
  1484. }
  1485. st.body = req.Body.(*requestBody).pipe // may be nil
  1486. st.declBodyBytes = req.ContentLength
  1487. handler := sc.handler.ServeHTTP
  1488. if f.Truncated {
  1489. // Their header list was too long. Send a 431 error.
  1490. handler = handleHeaderListTooLong
  1491. } else if err := checkValidHTTP2RequestHeaders(req.Header); err != nil {
  1492. handler = new400Handler(err)
  1493. }
  1494. // The net/http package sets the read deadline from the
  1495. // http.Server.ReadTimeout during the TLS handshake, but then
  1496. // passes the connection off to us with the deadline already
  1497. // set. Disarm it here after the request headers are read,
  1498. // similar to how the http1 server works. Here it's
  1499. // technically more like the http1 Server's ReadHeaderTimeout
  1500. // (in Go 1.8), though. That's a more sane option anyway.
  1501. if sc.hs.ReadTimeout != 0 {
  1502. sc.conn.SetReadDeadline(time.Time{})
  1503. }
  1504. go sc.runHandler(rw, req, handler)
  1505. return nil
  1506. }
  1507. func (st *stream) processTrailerHeaders(f *MetaHeadersFrame) error {
  1508. sc := st.sc
  1509. sc.serveG.check()
  1510. if st.gotTrailerHeader {
  1511. return ConnectionError(ErrCodeProtocol)
  1512. }
  1513. st.gotTrailerHeader = true
  1514. if !f.StreamEnded() {
  1515. return streamError(st.id, ErrCodeProtocol)
  1516. }
  1517. if len(f.PseudoFields()) > 0 {
  1518. return streamError(st.id, ErrCodeProtocol)
  1519. }
  1520. if st.trailer != nil {
  1521. for _, hf := range f.RegularFields() {
  1522. key := sc.canonicalHeader(hf.Name)
  1523. if !ValidTrailerHeader(key) {
  1524. // TODO: send more details to the peer somehow. But http2 has
  1525. // no way to send debug data at a stream level. Discuss with
  1526. // HTTP folk.
  1527. return streamError(st.id, ErrCodeProtocol)
  1528. }
  1529. st.trailer[key] = append(st.trailer[key], hf.Value)
  1530. }
  1531. }
  1532. st.endStream()
  1533. return nil
  1534. }
  1535. func checkPriority(streamID uint32, p PriorityParam) error {
  1536. if streamID == p.StreamDep {
  1537. // Section 5.3.1: "A stream cannot depend on itself. An endpoint MUST treat
  1538. // this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR."
  1539. // Section 5.3.3 says that a stream can depend on one of its dependencies,
  1540. // so it's only self-dependencies that are forbidden.
  1541. return streamError(streamID, ErrCodeProtocol)
  1542. }
  1543. return nil
  1544. }
  1545. func (sc *serverConn) processPriority(f *PriorityFrame) error {
  1546. if sc.inGoAway {
  1547. return nil
  1548. }
  1549. if err := checkPriority(f.StreamID, f.PriorityParam); err != nil {
  1550. return err
  1551. }
  1552. sc.writeSched.AdjustStream(f.StreamID, f.PriorityParam)
  1553. return nil
  1554. }
  1555. func (sc *serverConn) newStream(id, pusherID uint32, state streamState) *stream {
  1556. sc.serveG.check()
  1557. if id == 0 {
  1558. panic("internal error: cannot create stream with id 0")
  1559. }
  1560. ctx, cancelCtx := contextWithCancel(sc.baseCtx)
  1561. st := &stream{
  1562. sc: sc,
  1563. id: id,
  1564. state: state,
  1565. ctx: ctx,
  1566. cancelCtx: cancelCtx,
  1567. }
  1568. st.cw.Init()
  1569. st.flow.conn = &sc.flow // link to conn-level counter
  1570. st.flow.add(sc.initialWindowSize)
  1571. st.inflow.conn = &sc.inflow // link to conn-level counter
  1572. st.inflow.add(initialWindowSize) // TODO: update this when we send a higher initial window size in the initial settings
  1573. sc.streams[id] = st
  1574. sc.writeSched.OpenStream(st.id, OpenStreamOptions{PusherID: pusherID})
  1575. if st.isPushed() {
  1576. sc.curPushedStreams++
  1577. } else {
  1578. sc.curClientStreams++
  1579. }
  1580. if sc.curOpenStreams() == 1 {
  1581. sc.setConnState(http.StateActive)
  1582. }
  1583. return st
  1584. }
  1585. func (sc *serverConn) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*responseWriter, *http.Request, error) {
  1586. sc.serveG.check()
  1587. rp := requestParam{
  1588. method: f.PseudoValue("method"),
  1589. scheme: f.PseudoValue("scheme"),
  1590. authority: f.PseudoValue("authority"),
  1591. path: f.PseudoValue("path"),
  1592. }
  1593. isConnect := rp.method == "CONNECT"
  1594. if isConnect {
  1595. if rp.path != "" || rp.scheme != "" || rp.authority == "" {
  1596. return nil, nil, streamError(f.StreamID, ErrCodeProtocol)
  1597. }
  1598. } else if rp.method == "" || rp.path == "" || (rp.scheme != "https" && rp.scheme != "http") {
  1599. // See 8.1.2.6 Malformed Requests and Responses:
  1600. //
  1601. // Malformed requests or responses that are detected
  1602. // MUST be treated as a stream error (Section 5.4.2)
  1603. // of type PROTOCOL_ERROR."
  1604. //
  1605. // 8.1.2.3 Request Pseudo-Header Fields
  1606. // "All HTTP/2 requests MUST include exactly one valid
  1607. // value for the :method, :scheme, and :path
  1608. // pseudo-header fields"
  1609. return nil, nil, streamError(f.StreamID, ErrCodeProtocol)
  1610. }
  1611. bodyOpen := !f.StreamEnded()
  1612. if rp.method == "HEAD" && bodyOpen {
  1613. // HEAD requests can't have bodies
  1614. return nil, nil, streamError(f.StreamID, ErrCodeProtocol)
  1615. }
  1616. rp.header = make(http.Header)
  1617. for _, hf := range f.RegularFields() {
  1618. rp.header.Add(sc.canonicalHeader(hf.Name), hf.Value)
  1619. }
  1620. if rp.authority == "" {
  1621. rp.authority = rp.header.Get("Host")
  1622. }
  1623. rw, req, err := sc.newWriterAndRequestNoBody(st, rp)
  1624. if err != nil {
  1625. return nil, nil, err
  1626. }
  1627. if bodyOpen {
  1628. st.reqBuf = getRequestBodyBuf()
  1629. req.Body.(*requestBody).pipe = &pipe{
  1630. b: &fixedBuffer{buf: st.reqBuf},
  1631. }
  1632. if vv, ok := rp.header["Content-Length"]; ok {
  1633. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  1634. } else {
  1635. req.ContentLength = -1
  1636. }
  1637. }
  1638. return rw, req, nil
  1639. }
  1640. type requestParam struct {
  1641. method string
  1642. scheme, authority, path string
  1643. header http.Header
  1644. }
  1645. func (sc *serverConn) newWriterAndRequestNoBody(st *stream, rp requestParam) (*responseWriter, *http.Request, error) {
  1646. sc.serveG.check()
  1647. var tlsState *tls.ConnectionState // nil if not scheme https
  1648. if rp.scheme == "https" {
  1649. tlsState = sc.tlsState
  1650. }
  1651. needsContinue := rp.header.Get("Expect") == "100-continue"
  1652. if needsContinue {
  1653. rp.header.Del("Expect")
  1654. }
  1655. // Merge Cookie headers into one "; "-delimited value.
  1656. if cookies := rp.header["Cookie"]; len(cookies) > 1 {
  1657. rp.header.Set("Cookie", strings.Join(cookies, "; "))
  1658. }
  1659. // Setup Trailers
  1660. var trailer http.Header
  1661. for _, v := range rp.header["Trailer"] {
  1662. for _, key := range strings.Split(v, ",") {
  1663. key = http.CanonicalHeaderKey(strings.TrimSpace(key))
  1664. switch key {
  1665. case "Transfer-Encoding", "Trailer", "Content-Length":
  1666. // Bogus. (copy of http1 rules)
  1667. // Ignore.
  1668. default:
  1669. if trailer == nil {
  1670. trailer = make(http.Header)
  1671. }
  1672. trailer[key] = nil
  1673. }
  1674. }
  1675. }
  1676. delete(rp.header, "Trailer")
  1677. var url_ *url.URL
  1678. var requestURI string
  1679. if rp.method == "CONNECT" {
  1680. url_ = &url.URL{Host: rp.authority}
  1681. requestURI = rp.authority // mimic HTTP/1 server behavior
  1682. } else {
  1683. var err error
  1684. url_, err = url.ParseRequestURI(rp.path)
  1685. if err != nil {
  1686. return nil, nil, streamError(st.id, ErrCodeProtocol)
  1687. }
  1688. requestURI = rp.path
  1689. }
  1690. body := &requestBody{
  1691. conn: sc,
  1692. stream: st,
  1693. needsContinue: needsContinue,
  1694. }
  1695. req := &http.Request{
  1696. Method: rp.method,
  1697. URL: url_,
  1698. RemoteAddr: sc.remoteAddrStr,
  1699. Header: rp.header,
  1700. RequestURI: requestURI,
  1701. Proto: "HTTP/2.0",
  1702. ProtoMajor: 2,
  1703. ProtoMinor: 0,
  1704. TLS: tlsState,
  1705. Host: rp.authority,
  1706. Body: body,
  1707. Trailer: trailer,
  1708. }
  1709. req = requestWithContext(req, st.ctx)
  1710. rws := responseWriterStatePool.Get().(*responseWriterState)
  1711. bwSave := rws.bw
  1712. *rws = responseWriterState{} // zero all the fields
  1713. rws.conn = sc
  1714. rws.bw = bwSave
  1715. rws.bw.Reset(chunkWriter{rws})
  1716. rws.stream = st
  1717. rws.req = req
  1718. rws.body = body
  1719. rw := &responseWriter{rws: rws}
  1720. return rw, req, nil
  1721. }
  1722. var reqBodyCache = make(chan []byte, 8)
  1723. func getRequestBodyBuf() []byte {
  1724. select {
  1725. case b := <-reqBodyCache:
  1726. return b
  1727. default:
  1728. return make([]byte, initialWindowSize)
  1729. }
  1730. }
  1731. func putRequestBodyBuf(b []byte) {
  1732. select {
  1733. case reqBodyCache <- b:
  1734. default:
  1735. }
  1736. }
  1737. // Run on its own goroutine.
  1738. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) {
  1739. didPanic := true
  1740. defer func() {
  1741. rw.rws.stream.cancelCtx()
  1742. if didPanic {
  1743. e := recover()
  1744. sc.writeFrameFromHandler(FrameWriteRequest{
  1745. write: handlerPanicRST{rw.rws.stream.id},
  1746. stream: rw.rws.stream,
  1747. })
  1748. // Same as net/http:
  1749. if shouldLogPanic(e) {
  1750. const size = 64 << 10
  1751. buf := make([]byte, size)
  1752. buf = buf[:runtime.Stack(buf, false)]
  1753. sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf)
  1754. }
  1755. return
  1756. }
  1757. rw.handlerDone()
  1758. }()
  1759. handler(rw, req)
  1760. didPanic = false
  1761. }
  1762. func handleHeaderListTooLong(w http.ResponseWriter, r *http.Request) {
  1763. // 10.5.1 Limits on Header Block Size:
  1764. // .. "A server that receives a larger header block than it is
  1765. // willing to handle can send an HTTP 431 (Request Header Fields Too
  1766. // Large) status code"
  1767. const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+
  1768. w.WriteHeader(statusRequestHeaderFieldsTooLarge)
  1769. io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
  1770. }
  1771. // called from handler goroutines.
  1772. // h may be nil.
  1773. func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error {
  1774. sc.serveG.checkNotOn() // NOT on
  1775. var errc chan error
  1776. if headerData.h != nil {
  1777. // If there's a header map (which we don't own), so we have to block on
  1778. // waiting for this frame to be written, so an http.Flush mid-handler
  1779. // writes out the correct value of keys, before a handler later potentially
  1780. // mutates it.
  1781. errc = errChanPool.Get().(chan error)
  1782. }
  1783. if err := sc.writeFrameFromHandler(FrameWriteRequest{
  1784. write: headerData,
  1785. stream: st,
  1786. done: errc,
  1787. }); err != nil {
  1788. return err
  1789. }
  1790. if errc != nil {
  1791. select {
  1792. case err := <-errc:
  1793. errChanPool.Put(errc)
  1794. return err
  1795. case <-sc.doneServing:
  1796. return errClientDisconnected
  1797. case <-st.cw:
  1798. return errStreamClosed
  1799. }
  1800. }
  1801. return nil
  1802. }
  1803. // called from handler goroutines.
  1804. func (sc *serverConn) write100ContinueHeaders(st *stream) {
  1805. sc.writeFrameFromHandler(FrameWriteRequest{
  1806. write: write100ContinueHeadersFrame{st.id},
  1807. stream: st,
  1808. })
  1809. }
  1810. // A bodyReadMsg tells the server loop that the http.Handler read n
  1811. // bytes of the DATA from the client on the given stream.
  1812. type bodyReadMsg struct {
  1813. st *stream
  1814. n int
  1815. }
  1816. // called from handler goroutines.
  1817. // Notes that the handler for the given stream ID read n bytes of its body
  1818. // and schedules flow control tokens to be sent.
  1819. func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int, err error) {
  1820. sc.serveG.checkNotOn() // NOT on
  1821. if n > 0 {
  1822. select {
  1823. case sc.bodyReadCh <- bodyReadMsg{st, n}:
  1824. case <-sc.doneServing:
  1825. }
  1826. }
  1827. if err == io.EOF {
  1828. if buf := st.reqBuf; buf != nil {
  1829. st.reqBuf = nil // shouldn't matter; field unused by other
  1830. putRequestBodyBuf(buf)
  1831. }
  1832. }
  1833. }
  1834. func (sc *serverConn) noteBodyRead(st *stream, n int) {
  1835. sc.serveG.check()
  1836. sc.sendWindowUpdate(nil, n) // conn-level
  1837. if st.state != stateHalfClosedRemote && st.state != stateClosed {
  1838. // Don't send this WINDOW_UPDATE if the stream is closed
  1839. // remotely.
  1840. sc.sendWindowUpdate(st, n)
  1841. }
  1842. }
  1843. // st may be nil for conn-level
  1844. func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
  1845. sc.serveG.check()
  1846. // "The legal range for the increment to the flow control
  1847. // window is 1 to 2^31-1 (2,147,483,647) octets."
  1848. // A Go Read call on 64-bit machines could in theory read
  1849. // a larger Read than this. Very unlikely, but we handle it here
  1850. // rather than elsewhere for now.
  1851. const maxUint31 = 1<<31 - 1
  1852. for n >= maxUint31 {
  1853. sc.sendWindowUpdate32(st, maxUint31)
  1854. n -= maxUint31
  1855. }
  1856. sc.sendWindowUpdate32(st, int32(n))
  1857. }
  1858. // st may be nil for conn-level
  1859. func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) {
  1860. sc.serveG.check()
  1861. if n == 0 {
  1862. return
  1863. }
  1864. if n < 0 {
  1865. panic("negative update")
  1866. }
  1867. var streamID uint32
  1868. if st != nil {
  1869. streamID = st.id
  1870. }
  1871. sc.writeFrame(FrameWriteRequest{
  1872. write: writeWindowUpdate{streamID: streamID, n: uint32(n)},
  1873. stream: st,
  1874. })
  1875. var ok bool
  1876. if st == nil {
  1877. ok = sc.inflow.add(n)
  1878. } else {
  1879. ok = st.inflow.add(n)
  1880. }
  1881. if !ok {
  1882. panic("internal error; sent too many window updates without decrements?")
  1883. }
  1884. }
  1885. // requestBody is the Handler's Request.Body type.
  1886. // Read and Close may be called concurrently.
  1887. type requestBody struct {
  1888. stream *stream
  1889. conn *serverConn
  1890. closed bool // for use by Close only
  1891. sawEOF bool // for use by Read only
  1892. pipe *pipe // non-nil if we have a HTTP entity message body
  1893. needsContinue bool // need to send a 100-continue
  1894. }
  1895. func (b *requestBody) Close() error {
  1896. if b.pipe != nil && !b.closed {
  1897. b.pipe.BreakWithError(errClosedBody)
  1898. }
  1899. b.closed = true
  1900. return nil
  1901. }
  1902. func (b *requestBody) Read(p []byte) (n int, err error) {
  1903. if b.needsContinue {
  1904. b.needsContinue = false
  1905. b.conn.write100ContinueHeaders(b.stream)
  1906. }
  1907. if b.pipe == nil || b.sawEOF {
  1908. return 0, io.EOF
  1909. }
  1910. n, err = b.pipe.Read(p)
  1911. if err == io.EOF {
  1912. b.sawEOF = true
  1913. }
  1914. if b.conn == nil && inTests {
  1915. return
  1916. }
  1917. b.conn.noteBodyReadFromHandler(b.stream, n, err)
  1918. return
  1919. }
  1920. // responseWriter is the http.ResponseWriter implementation. It's
  1921. // intentionally small (1 pointer wide) to minimize garbage. The
  1922. // responseWriterState pointer inside is zeroed at the end of a
  1923. // request (in handlerDone) and calls on the responseWriter thereafter
  1924. // simply crash (caller's mistake), but the much larger responseWriterState
  1925. // and buffers are reused between multiple requests.
  1926. type responseWriter struct {
  1927. rws *responseWriterState
  1928. }
  1929. // Optional http.ResponseWriter interfaces implemented.
  1930. var (
  1931. _ http.CloseNotifier = (*responseWriter)(nil)
  1932. _ http.Flusher = (*responseWriter)(nil)
  1933. _ stringWriter = (*responseWriter)(nil)
  1934. )
  1935. type responseWriterState struct {
  1936. // immutable within a request:
  1937. stream *stream
  1938. req *http.Request
  1939. body *requestBody // to close at end of request, if DATA frames didn't
  1940. conn *serverConn
  1941. // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
  1942. bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
  1943. // mutated by http.Handler goroutine:
  1944. handlerHeader http.Header // nil until called
  1945. snapHeader http.Header // snapshot of handlerHeader at WriteHeader time
  1946. trailers []string // set in writeChunk
  1947. status int // status code passed to WriteHeader
  1948. wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
  1949. sentHeader bool // have we sent the header frame?
  1950. handlerDone bool // handler has finished
  1951. sentContentLen int64 // non-zero if handler set a Content-Length header
  1952. wroteBytes int64
  1953. closeNotifierMu sync.Mutex // guards closeNotifierCh
  1954. closeNotifierCh chan bool // nil until first used
  1955. }
  1956. type chunkWriter struct{ rws *responseWriterState }
  1957. func (cw chunkWriter) Write(p []byte) (n int, err error) { return cw.rws.writeChunk(p) }
  1958. func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) != 0 }
  1959. // declareTrailer is called for each Trailer header when the
  1960. // response header is written. It notes that a header will need to be
  1961. // written in the trailers at the end of the response.
  1962. func (rws *responseWriterState) declareTrailer(k string) {
  1963. k = http.CanonicalHeaderKey(k)
  1964. if !ValidTrailerHeader(k) {
  1965. // Forbidden by RFC 2616 14.40.
  1966. rws.conn.logf("ignoring invalid trailer %q", k)
  1967. return
  1968. }
  1969. if !strSliceContains(rws.trailers, k) {
  1970. rws.trailers = append(rws.trailers, k)
  1971. }
  1972. }
  1973. // writeChunk writes chunks from the bufio.Writer. But because
  1974. // bufio.Writer may bypass its chunking, sometimes p may be
  1975. // arbitrarily large.
  1976. //
  1977. // writeChunk is also responsible (on the first chunk) for sending the
  1978. // HEADER response.
  1979. func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
  1980. if !rws.wroteHeader {
  1981. rws.writeHeader(200)
  1982. }
  1983. isHeadResp := rws.req.Method == "HEAD"
  1984. if !rws.sentHeader {
  1985. rws.sentHeader = true
  1986. var ctype, clen string
  1987. if clen = rws.snapHeader.Get("Content-Length"); clen != "" {
  1988. rws.snapHeader.Del("Content-Length")
  1989. clen64, err := strconv.ParseInt(clen, 10, 64)
  1990. if err == nil && clen64 >= 0 {
  1991. rws.sentContentLen = clen64
  1992. } else {
  1993. clen = ""
  1994. }
  1995. }
  1996. if clen == "" && rws.handlerDone && bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) {
  1997. clen = strconv.Itoa(len(p))
  1998. }
  1999. _, hasContentType := rws.snapHeader["Content-Type"]
  2000. if !hasContentType && bodyAllowedForStatus(rws.status) {
  2001. ctype = http.DetectContentType(p)
  2002. }
  2003. var date string
  2004. if _, ok := rws.snapHeader["Date"]; !ok {
  2005. // TODO(bradfitz): be faster here, like net/http? measure.
  2006. date = time.Now().UTC().Format(http.TimeFormat)
  2007. }
  2008. for _, v := range rws.snapHeader["Trailer"] {
  2009. foreachHeaderElement(v, rws.declareTrailer)
  2010. }
  2011. endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp
  2012. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  2013. streamID: rws.stream.id,
  2014. httpResCode: rws.status,
  2015. h: rws.snapHeader,
  2016. endStream: endStream,
  2017. contentType: ctype,
  2018. contentLength: clen,
  2019. date: date,
  2020. })
  2021. if err != nil {
  2022. return 0, err
  2023. }
  2024. if endStream {
  2025. return 0, nil
  2026. }
  2027. }
  2028. if isHeadResp {
  2029. return len(p), nil
  2030. }
  2031. if len(p) == 0 && !rws.handlerDone {
  2032. return 0, nil
  2033. }
  2034. if rws.handlerDone {
  2035. rws.promoteUndeclaredTrailers()
  2036. }
  2037. endStream := rws.handlerDone && !rws.hasTrailers()
  2038. if len(p) > 0 || endStream {
  2039. // only send a 0 byte DATA frame if we're ending the stream.
  2040. if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil {
  2041. return 0, err
  2042. }
  2043. }
  2044. if rws.handlerDone && rws.hasTrailers() {
  2045. err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  2046. streamID: rws.stream.id,
  2047. h: rws.handlerHeader,
  2048. trailers: rws.trailers,
  2049. endStream: true,
  2050. })
  2051. return len(p), err
  2052. }
  2053. return len(p), nil
  2054. }
  2055. // TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
  2056. // that, if present, signals that the map entry is actually for
  2057. // the response trailers, and not the response headers. The prefix
  2058. // is stripped after the ServeHTTP call finishes and the values are
  2059. // sent in the trailers.
  2060. //
  2061. // This mechanism is intended only for trailers that are not known
  2062. // prior to the headers being written. If the set of trailers is fixed
  2063. // or known before the header is written, the normal Go trailers mechanism
  2064. // is preferred:
  2065. // https://golang.org/pkg/net/http/#ResponseWriter
  2066. // https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
  2067. const TrailerPrefix = "Trailer:"
  2068. // promoteUndeclaredTrailers permits http.Handlers to set trailers
  2069. // after the header has already been flushed. Because the Go
  2070. // ResponseWriter interface has no way to set Trailers (only the
  2071. // Header), and because we didn't want to expand the ResponseWriter
  2072. // interface, and because nobody used trailers, and because RFC 2616
  2073. // says you SHOULD (but not must) predeclare any trailers in the
  2074. // header, the official ResponseWriter rules said trailers in Go must
  2075. // be predeclared, and then we reuse the same ResponseWriter.Header()
  2076. // map to mean both Headers and Trailers. When it's time to write the
  2077. // Trailers, we pick out the fields of Headers that were declared as
  2078. // trailers. That worked for a while, until we found the first major
  2079. // user of Trailers in the wild: gRPC (using them only over http2),
  2080. // and gRPC libraries permit setting trailers mid-stream without
  2081. // predeclarnig them. So: change of plans. We still permit the old
  2082. // way, but we also permit this hack: if a Header() key begins with
  2083. // "Trailer:", the suffix of that key is a Trailer. Because ':' is an
  2084. // invalid token byte anyway, there is no ambiguity. (And it's already
  2085. // filtered out) It's mildly hacky, but not terrible.
  2086. //
  2087. // This method runs after the Handler is done and promotes any Header
  2088. // fields to be trailers.
  2089. func (rws *responseWriterState) promoteUndeclaredTrailers() {
  2090. for k, vv := range rws.handlerHeader {
  2091. if !strings.HasPrefix(k, TrailerPrefix) {
  2092. continue
  2093. }
  2094. trailerKey := strings.TrimPrefix(k, TrailerPrefix)
  2095. rws.declareTrailer(trailerKey)
  2096. rws.handlerHeader[http.CanonicalHeaderKey(trailerKey)] = vv
  2097. }
  2098. if len(rws.trailers) > 1 {
  2099. sorter := sorterPool.Get().(*sorter)
  2100. sorter.SortStrings(rws.trailers)
  2101. sorterPool.Put(sorter)
  2102. }
  2103. }
  2104. func (w *responseWriter) Flush() {
  2105. rws := w.rws
  2106. if rws == nil {
  2107. panic("Header called after Handler finished")
  2108. }
  2109. if rws.bw.Buffered() > 0 {
  2110. if err := rws.bw.Flush(); err != nil {
  2111. // Ignore the error. The frame writer already knows.
  2112. return
  2113. }
  2114. } else {
  2115. // The bufio.Writer won't call chunkWriter.Write
  2116. // (writeChunk with zero bytes, so we have to do it
  2117. // ourselves to force the HTTP response header and/or
  2118. // final DATA frame (with END_STREAM) to be sent.
  2119. rws.writeChunk(nil)
  2120. }
  2121. }
  2122. func (w *responseWriter) CloseNotify() <-chan bool {
  2123. rws := w.rws
  2124. if rws == nil {
  2125. panic("CloseNotify called after Handler finished")
  2126. }
  2127. rws.closeNotifierMu.Lock()
  2128. ch := rws.closeNotifierCh
  2129. if ch == nil {
  2130. ch = make(chan bool, 1)
  2131. rws.closeNotifierCh = ch
  2132. cw := rws.stream.cw
  2133. go func() {
  2134. cw.Wait() // wait for close
  2135. ch <- true
  2136. }()
  2137. }
  2138. rws.closeNotifierMu.Unlock()
  2139. return ch
  2140. }
  2141. func (w *responseWriter) Header() http.Header {
  2142. rws := w.rws
  2143. if rws == nil {
  2144. panic("Header called after Handler finished")
  2145. }
  2146. if rws.handlerHeader == nil {
  2147. rws.handlerHeader = make(http.Header)
  2148. }
  2149. return rws.handlerHeader
  2150. }
  2151. func (w *responseWriter) WriteHeader(code int) {
  2152. rws := w.rws
  2153. if rws == nil {
  2154. panic("WriteHeader called after Handler finished")
  2155. }
  2156. rws.writeHeader(code)
  2157. }
  2158. func (rws *responseWriterState) writeHeader(code int) {
  2159. if !rws.wroteHeader {
  2160. rws.wroteHeader = true
  2161. rws.status = code
  2162. if len(rws.handlerHeader) > 0 {
  2163. rws.snapHeader = cloneHeader(rws.handlerHeader)
  2164. }
  2165. }
  2166. }
  2167. func cloneHeader(h http.Header) http.Header {
  2168. h2 := make(http.Header, len(h))
  2169. for k, vv := range h {
  2170. vv2 := make([]string, len(vv))
  2171. copy(vv2, vv)
  2172. h2[k] = vv2
  2173. }
  2174. return h2
  2175. }
  2176. // The Life Of A Write is like this:
  2177. //
  2178. // * Handler calls w.Write or w.WriteString ->
  2179. // * -> rws.bw (*bufio.Writer) ->
  2180. // * (Handler migth call Flush)
  2181. // * -> chunkWriter{rws}
  2182. // * -> responseWriterState.writeChunk(p []byte)
  2183. // * -> responseWriterState.writeChunk (most of the magic; see comment there)
  2184. func (w *responseWriter) Write(p []byte) (n int, err error) {
  2185. return w.write(len(p), p, "")
  2186. }
  2187. func (w *responseWriter) WriteString(s string) (n int, err error) {
  2188. return w.write(len(s), nil, s)
  2189. }
  2190. // either dataB or dataS is non-zero.
  2191. func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  2192. rws := w.rws
  2193. if rws == nil {
  2194. panic("Write called after Handler finished")
  2195. }
  2196. if !rws.wroteHeader {
  2197. w.WriteHeader(200)
  2198. }
  2199. if !bodyAllowedForStatus(rws.status) {
  2200. return 0, http.ErrBodyNotAllowed
  2201. }
  2202. rws.wroteBytes += int64(len(dataB)) + int64(len(dataS)) // only one can be set
  2203. if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen {
  2204. // TODO: send a RST_STREAM
  2205. return 0, errors.New("http2: handler wrote more than declared Content-Length")
  2206. }
  2207. if dataB != nil {
  2208. return rws.bw.Write(dataB)
  2209. } else {
  2210. return rws.bw.WriteString(dataS)
  2211. }
  2212. }
  2213. func (w *responseWriter) handlerDone() {
  2214. rws := w.rws
  2215. rws.handlerDone = true
  2216. w.Flush()
  2217. w.rws = nil
  2218. responseWriterStatePool.Put(rws)
  2219. }
  2220. // Push errors.
  2221. var (
  2222. ErrRecursivePush = errors.New("http2: recursive push not allowed")
  2223. ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS")
  2224. )
  2225. // pushOptions is the internal version of http.PushOptions, which we
  2226. // cannot include here because it's only defined in Go 1.8 and later.
  2227. type pushOptions struct {
  2228. Method string
  2229. Header http.Header
  2230. }
  2231. func (w *responseWriter) push(target string, opts pushOptions) error {
  2232. st := w.rws.stream
  2233. sc := st.sc
  2234. sc.serveG.checkNotOn()
  2235. // No recursive pushes: "PUSH_PROMISE frames MUST only be sent on a peer-initiated stream."
  2236. // http://tools.ietf.org/html/rfc7540#section-6.6
  2237. if st.isPushed() {
  2238. return ErrRecursivePush
  2239. }
  2240. // Default options.
  2241. if opts.Method == "" {
  2242. opts.Method = "GET"
  2243. }
  2244. if opts.Header == nil {
  2245. opts.Header = http.Header{}
  2246. }
  2247. wantScheme := "http"
  2248. if w.rws.req.TLS != nil {
  2249. wantScheme = "https"
  2250. }
  2251. // Validate the request.
  2252. u, err := url.Parse(target)
  2253. if err != nil {
  2254. return err
  2255. }
  2256. if u.Scheme == "" {
  2257. if !strings.HasPrefix(target, "/") {
  2258. return fmt.Errorf("target must be an absolute URL or an absolute path: %q", target)
  2259. }
  2260. u.Scheme = wantScheme
  2261. u.Host = w.rws.req.Host
  2262. } else {
  2263. if u.Scheme != wantScheme {
  2264. return fmt.Errorf("cannot push URL with scheme %q from request with scheme %q", u.Scheme, wantScheme)
  2265. }
  2266. if u.Host == "" {
  2267. return errors.New("URL must have a host")
  2268. }
  2269. }
  2270. for k := range opts.Header {
  2271. if strings.HasPrefix(k, ":") {
  2272. return fmt.Errorf("promised request headers cannot include pseudo header %q", k)
  2273. }
  2274. // These headers are meaningful only if the request has a body,
  2275. // but PUSH_PROMISE requests cannot have a body.
  2276. // http://tools.ietf.org/html/rfc7540#section-8.2
  2277. // Also disallow Host, since the promised URL must be absolute.
  2278. switch strings.ToLower(k) {
  2279. case "content-length", "content-encoding", "trailer", "te", "expect", "host":
  2280. return fmt.Errorf("promised request headers cannot include %q", k)
  2281. }
  2282. }
  2283. if err := checkValidHTTP2RequestHeaders(opts.Header); err != nil {
  2284. return err
  2285. }
  2286. // The RFC effectively limits promised requests to GET and HEAD:
  2287. // "Promised requests MUST be cacheable [GET, HEAD, or POST], and MUST be safe [GET or HEAD]"
  2288. // http://tools.ietf.org/html/rfc7540#section-8.2
  2289. if opts.Method != "GET" && opts.Method != "HEAD" {
  2290. return fmt.Errorf("method %q must be GET or HEAD", opts.Method)
  2291. }
  2292. msg := startPushRequest{
  2293. parent: st,
  2294. method: opts.Method,
  2295. url: u,
  2296. header: cloneHeader(opts.Header),
  2297. done: errChanPool.Get().(chan error),
  2298. }
  2299. select {
  2300. case <-sc.doneServing:
  2301. return errClientDisconnected
  2302. case <-st.cw:
  2303. return errStreamClosed
  2304. case sc.wantStartPushCh <- msg:
  2305. }
  2306. select {
  2307. case <-sc.doneServing:
  2308. return errClientDisconnected
  2309. case <-st.cw:
  2310. return errStreamClosed
  2311. case err := <-msg.done:
  2312. errChanPool.Put(msg.done)
  2313. return err
  2314. }
  2315. }
  2316. type startPushRequest struct {
  2317. parent *stream
  2318. method string
  2319. url *url.URL
  2320. header http.Header
  2321. done chan error
  2322. }
  2323. func (sc *serverConn) startPush(msg startPushRequest) {
  2324. sc.serveG.check()
  2325. // http://tools.ietf.org/html/rfc7540#section-6.6.
  2326. // PUSH_PROMISE frames MUST only be sent on a peer-initiated stream that
  2327. // is in either the "open" or "half-closed (remote)" state.
  2328. if msg.parent.state != stateOpen && msg.parent.state != stateHalfClosedRemote {
  2329. // responseWriter.Push checks that the stream is peer-initiaed.
  2330. msg.done <- errStreamClosed
  2331. return
  2332. }
  2333. // http://tools.ietf.org/html/rfc7540#section-6.6.
  2334. if !sc.pushEnabled {
  2335. msg.done <- http.ErrNotSupported
  2336. return
  2337. }
  2338. // PUSH_PROMISE frames must be sent in increasing order by stream ID, so
  2339. // we allocate an ID for the promised stream lazily, when the PUSH_PROMISE
  2340. // is written. Once the ID is allocated, we start the request handler.
  2341. allocatePromisedID := func() (uint32, error) {
  2342. sc.serveG.check()
  2343. // Check this again, just in case. Technically, we might have received
  2344. // an updated SETTINGS by the time we got around to writing this frame.
  2345. if !sc.pushEnabled {
  2346. return 0, http.ErrNotSupported
  2347. }
  2348. // http://tools.ietf.org/html/rfc7540#section-6.5.2.
  2349. if sc.curPushedStreams+1 > sc.clientMaxStreams {
  2350. return 0, ErrPushLimitReached
  2351. }
  2352. // http://tools.ietf.org/html/rfc7540#section-5.1.1.
  2353. // Streams initiated by the server MUST use even-numbered identifiers.
  2354. // A server that is unable to establish a new stream identifier can send a GOAWAY
  2355. // frame so that the client is forced to open a new connection for new streams.
  2356. if sc.maxPushPromiseID+2 >= 1<<31 {
  2357. sc.startGracefulShutdown()
  2358. return 0, ErrPushLimitReached
  2359. }
  2360. sc.maxPushPromiseID += 2
  2361. promisedID := sc.maxPushPromiseID
  2362. // http://tools.ietf.org/html/rfc7540#section-8.2.
  2363. // Strictly speaking, the new stream should start in "reserved (local)", then
  2364. // transition to "half closed (remote)" after sending the initial HEADERS, but
  2365. // we start in "half closed (remote)" for simplicity.
  2366. // See further comments at the definition of stateHalfClosedRemote.
  2367. promised := sc.newStream(promisedID, msg.parent.id, stateHalfClosedRemote)
  2368. rw, req, err := sc.newWriterAndRequestNoBody(promised, requestParam{
  2369. method: msg.method,
  2370. scheme: msg.url.Scheme,
  2371. authority: msg.url.Host,
  2372. path: msg.url.RequestURI(),
  2373. header: cloneHeader(msg.header), // clone since handler runs concurrently with writing the PUSH_PROMISE
  2374. })
  2375. if err != nil {
  2376. // Should not happen, since we've already validated msg.url.
  2377. panic(fmt.Sprintf("newWriterAndRequestNoBody(%+v): %v", msg.url, err))
  2378. }
  2379. go sc.runHandler(rw, req, sc.handler.ServeHTTP)
  2380. return promisedID, nil
  2381. }
  2382. sc.writeFrame(FrameWriteRequest{
  2383. write: &writePushPromise{
  2384. streamID: msg.parent.id,
  2385. method: msg.method,
  2386. url: msg.url,
  2387. h: msg.header,
  2388. allocatePromisedID: allocatePromisedID,
  2389. },
  2390. stream: msg.parent,
  2391. done: msg.done,
  2392. })
  2393. }
  2394. // foreachHeaderElement splits v according to the "#rule" construction
  2395. // in RFC 2616 section 2.1 and calls fn for each non-empty element.
  2396. func foreachHeaderElement(v string, fn func(string)) {
  2397. v = textproto.TrimString(v)
  2398. if v == "" {
  2399. return
  2400. }
  2401. if !strings.Contains(v, ",") {
  2402. fn(v)
  2403. return
  2404. }
  2405. for _, f := range strings.Split(v, ",") {
  2406. if f = textproto.TrimString(f); f != "" {
  2407. fn(f)
  2408. }
  2409. }
  2410. }
  2411. // From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2
  2412. var connHeaders = []string{
  2413. "Connection",
  2414. "Keep-Alive",
  2415. "Proxy-Connection",
  2416. "Transfer-Encoding",
  2417. "Upgrade",
  2418. }
  2419. // checkValidHTTP2RequestHeaders checks whether h is a valid HTTP/2 request,
  2420. // per RFC 7540 Section 8.1.2.2.
  2421. // The returned error is reported to users.
  2422. func checkValidHTTP2RequestHeaders(h http.Header) error {
  2423. for _, k := range connHeaders {
  2424. if _, ok := h[k]; ok {
  2425. return fmt.Errorf("request header %q is not valid in HTTP/2", k)
  2426. }
  2427. }
  2428. te := h["Te"]
  2429. if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) {
  2430. return errors.New(`request header "TE" may only be "trailers" in HTTP/2`)
  2431. }
  2432. return nil
  2433. }
  2434. func new400Handler(err error) http.HandlerFunc {
  2435. return func(w http.ResponseWriter, r *http.Request) {
  2436. http.Error(w, err.Error(), http.StatusBadRequest)
  2437. }
  2438. }
  2439. // ValidTrailerHeader reports whether name is a valid header field name to appear
  2440. // in trailers.
  2441. // See: http://tools.ietf.org/html/rfc7230#section-4.1.2
  2442. func ValidTrailerHeader(name string) bool {
  2443. name = http.CanonicalHeaderKey(name)
  2444. if strings.HasPrefix(name, "If-") || badTrailer[name] {
  2445. return false
  2446. }
  2447. return true
  2448. }
  2449. var badTrailer = map[string]bool{
  2450. "Authorization": true,
  2451. "Cache-Control": true,
  2452. "Connection": true,
  2453. "Content-Encoding": true,
  2454. "Content-Length": true,
  2455. "Content-Range": true,
  2456. "Content-Type": true,
  2457. "Expect": true,
  2458. "Host": true,
  2459. "Keep-Alive": true,
  2460. "Max-Forwards": true,
  2461. "Pragma": true,
  2462. "Proxy-Authenticate": true,
  2463. "Proxy-Authorization": true,
  2464. "Proxy-Connection": true,
  2465. "Range": true,
  2466. "Realm": true,
  2467. "Te": true,
  2468. "Trailer": true,
  2469. "Transfer-Encoding": true,
  2470. "Www-Authenticate": true,
  2471. }
  2472. // h1ServerShutdownChan returns a channel that will be closed when the
  2473. // provided *http.Server wants to shut down.
  2474. //
  2475. // This is a somewhat hacky way to get at http1 innards. It works
  2476. // when the http2 code is bundled into the net/http package in the
  2477. // standard library. The alternatives ended up making the cmd/go tool
  2478. // depend on http Servers. This is the lightest option for now.
  2479. // This is tested via the TestServeShutdown* tests in net/http.
  2480. func h1ServerShutdownChan(hs *http.Server) <-chan struct{} {
  2481. if fn := testh1ServerShutdownChan; fn != nil {
  2482. return fn(hs)
  2483. }
  2484. var x interface{} = hs
  2485. type I interface {
  2486. getDoneChan() <-chan struct{}
  2487. }
  2488. if hs, ok := x.(I); ok {
  2489. return hs.getDoneChan()
  2490. }
  2491. return nil
  2492. }
  2493. // optional test hook for h1ServerShutdownChan.
  2494. var testh1ServerShutdownChan func(hs *http.Server) <-chan struct{}
  2495. // h1ServerKeepAlivesDisabled reports whether hs has its keep-alives
  2496. // disabled. See comments on h1ServerShutdownChan above for why
  2497. // the code is written this way.
  2498. func h1ServerKeepAlivesDisabled(hs *http.Server) bool {
  2499. var x interface{} = hs
  2500. type I interface {
  2501. doKeepAlives() bool
  2502. }
  2503. if hs, ok := x.(I); ok {
  2504. return !hs.doKeepAlives()
  2505. }
  2506. return false
  2507. }