http2.go 9.5 KB

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