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.
17 package http2 // import "golang.org/x/net/http2"
32 "golang.org/x/net/lex/httplex"
43 e := os.Getenv("GODEBUG")
44 if strings.Contains(e, "http2debug=1") {
47 if strings.Contains(e, "http2debug=2") {
55 // ClientPreface is the string that must be sent by new
56 // connections from clients.
57 ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
59 // SETTINGS_MAX_FRAME_SIZE default
60 // http://http2.github.io/http2-spec/#rfc.section.6.5.2
61 initialMaxFrameSize = 16384
63 // NextProtoTLS is the NPN/ALPN protocol negotiated during
64 // HTTP/2's TLS setup.
67 // http://http2.github.io/http2-spec/#SettingValues
68 initialHeaderTableSize = 4096
70 initialWindowSize = 65535 // 6.9.2 Initial Flow Control Window Size
72 defaultMaxReadFrameSize = 1 << 20
76 clientPreface = []byte(ClientPreface)
81 // HTTP/2 stream states.
83 // See http://tools.ietf.org/html/rfc7540#section-5.1.
85 // For simplicity, the server code merges "reserved (local)" into
86 // "half-closed (remote)". This is one less state transition to track.
87 // The only downside is that we send PUSH_PROMISEs slightly less
88 // liberally than allowable. More discussion here:
89 // https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
91 // "reserved (remote)" is omitted since the client code does not
92 // support server push.
94 stateIdle streamState = iota
101 var stateName = [...]string{
104 stateHalfClosedLocal: "HalfClosedLocal",
105 stateHalfClosedRemote: "HalfClosedRemote",
106 stateClosed: "Closed",
109 func (st streamState) String() string {
113 // Setting is a setting parameter: which setting it is, and its value.
114 type Setting struct {
115 // ID is which setting is being set.
116 // See http://http2.github.io/http2-spec/#SettingValues
123 func (s Setting) String() string {
124 return fmt.Sprintf("[%v = %d]", s.ID, s.Val)
127 // Valid reports whether the setting is valid.
128 func (s Setting) Valid() error {
129 // Limits and error codes from 6.5.2 Defined SETTINGS Parameters
131 case SettingEnablePush:
132 if s.Val != 1 && s.Val != 0 {
133 return ConnectionError(ErrCodeProtocol)
135 case SettingInitialWindowSize:
137 return ConnectionError(ErrCodeFlowControl)
139 case SettingMaxFrameSize:
140 if s.Val < 16384 || s.Val > 1<<24-1 {
141 return ConnectionError(ErrCodeProtocol)
147 // A SettingID is an HTTP/2 setting as defined in
148 // http://http2.github.io/http2-spec/#iana-settings
149 type SettingID uint16
152 SettingHeaderTableSize SettingID = 0x1
153 SettingEnablePush SettingID = 0x2
154 SettingMaxConcurrentStreams SettingID = 0x3
155 SettingInitialWindowSize SettingID = 0x4
156 SettingMaxFrameSize SettingID = 0x5
157 SettingMaxHeaderListSize SettingID = 0x6
160 var settingName = map[SettingID]string{
161 SettingHeaderTableSize: "HEADER_TABLE_SIZE",
162 SettingEnablePush: "ENABLE_PUSH",
163 SettingMaxConcurrentStreams: "MAX_CONCURRENT_STREAMS",
164 SettingInitialWindowSize: "INITIAL_WINDOW_SIZE",
165 SettingMaxFrameSize: "MAX_FRAME_SIZE",
166 SettingMaxHeaderListSize: "MAX_HEADER_LIST_SIZE",
169 func (s SettingID) String() string {
170 if v, ok := settingName[s]; ok {
173 return fmt.Sprintf("UNKNOWN_SETTING_%d", uint16(s))
177 errInvalidHeaderFieldName = errors.New("http2: invalid header field name")
178 errInvalidHeaderFieldValue = errors.New("http2: invalid header field value")
181 // validWireHeaderFieldName reports whether v is a valid header field
182 // name (key). See httplex.ValidHeaderName for the base rules.
184 // Further, http2 says:
185 // "Just as in HTTP/1.x, header field names are strings of ASCII
186 // characters that are compared in a case-insensitive
187 // fashion. However, header field names MUST be converted to
188 // lowercase prior to their encoding in HTTP/2. "
189 func validWireHeaderFieldName(v string) bool {
193 for _, r := range v {
194 if !httplex.IsTokenRune(r) {
197 if 'A' <= r && r <= 'Z' {
204 var httpCodeStringCommon = map[int]string{} // n -> strconv.Itoa(n)
207 for i := 100; i <= 999; i++ {
208 if v := http.StatusText(i); v != "" {
209 httpCodeStringCommon[i] = strconv.Itoa(i)
214 func httpCodeString(code int) string {
215 if s, ok := httpCodeStringCommon[code]; ok {
218 return strconv.Itoa(code)
222 type stringWriter interface {
223 WriteString(s string) (n int, err error)
226 // A gate lets two goroutines coordinate their activities.
227 type gate chan struct{}
229 func (g gate) Done() { g <- struct{}{} }
230 func (g gate) Wait() { <-g }
232 // A closeWaiter is like a sync.WaitGroup but only goes 1 to 0 (open to closed).
233 type closeWaiter chan struct{}
235 // Init makes a closeWaiter usable.
236 // It exists because so a closeWaiter value can be placed inside a
237 // larger struct and have the Mutex and Cond's memory in the same
239 func (cw *closeWaiter) Init() {
240 *cw = make(chan struct{})
243 // Close marks the closeWaiter as closed and unblocks any waiters.
244 func (cw closeWaiter) Close() {
248 // Wait waits for the closeWaiter to become closed.
249 func (cw closeWaiter) Wait() {
253 // bufferedWriter is a buffered writer that writes to w.
254 // Its buffered writer is lazily allocated as needed, to minimize
255 // idle memory usage with many connections.
256 type bufferedWriter struct {
257 w io.Writer // immutable
258 bw *bufio.Writer // non-nil when data is buffered
261 func newBufferedWriter(w io.Writer) *bufferedWriter {
262 return &bufferedWriter{w: w}
265 // bufWriterPoolBufferSize is the size of bufio.Writer's
266 // buffers created using bufWriterPool.
268 // TODO: pick a less arbitrary value? this is a bit under
269 // (3 x typical 1500 byte MTU) at least. Other than that,
270 // not much thought went into it.
271 const bufWriterPoolBufferSize = 4 << 10
273 var bufWriterPool = sync.Pool{
274 New: func() interface{} {
275 return bufio.NewWriterSize(nil, bufWriterPoolBufferSize)
279 func (w *bufferedWriter) Available() int {
281 return bufWriterPoolBufferSize
283 return w.bw.Available()
286 func (w *bufferedWriter) Write(p []byte) (n int, err error) {
288 bw := bufWriterPool.Get().(*bufio.Writer)
295 func (w *bufferedWriter) Flush() error {
302 bufWriterPool.Put(bw)
307 func mustUint31(v int32) uint32 {
308 if v < 0 || v > 2147483647 {
309 panic("out of range")
314 // bodyAllowedForStatus reports whether a given response status code
315 // permits a body. See RFC 2616, section 4.4.
316 func bodyAllowedForStatus(status int) bool {
318 case status >= 100 && status <= 199:
328 type httpError struct {
333 func (e *httpError) Error() string { return e.msg }
334 func (e *httpError) Timeout() bool { return e.timeout }
335 func (e *httpError) Temporary() bool { return true }
337 var errTimeout error = &httpError{msg: "http2: timeout awaiting response headers", timeout: true}
339 type connectionStater interface {
340 ConnectionState() tls.ConnectionState
343 var sorterPool = sync.Pool{New: func() interface{} { return new(sorter) }}
346 v []string // owned by sorter
349 func (s *sorter) Len() int { return len(s.v) }
350 func (s *sorter) Swap(i, j int) { s.v[i], s.v[j] = s.v[j], s.v[i] }
351 func (s *sorter) Less(i, j int) bool { return s.v[i] < s.v[j] }
353 // Keys returns the sorted keys of h.
355 // The returned slice is only valid until s used again or returned to
357 func (s *sorter) Keys(h http.Header) []string {
360 keys = append(keys, k)
367 func (s *sorter) SortStrings(ss []string) {
368 // Our sorter works on s.v, which sorter owns, so
369 // stash it away while we sort the user's buffer.
376 // validPseudoPath reports whether v is a valid :path pseudo-header
377 // value. It must be either:
379 // *) a non-empty string starting with '/'
380 // *) the string '*', for OPTIONS requests.
382 // For now this is only used a quick check for deciding when to clean
383 // up Opaque URLs before sending requests from the Transport.
384 // See golang.org/issue/16847
386 // We used to enforce that the path also didn't start with "//", but
387 // Google's GFE accepts such paths and Chrome sends them, so ignore
388 // that part of the spec. See golang.org/issue/19103.
389 func validPseudoPath(v string) bool {
390 return (len(v) > 0 && v[0] == '/') || v == "*"