write.go 11 KB

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