http2.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. "fmt"
  19. "io"
  20. "net/http"
  21. "os"
  22. "strconv"
  23. "strings"
  24. "sync"
  25. )
  26. var VerboseLogs = strings.Contains(os.Getenv("GODEBUG"), "h2debug=1")
  27. const (
  28. // ClientPreface is the string that must be sent by new
  29. // connections from clients.
  30. ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
  31. // SETTINGS_MAX_FRAME_SIZE default
  32. // http://http2.github.io/http2-spec/#rfc.section.6.5.2
  33. initialMaxFrameSize = 16384
  34. // NextProtoTLS is the NPN/ALPN protocol negotiated during
  35. // HTTP/2's TLS setup.
  36. NextProtoTLS = "h2"
  37. // http://http2.github.io/http2-spec/#SettingValues
  38. initialHeaderTableSize = 4096
  39. initialWindowSize = 65535 // 6.9.2 Initial Flow Control Window Size
  40. defaultMaxReadFrameSize = 1 << 20
  41. )
  42. var (
  43. clientPreface = []byte(ClientPreface)
  44. )
  45. type streamState int
  46. const (
  47. stateIdle streamState = iota
  48. stateOpen
  49. stateHalfClosedLocal
  50. stateHalfClosedRemote
  51. stateResvLocal
  52. stateResvRemote
  53. stateClosed
  54. )
  55. var stateName = [...]string{
  56. stateIdle: "Idle",
  57. stateOpen: "Open",
  58. stateHalfClosedLocal: "HalfClosedLocal",
  59. stateHalfClosedRemote: "HalfClosedRemote",
  60. stateResvLocal: "ResvLocal",
  61. stateResvRemote: "ResvRemote",
  62. stateClosed: "Closed",
  63. }
  64. func (st streamState) String() string {
  65. return stateName[st]
  66. }
  67. // Setting is a setting parameter: which setting it is, and its value.
  68. type Setting struct {
  69. // ID is which setting is being set.
  70. // See http://http2.github.io/http2-spec/#SettingValues
  71. ID SettingID
  72. // Val is the value.
  73. Val uint32
  74. }
  75. func (s Setting) String() string {
  76. return fmt.Sprintf("[%v = %d]", s.ID, s.Val)
  77. }
  78. // Valid reports whether the setting is valid.
  79. func (s Setting) Valid() error {
  80. // Limits and error codes from 6.5.2 Defined SETTINGS Parameters
  81. switch s.ID {
  82. case SettingEnablePush:
  83. if s.Val != 1 && s.Val != 0 {
  84. return ConnectionError(ErrCodeProtocol)
  85. }
  86. case SettingInitialWindowSize:
  87. if s.Val > 1<<31-1 {
  88. return ConnectionError(ErrCodeFlowControl)
  89. }
  90. case SettingMaxFrameSize:
  91. if s.Val < 16384 || s.Val > 1<<24-1 {
  92. return ConnectionError(ErrCodeProtocol)
  93. }
  94. }
  95. return nil
  96. }
  97. // A SettingID is an HTTP/2 setting as defined in
  98. // http://http2.github.io/http2-spec/#iana-settings
  99. type SettingID uint16
  100. const (
  101. SettingHeaderTableSize SettingID = 0x1
  102. SettingEnablePush SettingID = 0x2
  103. SettingMaxConcurrentStreams SettingID = 0x3
  104. SettingInitialWindowSize SettingID = 0x4
  105. SettingMaxFrameSize SettingID = 0x5
  106. SettingMaxHeaderListSize SettingID = 0x6
  107. )
  108. var settingName = map[SettingID]string{
  109. SettingHeaderTableSize: "HEADER_TABLE_SIZE",
  110. SettingEnablePush: "ENABLE_PUSH",
  111. SettingMaxConcurrentStreams: "MAX_CONCURRENT_STREAMS",
  112. SettingInitialWindowSize: "INITIAL_WINDOW_SIZE",
  113. SettingMaxFrameSize: "MAX_FRAME_SIZE",
  114. SettingMaxHeaderListSize: "MAX_HEADER_LIST_SIZE",
  115. }
  116. func (s SettingID) String() string {
  117. if v, ok := settingName[s]; ok {
  118. return v
  119. }
  120. return fmt.Sprintf("UNKNOWN_SETTING_%d", uint16(s))
  121. }
  122. func validHeader(v string) bool {
  123. if len(v) == 0 {
  124. return false
  125. }
  126. for _, r := range v {
  127. // "Just as in HTTP/1.x, header field names are
  128. // strings of ASCII characters that are compared in a
  129. // case-insensitive fashion. However, header field
  130. // names MUST be converted to lowercase prior to their
  131. // encoding in HTTP/2. "
  132. if r >= 127 || ('A' <= r && r <= 'Z') {
  133. return false
  134. }
  135. }
  136. return true
  137. }
  138. var httpCodeStringCommon = map[int]string{} // n -> strconv.Itoa(n)
  139. func init() {
  140. for i := 100; i <= 999; i++ {
  141. if v := http.StatusText(i); v != "" {
  142. httpCodeStringCommon[i] = strconv.Itoa(i)
  143. }
  144. }
  145. }
  146. func httpCodeString(code int) string {
  147. if s, ok := httpCodeStringCommon[code]; ok {
  148. return s
  149. }
  150. return strconv.Itoa(code)
  151. }
  152. // from pkg io
  153. type stringWriter interface {
  154. WriteString(s string) (n int, err error)
  155. }
  156. // A gate lets two goroutines coordinate their activities.
  157. type gate chan struct{}
  158. func (g gate) Done() { g <- struct{}{} }
  159. func (g gate) Wait() { <-g }
  160. // A closeWaiter is like a sync.WaitGroup but only goes 1 to 0 (open to closed).
  161. type closeWaiter chan struct{}
  162. // Init makes a closeWaiter usable.
  163. // It exists because so a closeWaiter value can be placed inside a
  164. // larger struct and have the Mutex and Cond's memory in the same
  165. // allocation.
  166. func (cw *closeWaiter) Init() {
  167. *cw = make(chan struct{})
  168. }
  169. // Close marks the closeWaiter as closed and unblocks any waiters.
  170. func (cw closeWaiter) Close() {
  171. close(cw)
  172. }
  173. // Wait waits for the closeWaiter to become closed.
  174. func (cw closeWaiter) Wait() {
  175. <-cw
  176. }
  177. // bufferedWriter is a buffered writer that writes to w.
  178. // Its buffered writer is lazily allocated as needed, to minimize
  179. // idle memory usage with many connections.
  180. type bufferedWriter struct {
  181. w io.Writer // immutable
  182. bw *bufio.Writer // non-nil when data is buffered
  183. }
  184. func newBufferedWriter(w io.Writer) *bufferedWriter {
  185. return &bufferedWriter{w: w}
  186. }
  187. var bufWriterPool = sync.Pool{
  188. New: func() interface{} {
  189. // TODO: pick something better? this is a bit under
  190. // (3 x typical 1500 byte MTU) at least.
  191. return bufio.NewWriterSize(nil, 4<<10)
  192. },
  193. }
  194. func (w *bufferedWriter) Write(p []byte) (n int, err error) {
  195. if w.bw == nil {
  196. bw := bufWriterPool.Get().(*bufio.Writer)
  197. bw.Reset(w.w)
  198. w.bw = bw
  199. }
  200. return w.bw.Write(p)
  201. }
  202. func (w *bufferedWriter) Flush() error {
  203. bw := w.bw
  204. if bw == nil {
  205. return nil
  206. }
  207. err := bw.Flush()
  208. bw.Reset(nil)
  209. bufWriterPool.Put(bw)
  210. w.bw = nil
  211. return err
  212. }
  213. func mustUint31(v int32) uint32 {
  214. if v < 0 || v > 2147483647 {
  215. panic("out of range")
  216. }
  217. return uint32(v)
  218. }
  219. // bodyAllowedForStatus reports whether a given response status code
  220. // permits a body. See RFC2616, section 4.4.
  221. func bodyAllowedForStatus(status int) bool {
  222. switch {
  223. case status >= 100 && status <= 199:
  224. return false
  225. case status == 204:
  226. return false
  227. case status == 304:
  228. return false
  229. }
  230. return true
  231. }