http2.go 6.4 KB

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