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.
 
 
 

385 lines
9.5 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/http/httpguts"
  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 httpguts.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 !httpguts.IsTokenRune(r) {
  169. return false
  170. }
  171. if 'A' <= r && r <= 'Z' {
  172. return false
  173. }
  174. }
  175. return true
  176. }
  177. func httpCodeString(code int) string {
  178. switch code {
  179. case 200:
  180. return "200"
  181. case 404:
  182. return "404"
  183. }
  184. return strconv.Itoa(code)
  185. }
  186. // from pkg io
  187. type stringWriter interface {
  188. WriteString(s string) (n int, err error)
  189. }
  190. // A gate lets two goroutines coordinate their activities.
  191. type gate chan struct{}
  192. func (g gate) Done() { g <- struct{}{} }
  193. func (g gate) Wait() { <-g }
  194. // A closeWaiter is like a sync.WaitGroup but only goes 1 to 0 (open to closed).
  195. type closeWaiter chan struct{}
  196. // Init makes a closeWaiter usable.
  197. // It exists because so a closeWaiter value can be placed inside a
  198. // larger struct and have the Mutex and Cond's memory in the same
  199. // allocation.
  200. func (cw *closeWaiter) Init() {
  201. *cw = make(chan struct{})
  202. }
  203. // Close marks the closeWaiter as closed and unblocks any waiters.
  204. func (cw closeWaiter) Close() {
  205. close(cw)
  206. }
  207. // Wait waits for the closeWaiter to become closed.
  208. func (cw closeWaiter) Wait() {
  209. <-cw
  210. }
  211. // bufferedWriter is a buffered writer that writes to w.
  212. // Its buffered writer is lazily allocated as needed, to minimize
  213. // idle memory usage with many connections.
  214. type bufferedWriter struct {
  215. w io.Writer // immutable
  216. bw *bufio.Writer // non-nil when data is buffered
  217. }
  218. func newBufferedWriter(w io.Writer) *bufferedWriter {
  219. return &bufferedWriter{w: w}
  220. }
  221. // bufWriterPoolBufferSize is the size of bufio.Writer's
  222. // buffers created using bufWriterPool.
  223. //
  224. // TODO: pick a less arbitrary value? this is a bit under
  225. // (3 x typical 1500 byte MTU) at least. Other than that,
  226. // not much thought went into it.
  227. const bufWriterPoolBufferSize = 4 << 10
  228. var bufWriterPool = sync.Pool{
  229. New: func() interface{} {
  230. return bufio.NewWriterSize(nil, bufWriterPoolBufferSize)
  231. },
  232. }
  233. func (w *bufferedWriter) Available() int {
  234. if w.bw == nil {
  235. return bufWriterPoolBufferSize
  236. }
  237. return w.bw.Available()
  238. }
  239. func (w *bufferedWriter) Write(p []byte) (n int, err error) {
  240. if w.bw == nil {
  241. bw := bufWriterPool.Get().(*bufio.Writer)
  242. bw.Reset(w.w)
  243. w.bw = bw
  244. }
  245. return w.bw.Write(p)
  246. }
  247. func (w *bufferedWriter) Flush() error {
  248. bw := w.bw
  249. if bw == nil {
  250. return nil
  251. }
  252. err := bw.Flush()
  253. bw.Reset(nil)
  254. bufWriterPool.Put(bw)
  255. w.bw = nil
  256. return err
  257. }
  258. func mustUint31(v int32) uint32 {
  259. if v < 0 || v > 2147483647 {
  260. panic("out of range")
  261. }
  262. return uint32(v)
  263. }
  264. // bodyAllowedForStatus reports whether a given response status code
  265. // permits a body. See RFC 7230, section 3.3.
  266. func bodyAllowedForStatus(status int) bool {
  267. switch {
  268. case status >= 100 && status <= 199:
  269. return false
  270. case status == 204:
  271. return false
  272. case status == 304:
  273. return false
  274. }
  275. return true
  276. }
  277. type httpError struct {
  278. msg string
  279. timeout bool
  280. }
  281. func (e *httpError) Error() string { return e.msg }
  282. func (e *httpError) Timeout() bool { return e.timeout }
  283. func (e *httpError) Temporary() bool { return true }
  284. var errTimeout error = &httpError{msg: "http2: timeout awaiting response headers", timeout: true}
  285. type connectionStater interface {
  286. ConnectionState() tls.ConnectionState
  287. }
  288. var sorterPool = sync.Pool{New: func() interface{} { return new(sorter) }}
  289. type sorter struct {
  290. v []string // owned by sorter
  291. }
  292. func (s *sorter) Len() int { return len(s.v) }
  293. func (s *sorter) Swap(i, j int) { s.v[i], s.v[j] = s.v[j], s.v[i] }
  294. func (s *sorter) Less(i, j int) bool { return s.v[i] < s.v[j] }
  295. // Keys returns the sorted keys of h.
  296. //
  297. // The returned slice is only valid until s used again or returned to
  298. // its pool.
  299. func (s *sorter) Keys(h http.Header) []string {
  300. keys := s.v[:0]
  301. for k := range h {
  302. keys = append(keys, k)
  303. }
  304. s.v = keys
  305. sort.Sort(s)
  306. return keys
  307. }
  308. func (s *sorter) SortStrings(ss []string) {
  309. // Our sorter works on s.v, which sorter owns, so
  310. // stash it away while we sort the user's buffer.
  311. save := s.v
  312. s.v = ss
  313. sort.Sort(s)
  314. s.v = save
  315. }
  316. // validPseudoPath reports whether v is a valid :path pseudo-header
  317. // value. It must be either:
  318. //
  319. // *) a non-empty string starting with '/'
  320. // *) the string '*', for OPTIONS requests.
  321. //
  322. // For now this is only used a quick check for deciding when to clean
  323. // up Opaque URLs before sending requests from the Transport.
  324. // See golang.org/issue/16847
  325. //
  326. // We used to enforce that the path also didn't start with "//", but
  327. // Google's GFE accepts such paths and Chrome sends them, so ignore
  328. // that part of the spec. See golang.org/issue/19103.
  329. func validPseudoPath(v string) bool {
  330. return (len(v) > 0 && v[0] == '/') || v == "*"
  331. }