http2.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. "errors"
  19. "fmt"
  20. "io"
  21. "net/http"
  22. "os"
  23. "strconv"
  24. "strings"
  25. "sync"
  26. )
  27. var (
  28. VerboseLogs bool
  29. logFrameWrites bool
  30. logFrameReads bool
  31. )
  32. func init() {
  33. e := os.Getenv("GODEBUG")
  34. if strings.Contains(e, "http2debug=1") {
  35. VerboseLogs = true
  36. }
  37. if strings.Contains(e, "http2debug=2") {
  38. VerboseLogs = true
  39. logFrameWrites = true
  40. logFrameReads = true
  41. }
  42. }
  43. const (
  44. // ClientPreface is the string that must be sent by new
  45. // connections from clients.
  46. ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
  47. // SETTINGS_MAX_FRAME_SIZE default
  48. // http://http2.github.io/http2-spec/#rfc.section.6.5.2
  49. initialMaxFrameSize = 16384
  50. // NextProtoTLS is the NPN/ALPN protocol negotiated during
  51. // HTTP/2's TLS setup.
  52. NextProtoTLS = "h2"
  53. // http://http2.github.io/http2-spec/#SettingValues
  54. initialHeaderTableSize = 4096
  55. initialWindowSize = 65535 // 6.9.2 Initial Flow Control Window Size
  56. defaultMaxReadFrameSize = 1 << 20
  57. )
  58. var (
  59. clientPreface = []byte(ClientPreface)
  60. )
  61. type streamState int
  62. const (
  63. stateIdle streamState = iota
  64. stateOpen
  65. stateHalfClosedLocal
  66. stateHalfClosedRemote
  67. stateResvLocal
  68. stateResvRemote
  69. stateClosed
  70. )
  71. var stateName = [...]string{
  72. stateIdle: "Idle",
  73. stateOpen: "Open",
  74. stateHalfClosedLocal: "HalfClosedLocal",
  75. stateHalfClosedRemote: "HalfClosedRemote",
  76. stateResvLocal: "ResvLocal",
  77. stateResvRemote: "ResvRemote",
  78. stateClosed: "Closed",
  79. }
  80. func (st streamState) String() string {
  81. return stateName[st]
  82. }
  83. // Setting is a setting parameter: which setting it is, and its value.
  84. type Setting struct {
  85. // ID is which setting is being set.
  86. // See http://http2.github.io/http2-spec/#SettingValues
  87. ID SettingID
  88. // Val is the value.
  89. Val uint32
  90. }
  91. func (s Setting) String() string {
  92. return fmt.Sprintf("[%v = %d]", s.ID, s.Val)
  93. }
  94. // Valid reports whether the setting is valid.
  95. func (s Setting) Valid() error {
  96. // Limits and error codes from 6.5.2 Defined SETTINGS Parameters
  97. switch s.ID {
  98. case SettingEnablePush:
  99. if s.Val != 1 && s.Val != 0 {
  100. return ConnectionError(ErrCodeProtocol)
  101. }
  102. case SettingInitialWindowSize:
  103. if s.Val > 1<<31-1 {
  104. return ConnectionError(ErrCodeFlowControl)
  105. }
  106. case SettingMaxFrameSize:
  107. if s.Val < 16384 || s.Val > 1<<24-1 {
  108. return ConnectionError(ErrCodeProtocol)
  109. }
  110. }
  111. return nil
  112. }
  113. // A SettingID is an HTTP/2 setting as defined in
  114. // http://http2.github.io/http2-spec/#iana-settings
  115. type SettingID uint16
  116. const (
  117. SettingHeaderTableSize SettingID = 0x1
  118. SettingEnablePush SettingID = 0x2
  119. SettingMaxConcurrentStreams SettingID = 0x3
  120. SettingInitialWindowSize SettingID = 0x4
  121. SettingMaxFrameSize SettingID = 0x5
  122. SettingMaxHeaderListSize SettingID = 0x6
  123. )
  124. var settingName = map[SettingID]string{
  125. SettingHeaderTableSize: "HEADER_TABLE_SIZE",
  126. SettingEnablePush: "ENABLE_PUSH",
  127. SettingMaxConcurrentStreams: "MAX_CONCURRENT_STREAMS",
  128. SettingInitialWindowSize: "INITIAL_WINDOW_SIZE",
  129. SettingMaxFrameSize: "MAX_FRAME_SIZE",
  130. SettingMaxHeaderListSize: "MAX_HEADER_LIST_SIZE",
  131. }
  132. func (s SettingID) String() string {
  133. if v, ok := settingName[s]; ok {
  134. return v
  135. }
  136. return fmt.Sprintf("UNKNOWN_SETTING_%d", uint16(s))
  137. }
  138. var (
  139. errInvalidHeaderFieldName = errors.New("http2: invalid header field name")
  140. errInvalidHeaderFieldValue = errors.New("http2: invalid header field value")
  141. )
  142. // validHeaderFieldName reports whether v is a valid header field name (key).
  143. // RFC 7230 says:
  144. // header-field = field-name ":" OWS field-value OWS
  145. // field-name = token
  146. // tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." /
  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 validHeaderFieldName(v string) bool {
  154. if len(v) == 0 {
  155. return false
  156. }
  157. for _, r := range v {
  158. if int(r) >= len(isTokenTable) || ('A' <= r && r <= 'Z') {
  159. return false
  160. }
  161. if !isTokenTable[byte(r)] {
  162. return false
  163. }
  164. }
  165. return true
  166. }
  167. // validHeaderFieldValue reports whether v is a valid header field value.
  168. //
  169. // RFC 7230 says:
  170. // field-value = *( field-content / obs-fold )
  171. // obj-fold = N/A to http2, and deprecated
  172. // field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
  173. // field-vchar = VCHAR / obs-text
  174. // obs-text = %x80-FF
  175. // VCHAR = "any visible [USASCII] character"
  176. //
  177. // http2 further says: "Similarly, HTTP/2 allows header field values
  178. // that are not valid. While most of the values that can be encoded
  179. // will not alter header field parsing, carriage return (CR, ASCII
  180. // 0xd), line feed (LF, ASCII 0xa), and the zero character (NUL, ASCII
  181. // 0x0) might be exploited by an attacker if they are translated
  182. // verbatim. Any request or response that contains a character not
  183. // permitted in a header field value MUST be treated as malformed
  184. // (Section 8.1.2.6). Valid characters are defined by the
  185. // field-content ABNF rule in Section 3.2 of [RFC7230]."
  186. //
  187. // This function does not (yet?) properly handle the rejection of
  188. // strings that begin or end with SP or HTAB.
  189. func validHeaderFieldValue(v string) bool {
  190. for i := 0; i < len(v); i++ {
  191. if b := v[i]; b < ' ' && b != '\t' || b == 0x7f {
  192. return false
  193. }
  194. }
  195. return true
  196. }
  197. var httpCodeStringCommon = map[int]string{} // n -> strconv.Itoa(n)
  198. func init() {
  199. for i := 100; i <= 999; i++ {
  200. if v := http.StatusText(i); v != "" {
  201. httpCodeStringCommon[i] = strconv.Itoa(i)
  202. }
  203. }
  204. }
  205. func httpCodeString(code int) string {
  206. if s, ok := httpCodeStringCommon[code]; ok {
  207. return s
  208. }
  209. return strconv.Itoa(code)
  210. }
  211. // from pkg io
  212. type stringWriter interface {
  213. WriteString(s string) (n int, err error)
  214. }
  215. // A gate lets two goroutines coordinate their activities.
  216. type gate chan struct{}
  217. func (g gate) Done() { g <- struct{}{} }
  218. func (g gate) Wait() { <-g }
  219. // A closeWaiter is like a sync.WaitGroup but only goes 1 to 0 (open to closed).
  220. type closeWaiter chan struct{}
  221. // Init makes a closeWaiter usable.
  222. // It exists because so a closeWaiter value can be placed inside a
  223. // larger struct and have the Mutex and Cond's memory in the same
  224. // allocation.
  225. func (cw *closeWaiter) Init() {
  226. *cw = make(chan struct{})
  227. }
  228. // Close marks the closeWaiter as closed and unblocks any waiters.
  229. func (cw closeWaiter) Close() {
  230. close(cw)
  231. }
  232. // Wait waits for the closeWaiter to become closed.
  233. func (cw closeWaiter) Wait() {
  234. <-cw
  235. }
  236. // bufferedWriter is a buffered writer that writes to w.
  237. // Its buffered writer is lazily allocated as needed, to minimize
  238. // idle memory usage with many connections.
  239. type bufferedWriter struct {
  240. w io.Writer // immutable
  241. bw *bufio.Writer // non-nil when data is buffered
  242. }
  243. func newBufferedWriter(w io.Writer) *bufferedWriter {
  244. return &bufferedWriter{w: w}
  245. }
  246. var bufWriterPool = sync.Pool{
  247. New: func() interface{} {
  248. // TODO: pick something better? this is a bit under
  249. // (3 x typical 1500 byte MTU) at least.
  250. return bufio.NewWriterSize(nil, 4<<10)
  251. },
  252. }
  253. func (w *bufferedWriter) Write(p []byte) (n int, err error) {
  254. if w.bw == nil {
  255. bw := bufWriterPool.Get().(*bufio.Writer)
  256. bw.Reset(w.w)
  257. w.bw = bw
  258. }
  259. return w.bw.Write(p)
  260. }
  261. func (w *bufferedWriter) Flush() error {
  262. bw := w.bw
  263. if bw == nil {
  264. return nil
  265. }
  266. err := bw.Flush()
  267. bw.Reset(nil)
  268. bufWriterPool.Put(bw)
  269. w.bw = nil
  270. return err
  271. }
  272. func mustUint31(v int32) uint32 {
  273. if v < 0 || v > 2147483647 {
  274. panic("out of range")
  275. }
  276. return uint32(v)
  277. }
  278. // bodyAllowedForStatus reports whether a given response status code
  279. // permits a body. See RFC2616, section 4.4.
  280. func bodyAllowedForStatus(status int) bool {
  281. switch {
  282. case status >= 100 && status <= 199:
  283. return false
  284. case status == 204:
  285. return false
  286. case status == 304:
  287. return false
  288. }
  289. return true
  290. }
  291. type httpError struct {
  292. msg string
  293. timeout bool
  294. }
  295. func (e *httpError) Error() string { return e.msg }
  296. func (e *httpError) Timeout() bool { return e.timeout }
  297. func (e *httpError) Temporary() bool { return true }
  298. var errTimeout error = &httpError{msg: "http2: timeout awaiting response headers", timeout: true}
  299. var isTokenTable = [127]bool{
  300. '!': true,
  301. '#': true,
  302. '$': true,
  303. '%': true,
  304. '&': true,
  305. '\'': true,
  306. '*': true,
  307. '+': true,
  308. '-': true,
  309. '.': true,
  310. '0': true,
  311. '1': true,
  312. '2': true,
  313. '3': true,
  314. '4': true,
  315. '5': true,
  316. '6': true,
  317. '7': true,
  318. '8': true,
  319. '9': true,
  320. 'A': true,
  321. 'B': true,
  322. 'C': true,
  323. 'D': true,
  324. 'E': true,
  325. 'F': true,
  326. 'G': true,
  327. 'H': true,
  328. 'I': true,
  329. 'J': true,
  330. 'K': true,
  331. 'L': true,
  332. 'M': true,
  333. 'N': true,
  334. 'O': true,
  335. 'P': true,
  336. 'Q': true,
  337. 'R': true,
  338. 'S': true,
  339. 'T': true,
  340. 'U': true,
  341. 'W': true,
  342. 'V': true,
  343. 'X': true,
  344. 'Y': true,
  345. 'Z': true,
  346. '^': true,
  347. '_': true,
  348. '`': true,
  349. 'a': true,
  350. 'b': true,
  351. 'c': true,
  352. 'd': true,
  353. 'e': true,
  354. 'f': true,
  355. 'g': true,
  356. 'h': true,
  357. 'i': true,
  358. 'j': true,
  359. 'k': true,
  360. 'l': true,
  361. 'm': true,
  362. 'n': true,
  363. 'o': true,
  364. 'p': true,
  365. 'q': true,
  366. 'r': true,
  367. 's': true,
  368. 't': true,
  369. 'u': true,
  370. 'v': true,
  371. 'w': true,
  372. 'x': true,
  373. 'y': true,
  374. 'z': true,
  375. '|': true,
  376. '~': true,
  377. }