You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

391 lines
9.7 KiB

  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 implements the HTTP/2 protocol.
  5. //
  6. // This package is low-level and intended to be used directly by very
  7. // few people. Most users will use it indirectly through the automatic
  8. // use by the net/http package (from Go 1.6 and later).
  9. // For use in earlier Go versions see ConfigureServer. (Transport support
  10. // requires Go 1.6 or later)
  11. //
  12. // See https://http2.github.io/ for more information on HTTP/2.
  13. //
  14. // See https://http2.golang.org/ for a test server running this code.
  15. //
  16. package http2 // import "golang.org/x/net/http2"
  17. import (
  18. "bufio"
  19. "crypto/tls"
  20. "errors"
  21. "fmt"
  22. "io"
  23. "net/http"
  24. "os"
  25. "sort"
  26. "strconv"
  27. "strings"
  28. "sync"
  29. "golang.org/x/net/lex/httplex"
  30. )
  31. var (
  32. VerboseLogs bool
  33. logFrameWrites bool
  34. logFrameReads bool
  35. inTests bool
  36. )
  37. func init() {
  38. e := os.Getenv("GODEBUG")
  39. if strings.Contains(e, "http2debug=1") {
  40. VerboseLogs = true
  41. }
  42. if strings.Contains(e, "http2debug=2") {
  43. VerboseLogs = true
  44. logFrameWrites = true
  45. logFrameReads = true
  46. }
  47. }
  48. const (
  49. // ClientPreface is the string that must be sent by new
  50. // connections from clients.
  51. ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
  52. // SETTINGS_MAX_FRAME_SIZE default
  53. // http://http2.github.io/http2-spec/#rfc.section.6.5.2
  54. initialMaxFrameSize = 16384
  55. // NextProtoTLS is the NPN/ALPN protocol negotiated during
  56. // HTTP/2's TLS setup.
  57. NextProtoTLS = "h2"
  58. // http://http2.github.io/http2-spec/#SettingValues
  59. initialHeaderTableSize = 4096
  60. initialWindowSize = 65535 // 6.9.2 Initial Flow Control Window Size
  61. defaultMaxReadFrameSize = 1 << 20
  62. )
  63. var (
  64. clientPreface = []byte(ClientPreface)
  65. )
  66. type streamState int
  67. // HTTP/2 stream states.
  68. //
  69. // See http://tools.ietf.org/html/rfc7540#section-5.1.
  70. //
  71. // For simplicity, the server code merges "reserved (local)" into
  72. // "half-closed (remote)". This is one less state transition to track.
  73. // The only downside is that we send PUSH_PROMISEs slightly less
  74. // liberally than allowable. More discussion here:
  75. // https://lists.w3.org/Archives/Public/ietf-http-wg/2016JulSep/0599.html
  76. //
  77. // "reserved (remote)" is omitted since the client code does not
  78. // support server push.
  79. const (
  80. stateIdle streamState = iota
  81. stateOpen
  82. stateHalfClosedLocal
  83. stateHalfClosedRemote
  84. stateClosed
  85. )
  86. var stateName = [...]string{
  87. stateIdle: "Idle",
  88. stateOpen: "Open",
  89. stateHalfClosedLocal: "HalfClosedLocal",
  90. stateHalfClosedRemote: "HalfClosedRemote",
  91. stateClosed: "Closed",
  92. }
  93. func (st streamState) String() string {
  94. return stateName[st]
  95. }
  96. // Setting is a setting parameter: which setting it is, and its value.
  97. type Setting struct {
  98. // ID is which setting is being set.
  99. // See http://http2.github.io/http2-spec/#SettingValues
  100. ID SettingID
  101. // Val is the value.
  102. Val uint32
  103. }
  104. func (s Setting) String() string {
  105. return fmt.Sprintf("[%v = %d]", s.ID, s.Val)
  106. }
  107. // Valid reports whether the setting is valid.
  108. func (s Setting) Valid() error {
  109. // Limits and error codes from 6.5.2 Defined SETTINGS Parameters
  110. switch s.ID {
  111. case SettingEnablePush:
  112. if s.Val != 1 && s.Val != 0 {
  113. return ConnectionError(ErrCodeProtocol)
  114. }
  115. case SettingInitialWindowSize:
  116. if s.Val > 1<<31-1 {
  117. return ConnectionError(ErrCodeFlowControl)
  118. }
  119. case SettingMaxFrameSize:
  120. if s.Val < 16384 || s.Val > 1<<24-1 {
  121. return ConnectionError(ErrCodeProtocol)
  122. }
  123. }
  124. return nil
  125. }
  126. // A SettingID is an HTTP/2 setting as defined in
  127. // http://http2.github.io/http2-spec/#iana-settings
  128. type SettingID uint16
  129. const (
  130. SettingHeaderTableSize SettingID = 0x1
  131. SettingEnablePush SettingID = 0x2
  132. SettingMaxConcurrentStreams SettingID = 0x3
  133. SettingInitialWindowSize SettingID = 0x4
  134. SettingMaxFrameSize SettingID = 0x5
  135. SettingMaxHeaderListSize SettingID = 0x6
  136. )
  137. var settingName = map[SettingID]string{
  138. SettingHeaderTableSize: "HEADER_TABLE_SIZE",
  139. SettingEnablePush: "ENABLE_PUSH",
  140. SettingMaxConcurrentStreams: "MAX_CONCURRENT_STREAMS",
  141. SettingInitialWindowSize: "INITIAL_WINDOW_SIZE",
  142. SettingMaxFrameSize: "MAX_FRAME_SIZE",
  143. SettingMaxHeaderListSize: "MAX_HEADER_LIST_SIZE",
  144. }
  145. func (s SettingID) String() string {
  146. if v, ok := settingName[s]; ok {
  147. return v
  148. }
  149. return fmt.Sprintf("UNKNOWN_SETTING_%d", uint16(s))
  150. }
  151. var (
  152. errInvalidHeaderFieldName = errors.New("http2: invalid header field name")
  153. errInvalidHeaderFieldValue = errors.New("http2: invalid header field value")
  154. )
  155. // validWireHeaderFieldName reports whether v is a valid header field
  156. // name (key). See httplex.ValidHeaderName for the base rules.
  157. //
  158. // Further, http2 says:
  159. // "Just as in HTTP/1.x, header field names are strings of ASCII
  160. // characters that are compared in a case-insensitive
  161. // fashion. However, header field names MUST be converted to
  162. // lowercase prior to their encoding in HTTP/2. "
  163. func validWireHeaderFieldName(v string) bool {
  164. if len(v) == 0 {
  165. return false
  166. }
  167. for _, r := range v {
  168. if !httplex.IsTokenRune(r) {
  169. return false
  170. }
  171. if 'A' <= r && r <= 'Z' {
  172. return false
  173. }
  174. }
  175. return true
  176. }
  177. var httpCodeStringCommon = map[int]string{} // n -> strconv.Itoa(n)
  178. func init() {
  179. for i := 100; i <= 999; i++ {
  180. if v := http.StatusText(i); v != "" {
  181. httpCodeStringCommon[i] = strconv.Itoa(i)
  182. }
  183. }
  184. }
  185. func httpCodeString(code int) string {
  186. if s, ok := httpCodeStringCommon[code]; ok {
  187. return s
  188. }
  189. return strconv.Itoa(code)
  190. }
  191. // from pkg io
  192. type stringWriter interface {
  193. WriteString(s string) (n int, err error)
  194. }
  195. // A gate lets two goroutines coordinate their activities.
  196. type gate chan struct{}
  197. func (g gate) Done() { g <- struct{}{} }
  198. func (g gate) Wait() { <-g }
  199. // A closeWaiter is like a sync.WaitGroup but only goes 1 to 0 (open to closed).
  200. type closeWaiter chan struct{}
  201. // Init makes a closeWaiter usable.
  202. // It exists because so a closeWaiter value can be placed inside a
  203. // larger struct and have the Mutex and Cond's memory in the same
  204. // allocation.
  205. func (cw *closeWaiter) Init() {
  206. *cw = make(chan struct{})
  207. }
  208. // Close marks the closeWaiter as closed and unblocks any waiters.
  209. func (cw closeWaiter) Close() {
  210. close(cw)
  211. }
  212. // Wait waits for the closeWaiter to become closed.
  213. func (cw closeWaiter) Wait() {
  214. <-cw
  215. }
  216. // bufferedWriter is a buffered writer that writes to w.
  217. // Its buffered writer is lazily allocated as needed, to minimize
  218. // idle memory usage with many connections.
  219. type bufferedWriter struct {
  220. w io.Writer // immutable
  221. bw *bufio.Writer // non-nil when data is buffered
  222. }
  223. func newBufferedWriter(w io.Writer) *bufferedWriter {
  224. return &bufferedWriter{w: w}
  225. }
  226. // bufWriterPoolBufferSize is the size of bufio.Writer's
  227. // buffers created using bufWriterPool.
  228. //
  229. // TODO: pick a less arbitrary value? this is a bit under
  230. // (3 x typical 1500 byte MTU) at least. Other than that,
  231. // not much thought went into it.
  232. const bufWriterPoolBufferSize = 4 << 10
  233. var bufWriterPool = sync.Pool{
  234. New: func() interface{} {
  235. return bufio.NewWriterSize(nil, bufWriterPoolBufferSize)
  236. },
  237. }
  238. func (w *bufferedWriter) Available() int {
  239. if w.bw == nil {
  240. return bufWriterPoolBufferSize
  241. }
  242. return w.bw.Available()
  243. }
  244. func (w *bufferedWriter) Write(p []byte) (n int, err error) {
  245. if w.bw == nil {
  246. bw := bufWriterPool.Get().(*bufio.Writer)
  247. bw.Reset(w.w)
  248. w.bw = bw
  249. }
  250. return w.bw.Write(p)
  251. }
  252. func (w *bufferedWriter) Flush() error {
  253. bw := w.bw
  254. if bw == nil {
  255. return nil
  256. }
  257. err := bw.Flush()
  258. bw.Reset(nil)
  259. bufWriterPool.Put(bw)
  260. w.bw = nil
  261. return err
  262. }
  263. func mustUint31(v int32) uint32 {
  264. if v < 0 || v > 2147483647 {
  265. panic("out of range")
  266. }
  267. return uint32(v)
  268. }
  269. // bodyAllowedForStatus reports whether a given response status code
  270. // permits a body. See RFC 2616, section 4.4.
  271. func bodyAllowedForStatus(status int) bool {
  272. switch {
  273. case status >= 100 && status <= 199:
  274. return false
  275. case status == 204:
  276. return false
  277. case status == 304:
  278. return false
  279. }
  280. return true
  281. }
  282. type httpError struct {
  283. msg string
  284. timeout bool
  285. }
  286. func (e *httpError) Error() string { return e.msg }
  287. func (e *httpError) Timeout() bool { return e.timeout }
  288. func (e *httpError) Temporary() bool { return true }
  289. var errTimeout error = &httpError{msg: "http2: timeout awaiting response headers", timeout: true}
  290. type connectionStater interface {
  291. ConnectionState() tls.ConnectionState
  292. }
  293. var sorterPool = sync.Pool{New: func() interface{} { return new(sorter) }}
  294. type sorter struct {
  295. v []string // owned by sorter
  296. }
  297. func (s *sorter) Len() int { return len(s.v) }
  298. func (s *sorter) Swap(i, j int) { s.v[i], s.v[j] = s.v[j], s.v[i] }
  299. func (s *sorter) Less(i, j int) bool { return s.v[i] < s.v[j] }
  300. // Keys returns the sorted keys of h.
  301. //
  302. // The returned slice is only valid until s used again or returned to
  303. // its pool.
  304. func (s *sorter) Keys(h http.Header) []string {
  305. keys := s.v[:0]
  306. for k := range h {
  307. keys = append(keys, k)
  308. }
  309. s.v = keys
  310. sort.Sort(s)
  311. return keys
  312. }
  313. func (s *sorter) SortStrings(ss []string) {
  314. // Our sorter works on s.v, which sorter owns, so
  315. // stash it away while we sort the user's buffer.
  316. save := s.v
  317. s.v = ss
  318. sort.Sort(s)
  319. s.v = save
  320. }
  321. // validPseudoPath reports whether v is a valid :path pseudo-header
  322. // value. It must be either:
  323. //
  324. // *) a non-empty string starting with '/'
  325. // *) the string '*', for OPTIONS requests.
  326. //
  327. // For now this is only used a quick check for deciding when to clean
  328. // up Opaque URLs before sending requests from the Transport.
  329. // See golang.org/issue/16847
  330. //
  331. // We used to enforce that the path also didn't start with "//", but
  332. // Google's GFE accepts such paths and Chrome sends them, so ignore
  333. // that part of the spec. See golang.org/issue/19103.
  334. func validPseudoPath(v string) bool {
  335. return (len(v) > 0 && v[0] == '/') || v == "*"
  336. }