write.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. package http2
  5. import (
  6. "bytes"
  7. "fmt"
  8. "log"
  9. "net/http"
  10. "net/url"
  11. "golang.org/x/net/http/httpguts"
  12. "golang.org/x/net/http2/hpack"
  13. )
  14. // writeFramer is implemented by any type that is used to write frames.
  15. type writeFramer interface {
  16. writeFrame(writeContext) error
  17. // staysWithinBuffer reports whether this writer promises that
  18. // it will only write less than or equal to size bytes, and it
  19. // won't Flush the write context.
  20. staysWithinBuffer(size int) bool
  21. }
  22. // writeContext is the interface needed by the various frame writer
  23. // types below. All the writeFrame methods below are scheduled via the
  24. // frame writing scheduler (see writeScheduler in writesched.go).
  25. //
  26. // This interface is implemented by *serverConn.
  27. //
  28. // TODO: decide whether to a) use this in the client code (which didn't
  29. // end up using this yet, because it has a simpler design, not
  30. // currently implementing priorities), or b) delete this and
  31. // make the server code a bit more concrete.
  32. type writeContext interface {
  33. Framer() *Framer
  34. Flush() error
  35. CloseConn() error
  36. // HeaderEncoder returns an HPACK encoder that writes to the
  37. // returned buffer.
  38. HeaderEncoder() (*hpack.Encoder, *bytes.Buffer)
  39. }
  40. // writeEndsStream reports whether w writes a frame that will transition
  41. // the stream to a half-closed local state. This returns false for RST_STREAM,
  42. // which closes the entire stream (not just the local half).
  43. func writeEndsStream(w writeFramer) bool {
  44. switch v := w.(type) {
  45. case *writeData:
  46. return v.endStream
  47. case *writeResHeaders:
  48. return v.endStream
  49. case nil:
  50. // This can only happen if the caller reuses w after it's
  51. // been intentionally nil'ed out to prevent use. Keep this
  52. // here to catch future refactoring breaking it.
  53. panic("writeEndsStream called on nil writeFramer")
  54. }
  55. return false
  56. }
  57. type flushFrameWriter struct{}
  58. func (flushFrameWriter) writeFrame(ctx writeContext) error {
  59. return ctx.Flush()
  60. }
  61. func (flushFrameWriter) staysWithinBuffer(max int) bool { return false }
  62. type writeSettings []Setting
  63. func (s writeSettings) staysWithinBuffer(max int) bool {
  64. const settingSize = 6 // uint16 + uint32
  65. return frameHeaderLen+settingSize*len(s) <= max
  66. }
  67. func (s writeSettings) writeFrame(ctx writeContext) error {
  68. return ctx.Framer().WriteSettings([]Setting(s)...)
  69. }
  70. type writeGoAway struct {
  71. maxStreamID uint32
  72. code ErrCode
  73. }
  74. func (p *writeGoAway) writeFrame(ctx writeContext) error {
  75. err := ctx.Framer().WriteGoAway(p.maxStreamID, p.code, nil)
  76. ctx.Flush() // ignore error: we're hanging up on them anyway
  77. return err
  78. }
  79. func (*writeGoAway) staysWithinBuffer(max int) bool { return false } // flushes
  80. type writeData struct {
  81. streamID uint32
  82. p []byte
  83. endStream bool
  84. }
  85. func (w *writeData) String() string {
  86. return fmt.Sprintf("writeData(stream=%d, p=%d, endStream=%v)", w.streamID, len(w.p), w.endStream)
  87. }
  88. func (w *writeData) writeFrame(ctx writeContext) error {
  89. return ctx.Framer().WriteData(w.streamID, w.endStream, w.p)
  90. }
  91. func (w *writeData) staysWithinBuffer(max int) bool {
  92. return frameHeaderLen+len(w.p) <= max
  93. }
  94. // handlerPanicRST is the message sent from handler goroutines when
  95. // the handler panics.
  96. type handlerPanicRST struct {
  97. StreamID uint32
  98. }
  99. func (hp handlerPanicRST) writeFrame(ctx writeContext) error {
  100. return ctx.Framer().WriteRSTStream(hp.StreamID, ErrCodeInternal)
  101. }
  102. func (hp handlerPanicRST) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max }
  103. func (se StreamError) writeFrame(ctx writeContext) error {
  104. return ctx.Framer().WriteRSTStream(se.StreamID, se.Code)
  105. }
  106. func (se StreamError) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max }
  107. type writePingAck struct{ pf *PingFrame }
  108. func (w writePingAck) writeFrame(ctx writeContext) error {
  109. return ctx.Framer().WritePing(true, w.pf.Data)
  110. }
  111. func (w writePingAck) staysWithinBuffer(max int) bool { return frameHeaderLen+len(w.pf.Data) <= max }
  112. type writeSettingsAck struct{}
  113. func (writeSettingsAck) writeFrame(ctx writeContext) error {
  114. return ctx.Framer().WriteSettingsAck()
  115. }
  116. func (writeSettingsAck) staysWithinBuffer(max int) bool { return frameHeaderLen <= max }
  117. // splitHeaderBlock splits headerBlock into fragments so that each fragment fits
  118. // in a single frame, then calls fn for each fragment. firstFrag/lastFrag are true
  119. // for the first/last fragment, respectively.
  120. func splitHeaderBlock(ctx writeContext, headerBlock []byte, fn func(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error) error {
  121. // For now we're lazy and just pick the minimum MAX_FRAME_SIZE
  122. // that all peers must support (16KB). Later we could care
  123. // more and send larger frames if the peer advertised it, but
  124. // there's little point. Most headers are small anyway (so we
  125. // generally won't have CONTINUATION frames), and extra frames
  126. // only waste 9 bytes anyway.
  127. const maxFrameSize = 16384
  128. first := true
  129. for len(headerBlock) > 0 {
  130. frag := headerBlock
  131. if len(frag) > maxFrameSize {
  132. frag = frag[:maxFrameSize]
  133. }
  134. headerBlock = headerBlock[len(frag):]
  135. if err := fn(ctx, frag, first, len(headerBlock) == 0); err != nil {
  136. return err
  137. }
  138. first = false
  139. }
  140. return nil
  141. }
  142. // writeResHeaders is a request to write a HEADERS and 0+ CONTINUATION frames
  143. // for HTTP response headers or trailers from a server handler.
  144. type writeResHeaders struct {
  145. streamID uint32
  146. httpResCode int // 0 means no ":status" line
  147. h http.Header // may be nil
  148. trailers []string // if non-nil, which keys of h to write. nil means all.
  149. endStream bool
  150. date string
  151. contentType string
  152. contentLength string
  153. }
  154. func encKV(enc *hpack.Encoder, k, v string) {
  155. if VerboseLogs {
  156. log.Printf("http2: server encoding header %q = %q", k, v)
  157. }
  158. enc.WriteField(hpack.HeaderField{Name: k, Value: v})
  159. }
  160. func (w *writeResHeaders) staysWithinBuffer(max int) bool {
  161. // TODO: this is a common one. It'd be nice to return true
  162. // here and get into the fast path if we could be clever and
  163. // calculate the size fast enough, or at least a conservative
  164. // upper bound that usually fires. (Maybe if w.h and
  165. // w.trailers are nil, so we don't need to enumerate it.)
  166. // Otherwise I'm afraid that just calculating the length to
  167. // answer this question would be slower than the ~2µs benefit.
  168. return false
  169. }
  170. func (w *writeResHeaders) writeFrame(ctx writeContext) error {
  171. enc, buf := ctx.HeaderEncoder()
  172. buf.Reset()
  173. if w.httpResCode != 0 {
  174. encKV(enc, ":status", httpCodeString(w.httpResCode))
  175. }
  176. encodeHeaders(enc, w.h, w.trailers)
  177. if w.contentType != "" {
  178. encKV(enc, "content-type", w.contentType)
  179. }
  180. if w.contentLength != "" {
  181. encKV(enc, "content-length", w.contentLength)
  182. }
  183. if w.date != "" {
  184. encKV(enc, "date", w.date)
  185. }
  186. headerBlock := buf.Bytes()
  187. if len(headerBlock) == 0 && w.trailers == nil {
  188. panic("unexpected empty hpack")
  189. }
  190. return splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock)
  191. }
  192. func (w *writeResHeaders) writeHeaderBlock(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error {
  193. if firstFrag {
  194. return ctx.Framer().WriteHeaders(HeadersFrameParam{
  195. StreamID: w.streamID,
  196. BlockFragment: frag,
  197. EndStream: w.endStream,
  198. EndHeaders: lastFrag,
  199. })
  200. } else {
  201. return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag)
  202. }
  203. }
  204. // writePushPromise is a request to write a PUSH_PROMISE and 0+ CONTINUATION frames.
  205. type writePushPromise struct {
  206. streamID uint32 // pusher stream
  207. method string // for :method
  208. url *url.URL // for :scheme, :authority, :path
  209. h http.Header
  210. // Creates an ID for a pushed stream. This runs on serveG just before
  211. // the frame is written. The returned ID is copied to promisedID.
  212. allocatePromisedID func() (uint32, error)
  213. promisedID uint32
  214. }
  215. func (w *writePushPromise) staysWithinBuffer(max int) bool {
  216. // TODO: see writeResHeaders.staysWithinBuffer
  217. return false
  218. }
  219. func (w *writePushPromise) writeFrame(ctx writeContext) error {
  220. enc, buf := ctx.HeaderEncoder()
  221. buf.Reset()
  222. encKV(enc, ":method", w.method)
  223. encKV(enc, ":scheme", w.url.Scheme)
  224. encKV(enc, ":authority", w.url.Host)
  225. encKV(enc, ":path", w.url.RequestURI())
  226. encodeHeaders(enc, w.h, nil)
  227. headerBlock := buf.Bytes()
  228. if len(headerBlock) == 0 {
  229. panic("unexpected empty hpack")
  230. }
  231. return splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock)
  232. }
  233. func (w *writePushPromise) writeHeaderBlock(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error {
  234. if firstFrag {
  235. return ctx.Framer().WritePushPromise(PushPromiseParam{
  236. StreamID: w.streamID,
  237. PromiseID: w.promisedID,
  238. BlockFragment: frag,
  239. EndHeaders: lastFrag,
  240. })
  241. } else {
  242. return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag)
  243. }
  244. }
  245. type write100ContinueHeadersFrame struct {
  246. streamID uint32
  247. }
  248. func (w write100ContinueHeadersFrame) writeFrame(ctx writeContext) error {
  249. enc, buf := ctx.HeaderEncoder()
  250. buf.Reset()
  251. encKV(enc, ":status", "100")
  252. return ctx.Framer().WriteHeaders(HeadersFrameParam{
  253. StreamID: w.streamID,
  254. BlockFragment: buf.Bytes(),
  255. EndStream: false,
  256. EndHeaders: true,
  257. })
  258. }
  259. func (w write100ContinueHeadersFrame) staysWithinBuffer(max int) bool {
  260. // Sloppy but conservative:
  261. return 9+2*(len(":status")+len("100")) <= max
  262. }
  263. type writeWindowUpdate struct {
  264. streamID uint32 // or 0 for conn-level
  265. n uint32
  266. }
  267. func (wu writeWindowUpdate) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max }
  268. func (wu writeWindowUpdate) writeFrame(ctx writeContext) error {
  269. return ctx.Framer().WriteWindowUpdate(wu.streamID, wu.n)
  270. }
  271. // encodeHeaders encodes an http.Header. If keys is not nil, then (k, h[k])
  272. // is encoded only if k is in keys.
  273. func encodeHeaders(enc *hpack.Encoder, h http.Header, keys []string) {
  274. if keys == nil {
  275. sorter := sorterPool.Get().(*sorter)
  276. // Using defer here, since the returned keys from the
  277. // sorter.Keys method is only valid until the sorter
  278. // is returned:
  279. defer sorterPool.Put(sorter)
  280. keys = sorter.Keys(h)
  281. }
  282. for _, k := range keys {
  283. vv := h[k]
  284. k = lowerHeader(k)
  285. if !validWireHeaderFieldName(k) {
  286. // Skip it as backup paranoia. Per
  287. // golang.org/issue/14048, these should
  288. // already be rejected at a higher level.
  289. continue
  290. }
  291. isTE := k == "transfer-encoding"
  292. for _, v := range vv {
  293. if !httpguts.ValidHeaderFieldValue(v) {
  294. // TODO: return an error? golang.org/issue/14048
  295. // For now just omit it.
  296. continue
  297. }
  298. // TODO: more of "8.1.2.2 Connection-Specific Header Fields"
  299. if isTE && v != "trailers" {
  300. continue
  301. }
  302. encKV(enc, k, v)
  303. }
  304. }
  305. }