http2.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. )
  36. func init() {
  37. e := os.Getenv("GODEBUG")
  38. if strings.Contains(e, "http2debug=1") {
  39. VerboseLogs = true
  40. }
  41. if strings.Contains(e, "http2debug=2") {
  42. VerboseLogs = true
  43. logFrameWrites = true
  44. logFrameReads = true
  45. }
  46. }
  47. const (
  48. // ClientPreface is the string that must be sent by new
  49. // connections from clients.
  50. ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
  51. // SETTINGS_MAX_FRAME_SIZE default
  52. // http://http2.github.io/http2-spec/#rfc.section.6.5.2
  53. initialMaxFrameSize = 16384
  54. // NextProtoTLS is the NPN/ALPN protocol negotiated during
  55. // HTTP/2's TLS setup.
  56. NextProtoTLS = "h2"
  57. // http://http2.github.io/http2-spec/#SettingValues
  58. initialHeaderTableSize = 4096
  59. initialWindowSize = 65535 // 6.9.2 Initial Flow Control Window Size
  60. defaultMaxReadFrameSize = 1 << 20
  61. )
  62. var (
  63. clientPreface = []byte(ClientPreface)
  64. )
  65. type streamState int
  66. const (
  67. stateIdle streamState = iota
  68. stateOpen
  69. stateHalfClosedLocal
  70. stateHalfClosedRemote
  71. stateResvLocal
  72. stateResvRemote
  73. stateClosed
  74. )
  75. var stateName = [...]string{
  76. stateIdle: "Idle",
  77. stateOpen: "Open",
  78. stateHalfClosedLocal: "HalfClosedLocal",
  79. stateHalfClosedRemote: "HalfClosedRemote",
  80. stateResvLocal: "ResvLocal",
  81. stateResvRemote: "ResvRemote",
  82. stateClosed: "Closed",
  83. }
  84. func (st streamState) String() string {
  85. return stateName[st]
  86. }
  87. // Setting is a setting parameter: which setting it is, and its value.
  88. type Setting struct {
  89. // ID is which setting is being set.
  90. // See http://http2.github.io/http2-spec/#SettingValues
  91. ID SettingID
  92. // Val is the value.
  93. Val uint32
  94. }
  95. func (s Setting) String() string {
  96. return fmt.Sprintf("[%v = %d]", s.ID, s.Val)
  97. }
  98. // Valid reports whether the setting is valid.
  99. func (s Setting) Valid() error {
  100. // Limits and error codes from 6.5.2 Defined SETTINGS Parameters
  101. switch s.ID {
  102. case SettingEnablePush:
  103. if s.Val != 1 && s.Val != 0 {
  104. return ConnectionError(ErrCodeProtocol)
  105. }
  106. case SettingInitialWindowSize:
  107. if s.Val > 1<<31-1 {
  108. return ConnectionError(ErrCodeFlowControl)
  109. }
  110. case SettingMaxFrameSize:
  111. if s.Val < 16384 || s.Val > 1<<24-1 {
  112. return ConnectionError(ErrCodeProtocol)
  113. }
  114. }
  115. return nil
  116. }
  117. // A SettingID is an HTTP/2 setting as defined in
  118. // http://http2.github.io/http2-spec/#iana-settings
  119. type SettingID uint16
  120. const (
  121. SettingHeaderTableSize SettingID = 0x1
  122. SettingEnablePush SettingID = 0x2
  123. SettingMaxConcurrentStreams SettingID = 0x3
  124. SettingInitialWindowSize SettingID = 0x4
  125. SettingMaxFrameSize SettingID = 0x5
  126. SettingMaxHeaderListSize SettingID = 0x6
  127. )
  128. var settingName = map[SettingID]string{
  129. SettingHeaderTableSize: "HEADER_TABLE_SIZE",
  130. SettingEnablePush: "ENABLE_PUSH",
  131. SettingMaxConcurrentStreams: "MAX_CONCURRENT_STREAMS",
  132. SettingInitialWindowSize: "INITIAL_WINDOW_SIZE",
  133. SettingMaxFrameSize: "MAX_FRAME_SIZE",
  134. SettingMaxHeaderListSize: "MAX_HEADER_LIST_SIZE",
  135. }
  136. func (s SettingID) String() string {
  137. if v, ok := settingName[s]; ok {
  138. return v
  139. }
  140. return fmt.Sprintf("UNKNOWN_SETTING_%d", uint16(s))
  141. }
  142. var (
  143. errInvalidHeaderFieldName = errors.New("http2: invalid header field name")
  144. errInvalidHeaderFieldValue = errors.New("http2: invalid header field value")
  145. )
  146. // validWireHeaderFieldName reports whether v is a valid header field
  147. // name (key). See httplex.ValidHeaderName for the base rules.
  148. //
  149. // Further, http2 says:
  150. // "Just as in HTTP/1.x, header field names are strings of ASCII
  151. // characters that are compared in a case-insensitive
  152. // fashion. However, header field names MUST be converted to
  153. // lowercase prior to their encoding in HTTP/2. "
  154. func validWireHeaderFieldName(v string) bool {
  155. if len(v) == 0 {
  156. return false
  157. }
  158. for _, r := range v {
  159. if !httplex.IsTokenRune(r) {
  160. return false
  161. }
  162. if 'A' <= r && r <= 'Z' {
  163. return false
  164. }
  165. }
  166. return true
  167. }
  168. var httpCodeStringCommon = map[int]string{} // n -> strconv.Itoa(n)
  169. func init() {
  170. for i := 100; i <= 999; i++ {
  171. if v := http.StatusText(i); v != "" {
  172. httpCodeStringCommon[i] = strconv.Itoa(i)
  173. }
  174. }
  175. }
  176. func httpCodeString(code int) string {
  177. if s, ok := httpCodeStringCommon[code]; ok {
  178. return s
  179. }
  180. return strconv.Itoa(code)
  181. }
  182. // from pkg io
  183. type stringWriter interface {
  184. WriteString(s string) (n int, err error)
  185. }
  186. // A gate lets two goroutines coordinate their activities.
  187. type gate chan struct{}
  188. func (g gate) Done() { g <- struct{}{} }
  189. func (g gate) Wait() { <-g }
  190. // A closeWaiter is like a sync.WaitGroup but only goes 1 to 0 (open to closed).
  191. type closeWaiter chan struct{}
  192. // Init makes a closeWaiter usable.
  193. // It exists because so a closeWaiter value can be placed inside a
  194. // larger struct and have the Mutex and Cond's memory in the same
  195. // allocation.
  196. func (cw *closeWaiter) Init() {
  197. *cw = make(chan struct{})
  198. }
  199. // Close marks the closeWaiter as closed and unblocks any waiters.
  200. func (cw closeWaiter) Close() {
  201. close(cw)
  202. }
  203. // Wait waits for the closeWaiter to become closed.
  204. func (cw closeWaiter) Wait() {
  205. <-cw
  206. }
  207. // bufferedWriter is a buffered writer that writes to w.
  208. // Its buffered writer is lazily allocated as needed, to minimize
  209. // idle memory usage with many connections.
  210. type bufferedWriter struct {
  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. var bufWriterPool = sync.Pool{
  218. New: func() interface{} {
  219. // TODO: pick something better? this is a bit under
  220. // (3 x typical 1500 byte MTU) at least.
  221. return bufio.NewWriterSize(nil, 4<<10)
  222. },
  223. }
  224. func (w *bufferedWriter) Write(p []byte) (n int, err error) {
  225. if w.bw == nil {
  226. bw := bufWriterPool.Get().(*bufio.Writer)
  227. bw.Reset(w.w)
  228. w.bw = bw
  229. }
  230. return w.bw.Write(p)
  231. }
  232. func (w *bufferedWriter) Flush() error {
  233. bw := w.bw
  234. if bw == nil {
  235. return nil
  236. }
  237. err := bw.Flush()
  238. bw.Reset(nil)
  239. bufWriterPool.Put(bw)
  240. w.bw = nil
  241. return err
  242. }
  243. func mustUint31(v int32) uint32 {
  244. if v < 0 || v > 2147483647 {
  245. panic("out of range")
  246. }
  247. return uint32(v)
  248. }
  249. // bodyAllowedForStatus reports whether a given response status code
  250. // permits a body. See RFC 2616, section 4.4.
  251. func bodyAllowedForStatus(status int) bool {
  252. switch {
  253. case status >= 100 && status <= 199:
  254. return false
  255. case status == 204:
  256. return false
  257. case status == 304:
  258. return false
  259. }
  260. return true
  261. }
  262. type httpError struct {
  263. msg string
  264. timeout bool
  265. }
  266. func (e *httpError) Error() string { return e.msg }
  267. func (e *httpError) Timeout() bool { return e.timeout }
  268. func (e *httpError) Temporary() bool { return true }
  269. var errTimeout error = &httpError{msg: "http2: timeout awaiting response headers", timeout: true}
  270. type connectionStater interface {
  271. ConnectionState() tls.ConnectionState
  272. }
  273. var sorterPool = sync.Pool{New: func() interface{} { return new(sorter) }}
  274. type sorter struct {
  275. v []string // owned by sorter
  276. }
  277. func (s *sorter) Len() int { return len(s.v) }
  278. func (s *sorter) Swap(i, j int) { s.v[i], s.v[j] = s.v[j], s.v[i] }
  279. func (s *sorter) Less(i, j int) bool { return s.v[i] < s.v[j] }
  280. // Keys returns the sorted keys of h.
  281. //
  282. // The returned slice is only valid until s used again or returned to
  283. // its pool.
  284. func (s *sorter) Keys(h http.Header) []string {
  285. keys := s.v[:0]
  286. for k := range h {
  287. keys = append(keys, k)
  288. }
  289. s.v = keys
  290. sort.Sort(s)
  291. return keys
  292. }
  293. func (s *sorter) SortStrings(ss []string) {
  294. // Our sorter works on s.v, which sorter owners, so
  295. // stash it away while we sort the user's buffer.
  296. save := s.v
  297. s.v = ss
  298. sort.Sort(s)
  299. s.v = save
  300. }