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.
5
// Package http2 implements the HTTP/2 protocol.
7
// This package is low-level and intended to be used directly by very
8
// few people. Most users will use it indirectly through the automatic
9
// use by the net/http package (from Go 1.6 and later).
10
// For use in earlier Go versions see ConfigureServer. (Transport support
11
// requires Go 1.6 or later)
13
// See https://http2.github.io/ for more information on HTTP/2.
15
// See https://http2.golang.org/ for a test server running this code.
16
package http2 // import "golang.org/x/net/http2"
30
"golang.org/x/net/http/httpguts"
41
e := os.Getenv("GODEBUG")
42
if strings.Contains(e, "http2debug=1") {
45
if strings.Contains(e, "http2debug=2") {
53
// ClientPreface is the string that must be sent by new
54
// connections from clients.
55
ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
57
// SETTINGS_MAX_FRAME_SIZE default
58
// https://httpwg.org/specs/rfc7540.html#rfc.section.6.5.2
59
initialMaxFrameSize = 16384
61
// NextProtoTLS is the NPN/ALPN protocol negotiated during
62
// HTTP/2's TLS setup.
65
// https://httpwg.org/specs/rfc7540.html#SettingValues
66
initialHeaderTableSize = 4096
68
initialWindowSize = 65535 // 6.9.2 Initial Flow Control Window Size
70
defaultMaxReadFrameSize = 1 << 20
74
clientPreface = []byte(ClientPreface)
79
// HTTP/2 stream states.
81
// See http://tools.ietf.org/html/rfc7540#section-5.1.
83
// For simplicity, the server code merges "reserved (local)" into
84
// "half-closed (remote)". This is one less state transition to track.
85
// The only downside is that we send PUSH_PROMISEs slightly less
86
// liberally than allowable. More discussion here:
87
// https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
89
// "reserved (remote)" is omitted since the client code does not
90
// support server push.
92
stateIdle streamState = iota
99
var stateName = [...]string{
102
stateHalfClosedLocal: "HalfClosedLocal",
103
stateHalfClosedRemote: "HalfClosedRemote",
104
stateClosed: "Closed",
107
func (st streamState) String() string {
111
// Setting is a setting parameter: which setting it is, and its value.
113
// ID is which setting is being set.
114
// See https://httpwg.org/specs/rfc7540.html#SettingFormat
121
func (s Setting) String() string {
122
return fmt.Sprintf("[%v = %d]", s.ID, s.Val)
125
// Valid reports whether the setting is valid.
126
func (s Setting) Valid() error {
127
// Limits and error codes from 6.5.2 Defined SETTINGS Parameters
129
case SettingEnablePush:
130
if s.Val != 1 && s.Val != 0 {
131
return ConnectionError(ErrCodeProtocol)
133
case SettingInitialWindowSize:
135
return ConnectionError(ErrCodeFlowControl)
137
case SettingMaxFrameSize:
138
if s.Val < 16384 || s.Val > 1<<24-1 {
139
return ConnectionError(ErrCodeProtocol)
145
// A SettingID is an HTTP/2 setting as defined in
146
// https://httpwg.org/specs/rfc7540.html#iana-settings
150
SettingHeaderTableSize SettingID = 0x1
151
SettingEnablePush SettingID = 0x2
152
SettingMaxConcurrentStreams SettingID = 0x3
153
SettingInitialWindowSize SettingID = 0x4
154
SettingMaxFrameSize SettingID = 0x5
155
SettingMaxHeaderListSize SettingID = 0x6
158
var settingName = map[SettingID]string{
159
SettingHeaderTableSize: "HEADER_TABLE_SIZE",
160
SettingEnablePush: "ENABLE_PUSH",
161
SettingMaxConcurrentStreams: "MAX_CONCURRENT_STREAMS",
162
SettingInitialWindowSize: "INITIAL_WINDOW_SIZE",
163
SettingMaxFrameSize: "MAX_FRAME_SIZE",
164
SettingMaxHeaderListSize: "MAX_HEADER_LIST_SIZE",
167
func (s SettingID) String() string {
168
if v, ok := settingName[s]; ok {
171
return fmt.Sprintf("UNKNOWN_SETTING_%d", uint16(s))
174
// validWireHeaderFieldName reports whether v is a valid header field
175
// name (key). See httpguts.ValidHeaderName for the base rules.
177
// Further, http2 says:
179
// "Just as in HTTP/1.x, header field names are strings of ASCII
180
// characters that are compared in a case-insensitive
181
// fashion. However, header field names MUST be converted to
182
// lowercase prior to their encoding in HTTP/2. "
183
func validWireHeaderFieldName(v string) bool {
187
for _, r := range v {
188
if !httpguts.IsTokenRune(r) {
191
if 'A' <= r && r <= 'Z' {
198
func httpCodeString(code int) string {
205
return strconv.Itoa(code)
209
type stringWriter interface {
210
WriteString(s string) (n int, err error)
213
// A gate lets two goroutines coordinate their activities.
214
type gate chan struct{}
216
func (g gate) Done() { g <- struct{}{} }
217
func (g gate) Wait() { <-g }
219
// A closeWaiter is like a sync.WaitGroup but only goes 1 to 0 (open to closed).
220
type closeWaiter chan struct{}
222
// Init makes a closeWaiter usable.
223
// It exists because so a closeWaiter value can be placed inside a
224
// larger struct and have the Mutex and Cond's memory in the same
226
func (cw *closeWaiter) Init() {
227
*cw = make(chan struct{})
230
// Close marks the closeWaiter as closed and unblocks any waiters.
231
func (cw closeWaiter) Close() {
235
// Wait waits for the closeWaiter to become closed.
236
func (cw closeWaiter) Wait() {
240
// bufferedWriter is a buffered writer that writes to w.
241
// Its buffered writer is lazily allocated as needed, to minimize
242
// idle memory usage with many connections.
243
type bufferedWriter struct {
245
w io.Writer // immutable
246
bw *bufio.Writer // non-nil when data is buffered
249
func newBufferedWriter(w io.Writer) *bufferedWriter {
250
return &bufferedWriter{w: w}
253
// bufWriterPoolBufferSize is the size of bufio.Writer's
254
// buffers created using bufWriterPool.
256
// TODO: pick a less arbitrary value? this is a bit under
257
// (3 x typical 1500 byte MTU) at least. Other than that,
258
// not much thought went into it.
259
const bufWriterPoolBufferSize = 4 << 10
261
var bufWriterPool = sync.Pool{
262
New: func() interface{} {
263
return bufio.NewWriterSize(nil, bufWriterPoolBufferSize)
267
func (w *bufferedWriter) Available() int {
269
return bufWriterPoolBufferSize
271
return w.bw.Available()
274
func (w *bufferedWriter) Write(p []byte) (n int, err error) {
276
bw := bufWriterPool.Get().(*bufio.Writer)
283
func (w *bufferedWriter) Flush() error {
290
bufWriterPool.Put(bw)
295
func mustUint31(v int32) uint32 {
296
if v < 0 || v > 2147483647 {
297
panic("out of range")
302
// bodyAllowedForStatus reports whether a given response status code
303
// permits a body. See RFC 7230, section 3.3.
304
func bodyAllowedForStatus(status int) bool {
306
case status >= 100 && status <= 199:
316
type httpError struct {
322
func (e *httpError) Error() string { return e.msg }
323
func (e *httpError) Timeout() bool { return e.timeout }
324
func (e *httpError) Temporary() bool { return true }
326
var errTimeout error = &httpError{msg: "http2: timeout awaiting response headers", timeout: true}
328
type connectionStater interface {
329
ConnectionState() tls.ConnectionState
332
var sorterPool = sync.Pool{New: func() interface{} { return new(sorter) }}
335
v []string // owned by sorter
338
func (s *sorter) Len() int { return len(s.v) }
339
func (s *sorter) Swap(i, j int) { s.v[i], s.v[j] = s.v[j], s.v[i] }
340
func (s *sorter) Less(i, j int) bool { return s.v[i] < s.v[j] }
342
// Keys returns the sorted keys of h.
344
// The returned slice is only valid until s used again or returned to
346
func (s *sorter) Keys(h http.Header) []string {
349
keys = append(keys, k)
356
func (s *sorter) SortStrings(ss []string) {
357
// Our sorter works on s.v, which sorter owns, so
358
// stash it away while we sort the user's buffer.
365
// validPseudoPath reports whether v is a valid :path pseudo-header
366
// value. It must be either:
368
// - a non-empty string starting with '/'
369
// - the string '*', for OPTIONS requests.
371
// For now this is only used a quick check for deciding when to clean
372
// up Opaque URLs before sending requests from the Transport.
373
// See golang.org/issue/16847
375
// We used to enforce that the path also didn't start with "//", but
376
// Google's GFE accepts such paths and Chrome sends them, so ignore
377
// that part of the spec. See golang.org/issue/19103.
378
func validPseudoPath(v string) bool {
379
return (len(v) > 0 && v[0] == '/') || v == "*"
382
// incomparable is a zero-width, non-comparable type. Adding it to a struct
383
// makes that struct also non-comparable, and generally doesn't add
384
// any size (as long as it's first).
385
type incomparable [0]func()