http2.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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
  16. import (
  17. "bufio"
  18. "crypto/tls"
  19. "errors"
  20. "fmt"
  21. "io"
  22. "net/http"
  23. "os"
  24. "sort"
  25. "strconv"
  26. "strings"
  27. "sync"
  28. "golang.org/x/net/lex/httplex"
  29. )
  30. var (
  31. VerboseLogs bool
  32. logFrameWrites bool
  33. logFrameReads 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. // http://http2.github.io/http2-spec/#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. // http://http2.github.io/http2-spec/#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. const (
  66. stateIdle streamState = iota
  67. stateOpen
  68. stateHalfClosedLocal
  69. stateHalfClosedRemote
  70. stateResvLocal
  71. stateResvRemote
  72. stateClosed
  73. )
  74. var stateName = [...]string{
  75. stateIdle: "Idle",
  76. stateOpen: "Open",
  77. stateHalfClosedLocal: "HalfClosedLocal",
  78. stateHalfClosedRemote: "HalfClosedRemote",
  79. stateResvLocal: "ResvLocal",
  80. stateResvRemote: "ResvRemote",
  81. stateClosed: "Closed",
  82. }
  83. func (st streamState) String() string {
  84. return stateName[st]
  85. }
  86. // Setting is a setting parameter: which setting it is, and its value.
  87. type Setting struct {
  88. // ID is which setting is being set.
  89. // See http://http2.github.io/http2-spec/#SettingValues
  90. ID SettingID
  91. // Val is the value.
  92. Val uint32
  93. }
  94. func (s Setting) String() string {
  95. return fmt.Sprintf("[%v = %d]", s.ID, s.Val)
  96. }
  97. // Valid reports whether the setting is valid.
  98. func (s Setting) Valid() error {
  99. // Limits and error codes from 6.5.2 Defined SETTINGS Parameters
  100. switch s.ID {
  101. case SettingEnablePush:
  102. if s.Val != 1 && s.Val != 0 {
  103. return ConnectionError(ErrCodeProtocol)
  104. }
  105. case SettingInitialWindowSize:
  106. if s.Val > 1<<31-1 {
  107. return ConnectionError(ErrCodeFlowControl)
  108. }
  109. case SettingMaxFrameSize:
  110. if s.Val < 16384 || s.Val > 1<<24-1 {
  111. return ConnectionError(ErrCodeProtocol)
  112. }
  113. }
  114. return nil
  115. }
  116. // A SettingID is an HTTP/2 setting as defined in
  117. // http://http2.github.io/http2-spec/#iana-settings
  118. type SettingID uint16
  119. const (
  120. SettingHeaderTableSize SettingID = 0x1
  121. SettingEnablePush SettingID = 0x2
  122. SettingMaxConcurrentStreams SettingID = 0x3
  123. SettingInitialWindowSize SettingID = 0x4
  124. SettingMaxFrameSize SettingID = 0x5
  125. SettingMaxHeaderListSize SettingID = 0x6
  126. )
  127. var settingName = map[SettingID]string{
  128. SettingHeaderTableSize: "HEADER_TABLE_SIZE",
  129. SettingEnablePush: "ENABLE_PUSH",
  130. SettingMaxConcurrentStreams: "MAX_CONCURRENT_STREAMS",
  131. SettingInitialWindowSize: "INITIAL_WINDOW_SIZE",
  132. SettingMaxFrameSize: "MAX_FRAME_SIZE",
  133. SettingMaxHeaderListSize: "MAX_HEADER_LIST_SIZE",
  134. }
  135. func (s SettingID) String() string {
  136. if v, ok := settingName[s]; ok {
  137. return v
  138. }
  139. return fmt.Sprintf("UNKNOWN_SETTING_%d", uint16(s))
  140. }
  141. var (
  142. errInvalidHeaderFieldName = errors.New("http2: invalid header field name")
  143. errInvalidHeaderFieldValue = errors.New("http2: invalid header field value")
  144. )
  145. // validWireHeaderFieldName reports whether v is a valid header field
  146. // name (key). See httplex.ValidHeaderName for the base rules.
  147. //
  148. // Further, http2 says:
  149. // "Just as in HTTP/1.x, header field names are strings of ASCII
  150. // characters that are compared in a case-insensitive
  151. // fashion. However, header field names MUST be converted to
  152. // lowercase prior to their encoding in HTTP/2. "
  153. func validWireHeaderFieldName(v string) bool {
  154. if len(v) == 0 {
  155. return false
  156. }
  157. for _, r := range v {
  158. if !httplex.IsTokenRune(r) {
  159. return false
  160. }
  161. if 'A' <= r && r <= 'Z' {
  162. return false
  163. }
  164. }
  165. return true
  166. }
  167. var httpCodeStringCommon = map[int]string{} // n -> strconv.Itoa(n)
  168. func init() {
  169. for i := 100; i <= 999; i++ {
  170. if v := http.StatusText(i); v != "" {
  171. httpCodeStringCommon[i] = strconv.Itoa(i)
  172. }
  173. }
  174. }
  175. func httpCodeString(code int) string {
  176. if s, ok := httpCodeStringCommon[code]; ok {
  177. return s
  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. w io.Writer // immutable
  211. bw *bufio.Writer // non-nil when data is buffered
  212. }
  213. func newBufferedWriter(w io.Writer) *bufferedWriter {
  214. return &bufferedWriter{w: w}
  215. }
  216. var bufWriterPool = sync.Pool{
  217. New: func() interface{} {
  218. // TODO: pick something better? this is a bit under
  219. // (3 x typical 1500 byte MTU) at least.
  220. return bufio.NewWriterSize(nil, 4<<10)
  221. },
  222. }
  223. func (w *bufferedWriter) Write(p []byte) (n int, err error) {
  224. if w.bw == nil {
  225. bw := bufWriterPool.Get().(*bufio.Writer)
  226. bw.Reset(w.w)
  227. w.bw = bw
  228. }
  229. return w.bw.Write(p)
  230. }
  231. func (w *bufferedWriter) Flush() error {
  232. bw := w.bw
  233. if bw == nil {
  234. return nil
  235. }
  236. err := bw.Flush()
  237. bw.Reset(nil)
  238. bufWriterPool.Put(bw)
  239. w.bw = nil
  240. return err
  241. }
  242. func mustUint31(v int32) uint32 {
  243. if v < 0 || v > 2147483647 {
  244. panic("out of range")
  245. }
  246. return uint32(v)
  247. }
  248. // bodyAllowedForStatus reports whether a given response status code
  249. // permits a body. See RFC 2616, section 4.4.
  250. func bodyAllowedForStatus(status int) bool {
  251. switch {
  252. case status >= 100 && status <= 199:
  253. return false
  254. case status == 204:
  255. return false
  256. case status == 304:
  257. return false
  258. }
  259. return true
  260. }
  261. type httpError struct {
  262. msg string
  263. timeout bool
  264. }
  265. func (e *httpError) Error() string { return e.msg }
  266. func (e *httpError) Timeout() bool { return e.timeout }
  267. func (e *httpError) Temporary() bool { return true }
  268. var errTimeout error = &httpError{msg: "http2: timeout awaiting response headers", timeout: true}
  269. type connectionStater interface {
  270. ConnectionState() tls.ConnectionState
  271. }
  272. var sorterPool = sync.Pool{New: func() interface{} { return new(sorter) }}
  273. type sorter struct {
  274. v []string // owned by sorter
  275. }
  276. func (s *sorter) Len() int { return len(s.v) }
  277. func (s *sorter) Swap(i, j int) { s.v[i], s.v[j] = s.v[j], s.v[i] }
  278. func (s *sorter) Less(i, j int) bool { return s.v[i] < s.v[j] }
  279. // Keys returns the sorted keys of h.
  280. //
  281. // The returned slice is only valid until s used again or returned to
  282. // its pool.
  283. func (s *sorter) Keys(h http.Header) []string {
  284. keys := s.v[:0]
  285. for k := range h {
  286. keys = append(keys, k)
  287. }
  288. s.v = keys
  289. sort.Sort(s)
  290. return keys
  291. }
  292. func (s *sorter) SortStrings(ss []string) {
  293. // Our sorter works on s.v, which sorter owners, so
  294. // stash it away while we sort the user's buffer.
  295. save := s.v
  296. s.v = ss
  297. sort.Sort(s)
  298. s.v = save
  299. }