server.go 80 KB

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