http2.go 6.6 KB

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