write.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. "net/http"
  9. "time"
  10. "golang.org/x/net/http2/hpack"
  11. )
  12. // writeFramer is implemented by any type that is used to write frames.
  13. type writeFramer interface {
  14. writeFrame(writeContext) error
  15. }
  16. // writeContext is the interface needed by the various frame writer
  17. // types below. All the writeFrame methods below are scheduled via the
  18. // frame writing scheduler (see writeScheduler in writesched.go).
  19. //
  20. // This interface is implemented by *serverConn.
  21. //
  22. // TODO: decide whether to a) use this in the client code (which didn't
  23. // end up using this yet, because it has a simpler design, not
  24. // currently implementing priorities), or b) delete this and
  25. // make the server code a bit more concrete.
  26. type writeContext interface {
  27. Framer() *Framer
  28. Flush() error
  29. CloseConn() error
  30. // HeaderEncoder returns an HPACK encoder that writes to the
  31. // returned buffer.
  32. HeaderEncoder() (*hpack.Encoder, *bytes.Buffer)
  33. }
  34. // endsStream reports whether the given frame writer w will locally
  35. // close the stream.
  36. func endsStream(w writeFramer) bool {
  37. switch v := w.(type) {
  38. case *writeData:
  39. return v.endStream
  40. case *writeResHeaders:
  41. return v.endStream
  42. case nil:
  43. // This can only happen if the caller reuses w after it's
  44. // been intentionally nil'ed out to prevent use. Keep this
  45. // here to catch future refactoring breaking it.
  46. panic("endsStream called on nil writeFramer")
  47. }
  48. return false
  49. }
  50. type flushFrameWriter struct{}
  51. func (flushFrameWriter) writeFrame(ctx writeContext) error {
  52. return ctx.Flush()
  53. }
  54. type writeSettings []Setting
  55. func (s writeSettings) writeFrame(ctx writeContext) error {
  56. return ctx.Framer().WriteSettings([]Setting(s)...)
  57. }
  58. type writeGoAway struct {
  59. maxStreamID uint32
  60. code ErrCode
  61. }
  62. func (p *writeGoAway) writeFrame(ctx writeContext) error {
  63. err := ctx.Framer().WriteGoAway(p.maxStreamID, p.code, nil)
  64. if p.code != 0 {
  65. ctx.Flush() // ignore error: we're hanging up on them anyway
  66. time.Sleep(50 * time.Millisecond)
  67. ctx.CloseConn()
  68. }
  69. return err
  70. }
  71. type writeData struct {
  72. streamID uint32
  73. p []byte
  74. endStream bool
  75. }
  76. func (w *writeData) String() string {
  77. return fmt.Sprintf("writeData(stream=%d, p=%d, endStream=%v)", w.streamID, len(w.p), w.endStream)
  78. }
  79. func (w *writeData) writeFrame(ctx writeContext) error {
  80. return ctx.Framer().WriteData(w.streamID, w.endStream, w.p)
  81. }
  82. func (se StreamError) writeFrame(ctx writeContext) error {
  83. return ctx.Framer().WriteRSTStream(se.StreamID, se.Code)
  84. }
  85. type writePingAck struct{ pf *PingFrame }
  86. func (w writePingAck) writeFrame(ctx writeContext) error {
  87. return ctx.Framer().WritePing(true, w.pf.Data)
  88. }
  89. type writeSettingsAck struct{}
  90. func (writeSettingsAck) writeFrame(ctx writeContext) error {
  91. return ctx.Framer().WriteSettingsAck()
  92. }
  93. // writeResHeaders is a request to write a HEADERS and 0+ CONTINUATION frames
  94. // for HTTP response headers from a server handler.
  95. type writeResHeaders struct {
  96. streamID uint32
  97. httpResCode int
  98. h http.Header // may be nil
  99. endStream bool
  100. date string
  101. contentType string
  102. contentLength string
  103. }
  104. func (w *writeResHeaders) writeFrame(ctx writeContext) error {
  105. enc, buf := ctx.HeaderEncoder()
  106. buf.Reset()
  107. enc.WriteField(hpack.HeaderField{Name: ":status", Value: httpCodeString(w.httpResCode)})
  108. for k, vv := range w.h {
  109. k = lowerHeader(k)
  110. for _, v := range vv {
  111. // TODO: more of "8.1.2.2 Connection-Specific Header Fields"
  112. if k == "transfer-encoding" && v != "trailers" {
  113. continue
  114. }
  115. enc.WriteField(hpack.HeaderField{Name: k, Value: v})
  116. }
  117. }
  118. if w.contentType != "" {
  119. enc.WriteField(hpack.HeaderField{Name: "content-type", Value: w.contentType})
  120. }
  121. if w.contentLength != "" {
  122. enc.WriteField(hpack.HeaderField{Name: "content-length", Value: w.contentLength})
  123. }
  124. if w.date != "" {
  125. enc.WriteField(hpack.HeaderField{Name: "date", Value: w.date})
  126. }
  127. headerBlock := buf.Bytes()
  128. if len(headerBlock) == 0 {
  129. panic("unexpected empty hpack")
  130. }
  131. // For now we're lazy and just pick the minimum MAX_FRAME_SIZE
  132. // that all peers must support (16KB). Later we could care
  133. // more and send larger frames if the peer advertised it, but
  134. // there's little point. Most headers are small anyway (so we
  135. // generally won't have CONTINUATION frames), and extra frames
  136. // only waste 9 bytes anyway.
  137. const maxFrameSize = 16384
  138. first := true
  139. for len(headerBlock) > 0 {
  140. frag := headerBlock
  141. if len(frag) > maxFrameSize {
  142. frag = frag[:maxFrameSize]
  143. }
  144. headerBlock = headerBlock[len(frag):]
  145. endHeaders := len(headerBlock) == 0
  146. var err error
  147. if first {
  148. first = false
  149. err = ctx.Framer().WriteHeaders(HeadersFrameParam{
  150. StreamID: w.streamID,
  151. BlockFragment: frag,
  152. EndStream: w.endStream,
  153. EndHeaders: endHeaders,
  154. })
  155. } else {
  156. err = ctx.Framer().WriteContinuation(w.streamID, endHeaders, frag)
  157. }
  158. if err != nil {
  159. return err
  160. }
  161. }
  162. return nil
  163. }
  164. type write100ContinueHeadersFrame struct {
  165. streamID uint32
  166. }
  167. func (w write100ContinueHeadersFrame) writeFrame(ctx writeContext) error {
  168. enc, buf := ctx.HeaderEncoder()
  169. buf.Reset()
  170. enc.WriteField(hpack.HeaderField{Name: ":status", Value: "100"})
  171. return ctx.Framer().WriteHeaders(HeadersFrameParam{
  172. StreamID: w.streamID,
  173. BlockFragment: buf.Bytes(),
  174. EndStream: false,
  175. EndHeaders: true,
  176. })
  177. }
  178. type writeWindowUpdate struct {
  179. streamID uint32 // or 0 for conn-level
  180. n uint32
  181. }
  182. func (wu writeWindowUpdate) writeFrame(ctx writeContext) error {
  183. return ctx.Framer().WriteWindowUpdate(wu.streamID, wu.n)
  184. }