http2.go 6.1 KB

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