http2.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. }