write.go 6.6 KB

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