write.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. "golang.org/x/net/lex/httplex"
  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. // endsStream reports whether the given frame writer w will locally
  41. // close the stream.
  42. func endsStream(w writeFramer) bool {
  43. switch v := w.(type) {
  44. case *writeData:
  45. return v.endStream
  46. case *writeResHeaders:
  47. return v.endStream
  48. case nil:
  49. // This can only happen if the caller reuses w after it's
  50. // been intentionally nil'ed out to prevent use. Keep this
  51. // here to catch future refactoring breaking it.
  52. panic("endsStream called on nil writeFramer")
  53. }
  54. return false
  55. }
  56. type flushFrameWriter struct{}
  57. func (flushFrameWriter) writeFrame(ctx writeContext) error {
  58. return ctx.Flush()
  59. }
  60. func (flushFrameWriter) staysWithinBuffer(max int) bool { return false }
  61. type writeSettings []Setting
  62. func (s writeSettings) staysWithinBuffer(max int) bool {
  63. const settingSize = 6 // uint16 + uint32
  64. return frameHeaderLen+settingSize*len(s) <= max
  65. }
  66. func (s writeSettings) writeFrame(ctx writeContext) error {
  67. return ctx.Framer().WriteSettings([]Setting(s)...)
  68. }
  69. type writeGoAway struct {
  70. maxStreamID uint32
  71. code ErrCode
  72. }
  73. func (p *writeGoAway) writeFrame(ctx writeContext) error {
  74. err := ctx.Framer().WriteGoAway(p.maxStreamID, p.code, nil)
  75. if p.code != 0 {
  76. ctx.Flush() // ignore error: we're hanging up on them anyway
  77. time.Sleep(50 * time.Millisecond)
  78. ctx.CloseConn()
  79. }
  80. return err
  81. }
  82. func (*writeGoAway) staysWithinBuffer(max int) bool { return false } // flushes
  83. type writeData struct {
  84. streamID uint32
  85. p []byte
  86. endStream bool
  87. }
  88. func (w *writeData) String() string {
  89. return fmt.Sprintf("writeData(stream=%d, p=%d, endStream=%v)", w.streamID, len(w.p), w.endStream)
  90. }
  91. func (w *writeData) writeFrame(ctx writeContext) error {
  92. return ctx.Framer().WriteData(w.streamID, w.endStream, w.p)
  93. }
  94. func (w *writeData) staysWithinBuffer(max int) bool {
  95. return frameHeaderLen+len(w.p) <= max
  96. }
  97. // handlerPanicRST is the message sent from handler goroutines when
  98. // the handler panics.
  99. type handlerPanicRST struct {
  100. StreamID uint32
  101. }
  102. func (hp handlerPanicRST) writeFrame(ctx writeContext) error {
  103. return ctx.Framer().WriteRSTStream(hp.StreamID, ErrCodeInternal)
  104. }
  105. func (hp handlerPanicRST) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max }
  106. func (se StreamError) writeFrame(ctx writeContext) error {
  107. return ctx.Framer().WriteRSTStream(se.StreamID, se.Code)
  108. }
  109. func (se StreamError) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max }
  110. type writePingAck struct{ pf *PingFrame }
  111. func (w writePingAck) writeFrame(ctx writeContext) error {
  112. return ctx.Framer().WritePing(true, w.pf.Data)
  113. }
  114. func (w writePingAck) staysWithinBuffer(max int) bool { return frameHeaderLen+len(w.pf.Data) <= max }
  115. type writeSettingsAck struct{}
  116. func (writeSettingsAck) writeFrame(ctx writeContext) error {
  117. return ctx.Framer().WriteSettingsAck()
  118. }
  119. func (writeSettingsAck) staysWithinBuffer(max int) bool { return frameHeaderLen <= max }
  120. // writeResHeaders is a request to write a HEADERS and 0+ CONTINUATION frames
  121. // for HTTP response headers or trailers from a server handler.
  122. type writeResHeaders struct {
  123. streamID uint32
  124. httpResCode int // 0 means no ":status" line
  125. h http.Header // may be nil
  126. trailers []string // if non-nil, which keys of h to write. nil means all.
  127. endStream bool
  128. date string
  129. contentType string
  130. contentLength string
  131. }
  132. func encKV(enc *hpack.Encoder, k, v string) {
  133. if VerboseLogs {
  134. log.Printf("http2: server encoding header %q = %q", k, v)
  135. }
  136. enc.WriteField(hpack.HeaderField{Name: k, Value: v})
  137. }
  138. func (w *writeResHeaders) staysWithinBuffer(max int) bool {
  139. // TODO: this is a common one. It'd be nice to return true
  140. // here and get into the fast path if we could be clever and
  141. // calculate the size fast enough, or at least a conservative
  142. // uppper bound that usually fires. (Maybe if w.h and
  143. // w.trailers are nil, so we don't need to enumerate it.)
  144. // Otherwise I'm afraid that just calculating the length to
  145. // answer this question would be slower than the ~2µs benefit.
  146. return false
  147. }
  148. func (w *writeResHeaders) writeFrame(ctx writeContext) error {
  149. enc, buf := ctx.HeaderEncoder()
  150. buf.Reset()
  151. if w.httpResCode != 0 {
  152. encKV(enc, ":status", httpCodeString(w.httpResCode))
  153. }
  154. encodeHeaders(enc, w.h, w.trailers)
  155. if w.contentType != "" {
  156. encKV(enc, "content-type", w.contentType)
  157. }
  158. if w.contentLength != "" {
  159. encKV(enc, "content-length", w.contentLength)
  160. }
  161. if w.date != "" {
  162. encKV(enc, "date", w.date)
  163. }
  164. headerBlock := buf.Bytes()
  165. if len(headerBlock) == 0 && w.trailers == nil {
  166. panic("unexpected empty hpack")
  167. }
  168. // For now we're lazy and just pick the minimum MAX_FRAME_SIZE
  169. // that all peers must support (16KB). Later we could care
  170. // more and send larger frames if the peer advertised it, but
  171. // there's little point. Most headers are small anyway (so we
  172. // generally won't have CONTINUATION frames), and extra frames
  173. // only waste 9 bytes anyway.
  174. const maxFrameSize = 16384
  175. first := true
  176. for len(headerBlock) > 0 {
  177. frag := headerBlock
  178. if len(frag) > maxFrameSize {
  179. frag = frag[:maxFrameSize]
  180. }
  181. headerBlock = headerBlock[len(frag):]
  182. endHeaders := len(headerBlock) == 0
  183. var err error
  184. if first {
  185. first = false
  186. err = ctx.Framer().WriteHeaders(HeadersFrameParam{
  187. StreamID: w.streamID,
  188. BlockFragment: frag,
  189. EndStream: w.endStream,
  190. EndHeaders: endHeaders,
  191. })
  192. } else {
  193. err = ctx.Framer().WriteContinuation(w.streamID, endHeaders, frag)
  194. }
  195. if err != nil {
  196. return err
  197. }
  198. }
  199. return nil
  200. }
  201. type write100ContinueHeadersFrame struct {
  202. streamID uint32
  203. }
  204. func (w write100ContinueHeadersFrame) writeFrame(ctx writeContext) error {
  205. enc, buf := ctx.HeaderEncoder()
  206. buf.Reset()
  207. encKV(enc, ":status", "100")
  208. return ctx.Framer().WriteHeaders(HeadersFrameParam{
  209. StreamID: w.streamID,
  210. BlockFragment: buf.Bytes(),
  211. EndStream: false,
  212. EndHeaders: true,
  213. })
  214. }
  215. func (w write100ContinueHeadersFrame) staysWithinBuffer(max int) bool {
  216. // Sloppy but conservative:
  217. return 9+2*(len(":status")+len("100")) <= max
  218. }
  219. type writeWindowUpdate struct {
  220. streamID uint32 // or 0 for conn-level
  221. n uint32
  222. }
  223. func (wu writeWindowUpdate) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max }
  224. func (wu writeWindowUpdate) writeFrame(ctx writeContext) error {
  225. return ctx.Framer().WriteWindowUpdate(wu.streamID, wu.n)
  226. }
  227. func encodeHeaders(enc *hpack.Encoder, h http.Header, keys []string) {
  228. if keys == nil {
  229. sorter := sorterPool.Get().(*sorter)
  230. // Using defer here, since the returned keys from the
  231. // sorter.Keys method is only valid until the sorter
  232. // is returned:
  233. defer sorterPool.Put(sorter)
  234. keys = sorter.Keys(h)
  235. }
  236. for _, k := range keys {
  237. vv := h[k]
  238. k = lowerHeader(k)
  239. if !validWireHeaderFieldName(k) {
  240. // Skip it as backup paranoia. Per
  241. // golang.org/issue/14048, these should
  242. // already be rejected at a higher level.
  243. continue
  244. }
  245. isTE := k == "transfer-encoding"
  246. for _, v := range vv {
  247. if !httplex.ValidHeaderFieldValue(v) {
  248. // TODO: return an error? golang.org/issue/14048
  249. // For now just omit it.
  250. continue
  251. }
  252. // TODO: more of "8.1.2.2 Connection-Specific Header Fields"
  253. if isTE && v != "trailers" {
  254. continue
  255. }
  256. encKV(enc, k, v)
  257. }
  258. }
  259. }