http2.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. const (
  68. stateIdle streamState = iota
  69. stateOpen
  70. stateHalfClosedLocal
  71. stateHalfClosedRemote
  72. stateResvLocal
  73. stateResvRemote
  74. stateClosed
  75. )
  76. var stateName = [...]string{
  77. stateIdle: "Idle",
  78. stateOpen: "Open",
  79. stateHalfClosedLocal: "HalfClosedLocal",
  80. stateHalfClosedRemote: "HalfClosedRemote",
  81. stateResvLocal: "ResvLocal",
  82. stateResvRemote: "ResvRemote",
  83. stateClosed: "Closed",
  84. }
  85. func (st streamState) String() string {
  86. return stateName[st]
  87. }
  88. // Setting is a setting parameter: which setting it is, and its value.
  89. type Setting struct {
  90. // ID is which setting is being set.
  91. // See http://http2.github.io/http2-spec/#SettingValues
  92. ID SettingID
  93. // Val is the value.
  94. Val uint32
  95. }
  96. func (s Setting) String() string {
  97. return fmt.Sprintf("[%v = %d]", s.ID, s.Val)
  98. }
  99. // Valid reports whether the setting is valid.
  100. func (s Setting) Valid() error {
  101. // Limits and error codes from 6.5.2 Defined SETTINGS Parameters
  102. switch s.ID {
  103. case SettingEnablePush:
  104. if s.Val != 1 && s.Val != 0 {
  105. return ConnectionError(ErrCodeProtocol)
  106. }
  107. case SettingInitialWindowSize:
  108. if s.Val > 1<<31-1 {
  109. return ConnectionError(ErrCodeFlowControl)
  110. }
  111. case SettingMaxFrameSize:
  112. if s.Val < 16384 || s.Val > 1<<24-1 {
  113. return ConnectionError(ErrCodeProtocol)
  114. }
  115. }
  116. return nil
  117. }
  118. // A SettingID is an HTTP/2 setting as defined in
  119. // http://http2.github.io/http2-spec/#iana-settings
  120. type SettingID uint16
  121. const (
  122. SettingHeaderTableSize SettingID = 0x1
  123. SettingEnablePush SettingID = 0x2
  124. SettingMaxConcurrentStreams SettingID = 0x3
  125. SettingInitialWindowSize SettingID = 0x4
  126. SettingMaxFrameSize SettingID = 0x5
  127. SettingMaxHeaderListSize SettingID = 0x6
  128. )
  129. var settingName = map[SettingID]string{
  130. SettingHeaderTableSize: "HEADER_TABLE_SIZE",
  131. SettingEnablePush: "ENABLE_PUSH",
  132. SettingMaxConcurrentStreams: "MAX_CONCURRENT_STREAMS",
  133. SettingInitialWindowSize: "INITIAL_WINDOW_SIZE",
  134. SettingMaxFrameSize: "MAX_FRAME_SIZE",
  135. SettingMaxHeaderListSize: "MAX_HEADER_LIST_SIZE",
  136. }
  137. func (s SettingID) String() string {
  138. if v, ok := settingName[s]; ok {
  139. return v
  140. }
  141. return fmt.Sprintf("UNKNOWN_SETTING_%d", uint16(s))
  142. }
  143. var (
  144. errInvalidHeaderFieldName = errors.New("http2: invalid header field name")
  145. errInvalidHeaderFieldValue = errors.New("http2: invalid header field value")
  146. )
  147. // validWireHeaderFieldName reports whether v is a valid header field
  148. // name (key). See httplex.ValidHeaderName for the base rules.
  149. //
  150. // Further, http2 says:
  151. // "Just as in HTTP/1.x, header field names are strings of ASCII
  152. // characters that are compared in a case-insensitive
  153. // fashion. However, header field names MUST be converted to
  154. // lowercase prior to their encoding in HTTP/2. "
  155. func validWireHeaderFieldName(v string) bool {
  156. if len(v) == 0 {
  157. return false
  158. }
  159. for _, r := range v {
  160. if !httplex.IsTokenRune(r) {
  161. return false
  162. }
  163. if 'A' <= r && r <= 'Z' {
  164. return false
  165. }
  166. }
  167. return true
  168. }
  169. var httpCodeStringCommon = map[int]string{} // n -> strconv.Itoa(n)
  170. func init() {
  171. for i := 100; i <= 999; i++ {
  172. if v := http.StatusText(i); v != "" {
  173. httpCodeStringCommon[i] = strconv.Itoa(i)
  174. }
  175. }
  176. }
  177. func httpCodeString(code int) string {
  178. if s, ok := httpCodeStringCommon[code]; ok {
  179. return s
  180. }
  181. return strconv.Itoa(code)
  182. }
  183. // from pkg io
  184. type stringWriter interface {
  185. WriteString(s string) (n int, err error)
  186. }
  187. // A gate lets two goroutines coordinate their activities.
  188. type gate chan struct{}
  189. func (g gate) Done() { g <- struct{}{} }
  190. func (g gate) Wait() { <-g }
  191. // A closeWaiter is like a sync.WaitGroup but only goes 1 to 0 (open to closed).
  192. type closeWaiter chan struct{}
  193. // Init makes a closeWaiter usable.
  194. // It exists because so a closeWaiter value can be placed inside a
  195. // larger struct and have the Mutex and Cond's memory in the same
  196. // allocation.
  197. func (cw *closeWaiter) Init() {
  198. *cw = make(chan struct{})
  199. }
  200. // Close marks the closeWaiter as closed and unblocks any waiters.
  201. func (cw closeWaiter) Close() {
  202. close(cw)
  203. }
  204. // Wait waits for the closeWaiter to become closed.
  205. func (cw closeWaiter) Wait() {
  206. <-cw
  207. }
  208. // bufferedWriter is a buffered writer that writes to w.
  209. // Its buffered writer is lazily allocated as needed, to minimize
  210. // idle memory usage with many connections.
  211. type bufferedWriter struct {
  212. w io.Writer // immutable
  213. bw *bufio.Writer // non-nil when data is buffered
  214. }
  215. func newBufferedWriter(w io.Writer) *bufferedWriter {
  216. return &bufferedWriter{w: w}
  217. }
  218. // bufWriterPoolBufferSize is the size of bufio.Writer's
  219. // buffers created using bufWriterPool.
  220. //
  221. // TODO: pick a less arbitrary value? this is a bit under
  222. // (3 x typical 1500 byte MTU) at least. Other than that,
  223. // not much thought went into it.
  224. const bufWriterPoolBufferSize = 4 << 10
  225. var bufWriterPool = sync.Pool{
  226. New: func() interface{} {
  227. return bufio.NewWriterSize(nil, bufWriterPoolBufferSize)
  228. },
  229. }
  230. func (w *bufferedWriter) Available() int {
  231. if w.bw == nil {
  232. return bufWriterPoolBufferSize
  233. }
  234. return w.bw.Available()
  235. }
  236. func (w *bufferedWriter) Write(p []byte) (n int, err error) {
  237. if w.bw == nil {
  238. bw := bufWriterPool.Get().(*bufio.Writer)
  239. bw.Reset(w.w)
  240. w.bw = bw
  241. }
  242. return w.bw.Write(p)
  243. }
  244. func (w *bufferedWriter) Flush() error {
  245. bw := w.bw
  246. if bw == nil {
  247. return nil
  248. }
  249. err := bw.Flush()
  250. bw.Reset(nil)
  251. bufWriterPool.Put(bw)
  252. w.bw = nil
  253. return err
  254. }
  255. func mustUint31(v int32) uint32 {
  256. if v < 0 || v > 2147483647 {
  257. panic("out of range")
  258. }
  259. return uint32(v)
  260. }
  261. // bodyAllowedForStatus reports whether a given response status code
  262. // permits a body. See RFC 2616, section 4.4.
  263. func bodyAllowedForStatus(status int) bool {
  264. switch {
  265. case status >= 100 && status <= 199:
  266. return false
  267. case status == 204:
  268. return false
  269. case status == 304:
  270. return false
  271. }
  272. return true
  273. }
  274. type httpError struct {
  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 '/', but not with 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. func validPseudoPath(v string) bool {
  323. return (len(v) > 0 && v[0] == '/' && (len(v) == 1 || v[1] != '/')) || v == "*"
  324. }