server.go 78 KB

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