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