http2.go 9.8 KB

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