server.go 77 KB

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