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.
14 "golang.org/x/net/http/httpguts"
15 "golang.org/x/net/http2/hpack"
18 // writeFramer is implemented by any type that is used to write frames.
19 type writeFramer interface {
20 writeFrame(writeContext) error
22 // staysWithinBuffer reports whether this writer promises that
23 // it will only write less than or equal to size bytes, and it
24 // won't Flush the write context.
25 staysWithinBuffer(size int) bool
28 // writeContext is the interface needed by the various frame writer
29 // types below. All the writeFrame methods below are scheduled via the
30 // frame writing scheduler (see writeScheduler in writesched.go).
32 // This interface is implemented by *serverConn.
34 // TODO: decide whether to a) use this in the client code (which didn't
35 // end up using this yet, because it has a simpler design, not
36 // currently implementing priorities), or b) delete this and
37 // make the server code a bit more concrete.
38 type writeContext interface {
42 // HeaderEncoder returns an HPACK encoder that writes to the
44 HeaderEncoder() (*hpack.Encoder, *bytes.Buffer)
47 // writeEndsStream reports whether w writes a frame that will transition
48 // the stream to a half-closed local state. This returns false for RST_STREAM,
49 // which closes the entire stream (not just the local half).
50 func writeEndsStream(w writeFramer) bool {
51 switch v := w.(type) {
54 case *writeResHeaders:
57 // This can only happen if the caller reuses w after it's
58 // been intentionally nil'ed out to prevent use. Keep this
59 // here to catch future refactoring breaking it.
60 panic("writeEndsStream called on nil writeFramer")
65 type flushFrameWriter struct{}
67 func (flushFrameWriter) writeFrame(ctx writeContext) error {
71 func (flushFrameWriter) staysWithinBuffer(max int) bool { return false }
73 type writeSettings []Setting
75 func (s writeSettings) staysWithinBuffer(max int) bool {
76 const settingSize = 6 // uint16 + uint32
77 return frameHeaderLen+settingSize*len(s) <= max
81 func (s writeSettings) writeFrame(ctx writeContext) error {
82 return ctx.Framer().WriteSettings([]Setting(s)...)
85 type writeGoAway struct {
90 func (p *writeGoAway) writeFrame(ctx writeContext) error {
91 err := ctx.Framer().WriteGoAway(p.maxStreamID, p.code, nil)
92 ctx.Flush() // ignore error: we're hanging up on them anyway
96 func (*writeGoAway) staysWithinBuffer(max int) bool { return false } // flushes
98 type writeData struct {
104 func (w *writeData) String() string {
105 return fmt.Sprintf("writeData(stream=%d, p=%d, endStream=%v)", w.streamID, len(w.p), w.endStream)
108 func (w *writeData) writeFrame(ctx writeContext) error {
109 return ctx.Framer().WriteData(w.streamID, w.endStream, w.p)
112 func (w *writeData) staysWithinBuffer(max int) bool {
113 return frameHeaderLen+len(w.p) <= max
116 // handlerPanicRST is the message sent from handler goroutines when
117 // the handler panics.
118 type handlerPanicRST struct {
122 func (hp handlerPanicRST) writeFrame(ctx writeContext) error {
123 return ctx.Framer().WriteRSTStream(hp.StreamID, ErrCodeInternal)
126 func (hp handlerPanicRST) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max }
128 func (se StreamError) writeFrame(ctx writeContext) error {
129 return ctx.Framer().WriteRSTStream(se.StreamID, se.Code)
132 func (se StreamError) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max }
134 type writePingAck struct{ pf *PingFrame }
136 func (w writePingAck) writeFrame(ctx writeContext) error {
137 return ctx.Framer().WritePing(true, w.pf.Data)
140 func (w writePingAck) staysWithinBuffer(max int) bool { return frameHeaderLen+len(w.pf.Data) <= max }
142 type writeSettingsAck struct{}
144 func (writeSettingsAck) writeFrame(ctx writeContext) error {
145 return ctx.Framer().WriteSettingsAck()
148 func (writeSettingsAck) staysWithinBuffer(max int) bool { return frameHeaderLen <= max }
150 // splitHeaderBlock splits headerBlock into fragments so that each fragment fits
151 // in a single frame, then calls fn for each fragment. firstFrag/lastFrag are true
152 // for the first/last fragment, respectively.
153 func splitHeaderBlock(ctx writeContext, headerBlock []byte, fn func(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error) error {
154 // For now we're lazy and just pick the minimum MAX_FRAME_SIZE
155 // that all peers must support (16KB). Later we could care
156 // more and send larger frames if the peer advertised it, but
157 // there's little point. Most headers are small anyway (so we
158 // generally won't have CONTINUATION frames), and extra frames
159 // only waste 9 bytes anyway.
160 const maxFrameSize = 16384
163 for len(headerBlock) > 0 {
165 if len(frag) > maxFrameSize {
166 frag = frag[:maxFrameSize]
168 headerBlock = headerBlock[len(frag):]
169 if err := fn(ctx, frag, first, len(headerBlock) == 0); err != nil {
177 // writeResHeaders is a request to write a HEADERS and 0+ CONTINUATION frames
178 // for HTTP response headers or trailers from a server handler.
179 type writeResHeaders struct {
181 httpResCode int // 0 means no ":status" line
182 h http.Header // may be nil
183 trailers []string // if non-nil, which keys of h to write. nil means all.
191 func encKV(enc *hpack.Encoder, k, v string) {
193 log.Printf("http2: server encoding header %q = %q", k, v)
195 enc.WriteField(hpack.HeaderField{Name: k, Value: v})
198 func (w *writeResHeaders) staysWithinBuffer(max int) bool {
199 // TODO: this is a common one. It'd be nice to return true
200 // here and get into the fast path if we could be clever and
201 // calculate the size fast enough, or at least a conservative
202 // upper bound that usually fires. (Maybe if w.h and
203 // w.trailers are nil, so we don't need to enumerate it.)
204 // Otherwise I'm afraid that just calculating the length to
205 // answer this question would be slower than the ~2µs benefit.
209 func (w *writeResHeaders) writeFrame(ctx writeContext) error {
210 enc, buf := ctx.HeaderEncoder()
213 if w.httpResCode != 0 {
214 encKV(enc, ":status", httpCodeString(w.httpResCode))
217 encodeHeaders(enc, w.h, w.trailers)
219 if w.contentType != "" {
220 encKV(enc, "content-type", w.contentType)
222 if w.contentLength != "" {
223 encKV(enc, "content-length", w.contentLength)
226 encKV(enc, "date", w.date)
229 headerBlock := buf.Bytes()
230 if len(headerBlock) == 0 && w.trailers == nil {
231 panic("unexpected empty hpack")
234 return splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock)
237 func (w *writeResHeaders) writeHeaderBlock(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error {
239 return ctx.Framer().WriteHeaders(HeadersFrameParam{
240 StreamID: w.streamID,
242 EndStream: w.endStream,
243 EndHeaders: lastFrag,
246 return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag)
250 // writePushPromise is a request to write a PUSH_PROMISE and 0+ CONTINUATION frames.
251 type writePushPromise struct {
252 streamID uint32 // pusher stream
253 method string // for :method
254 url *url.URL // for :scheme, :authority, :path
257 // Creates an ID for a pushed stream. This runs on serveG just before
258 // the frame is written. The returned ID is copied to promisedID.
259 allocatePromisedID func() (uint32, error)
263 func (w *writePushPromise) staysWithinBuffer(max int) bool {
264 // TODO: see writeResHeaders.staysWithinBuffer
268 func (w *writePushPromise) writeFrame(ctx writeContext) error {
269 enc, buf := ctx.HeaderEncoder()
272 encKV(enc, ":method", w.method)
273 encKV(enc, ":scheme", w.url.Scheme)
274 encKV(enc, ":authority", w.url.Host)
275 encKV(enc, ":path", w.url.RequestURI())
276 encodeHeaders(enc, w.h, nil)
278 headerBlock := buf.Bytes()
279 if len(headerBlock) == 0 {
280 panic("unexpected empty hpack")
283 return splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock)
286 func (w *writePushPromise) writeHeaderBlock(ctx writeContext, frag []byte, firstFrag, lastFrag bool) error {
288 return ctx.Framer().WritePushPromise(PushPromiseParam{
289 StreamID: w.streamID,
290 PromiseID: w.promisedID,
292 EndHeaders: lastFrag,
295 return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag)
299 type write100ContinueHeadersFrame struct {
303 func (w write100ContinueHeadersFrame) writeFrame(ctx writeContext) error {
304 enc, buf := ctx.HeaderEncoder()
306 encKV(enc, ":status", "100")
307 return ctx.Framer().WriteHeaders(HeadersFrameParam{
308 StreamID: w.streamID,
309 BlockFragment: buf.Bytes(),
315 func (w write100ContinueHeadersFrame) staysWithinBuffer(max int) bool {
316 // Sloppy but conservative:
317 return 9+2*(len(":status")+len("100")) <= max
320 type writeWindowUpdate struct {
321 streamID uint32 // or 0 for conn-level
325 func (wu writeWindowUpdate) staysWithinBuffer(max int) bool { return frameHeaderLen+4 <= max }
327 func (wu writeWindowUpdate) writeFrame(ctx writeContext) error {
328 return ctx.Framer().WriteWindowUpdate(wu.streamID, wu.n)
331 // encodeHeaders encodes an http.Header. If keys is not nil, then (k, h[k])
332 // is encoded only if k is in keys.
333 func encodeHeaders(enc *hpack.Encoder, h http.Header, keys []string) {
335 sorter := sorterPool.Get().(*sorter)
336 // Using defer here, since the returned keys from the
337 // sorter.Keys method is only valid until the sorter
339 defer sorterPool.Put(sorter)
340 keys = sorter.Keys(h)
342 for _, k := range keys {
345 if !validWireHeaderFieldName(k) {
346 // Skip it as backup paranoia. Per
347 // golang.org/issue/14048, these should
348 // already be rejected at a higher level.
351 isTE := k == "transfer-encoding"
352 for _, v := range vv {
353 if !httpguts.ValidHeaderFieldValue(v) {
354 // TODO: return an error? golang.org/issue/14048
355 // For now just omit it.
358 // TODO: more of "8.1.2.2 Connection-Specific Header Fields"
359 if isTE && v != "trailers" {